ieee1394: sbp2: update comment on things to do
[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 (usually storage devices) as regular
33  * SCSI devices. E.g. mount /dev/sda1, fdisk, mkfs, etc..
34  *
35  * See http://www.t10.org/drafts.htm#sbp2 for the final draft of the SBP-2
36  * specification and for where to purchase the official standard.
37  *
38  * TODO:
39  *   - look into possible improvements of the SCSI error handlers
40  *   - handle Unit_Characteristics.mgt_ORB_timeout and .ORB_size
41  *   - handle Logical_Unit_Number.ordered
42  *   - handle src == 1 in status blocks
43  *   - reimplement the DMA mapping in absence of physical DMA so that
44  *     bus_to_virt is no longer required
45  *   - debug the handling of absent physical DMA
46  *   - replace CONFIG_IEEE1394_SBP2_PHYS_DMA by automatic detection
47  *     (this is easy but depends on the previous two TODO items)
48  *   - make the parameter serialize_io configurable per device
49  *   - move all requests to fetch agent registers into non-atomic context,
50  *     replace all usages of sbp2util_node_write_no_wait by true transactions
51  *   - convert to generic DMA mapping API to eliminate dependency on PCI
52  * Grep for inline FIXME comments below.
53  */
54
55 #include <linux/blkdev.h>
56 #include <linux/compiler.h>
57 #include <linux/delay.h>
58 #include <linux/device.h>
59 #include <linux/dma-mapping.h>
60 #include <linux/gfp.h>
61 #include <linux/init.h>
62 #include <linux/kernel.h>
63 #include <linux/list.h>
64 #include <linux/module.h>
65 #include <linux/moduleparam.h>
66 #include <linux/pci.h>
67 #include <linux/slab.h>
68 #include <linux/spinlock.h>
69 #include <linux/stat.h>
70 #include <linux/string.h>
71 #include <linux/stringify.h>
72 #include <linux/types.h>
73 #include <linux/wait.h>
74
75 #include <asm/byteorder.h>
76 #include <asm/errno.h>
77 #include <asm/param.h>
78 #include <asm/scatterlist.h>
79 #include <asm/system.h>
80 #include <asm/types.h>
81
82 #ifdef CONFIG_IEEE1394_SBP2_PHYS_DMA
83 #include <asm/io.h> /* for bus_to_virt */
84 #endif
85
86 #include <scsi/scsi.h>
87 #include <scsi/scsi_cmnd.h>
88 #include <scsi/scsi_dbg.h>
89 #include <scsi/scsi_device.h>
90 #include <scsi/scsi_host.h>
91
92 #include "csr1212.h"
93 #include "highlevel.h"
94 #include "hosts.h"
95 #include "ieee1394.h"
96 #include "ieee1394_core.h"
97 #include "ieee1394_hotplug.h"
98 #include "ieee1394_transactions.h"
99 #include "ieee1394_types.h"
100 #include "nodemgr.h"
101 #include "sbp2.h"
102
103 /*
104  * Module load parameter definitions
105  */
106
107 /*
108  * Change max_speed on module load if you have a bad IEEE-1394
109  * controller that has trouble running 2KB packets at 400mb.
110  *
111  * NOTE: On certain OHCI parts I have seen short packets on async transmit
112  * (probably due to PCI latency/throughput issues with the part). You can
113  * bump down the speed if you are running into problems.
114  */
115 static int sbp2_max_speed = IEEE1394_SPEED_MAX;
116 module_param_named(max_speed, sbp2_max_speed, int, 0644);
117 MODULE_PARM_DESC(max_speed, "Force max speed "
118                  "(3 = 800Mb/s, 2 = 400Mb/s, 1 = 200Mb/s, 0 = 100Mb/s)");
119
120 /*
121  * Set serialize_io to 1 if you'd like only one scsi command sent
122  * down to us at a time (debugging). This might be necessary for very
123  * badly behaved sbp2 devices.
124  */
125 static int sbp2_serialize_io = 1;
126 module_param_named(serialize_io, sbp2_serialize_io, int, 0444);
127 MODULE_PARM_DESC(serialize_io, "Serialize I/O coming from scsi drivers "
128                  "(default = 1, faster = 0)");
129
130 /*
131  * Bump up max_sectors if you'd like to support very large sized
132  * transfers. Please note that some older sbp2 bridge chips are broken for
133  * transfers greater or equal to 128KB.  Default is a value of 255
134  * sectors, or just under 128KB (at 512 byte sector size). I can note that
135  * the Oxsemi sbp2 chipsets have no problems supporting very large
136  * transfer sizes.
137  */
138 static int sbp2_max_sectors = SBP2_MAX_SECTORS;
139 module_param_named(max_sectors, sbp2_max_sectors, int, 0444);
140 MODULE_PARM_DESC(max_sectors, "Change max sectors per I/O supported "
141                  "(default = " __stringify(SBP2_MAX_SECTORS) ")");
142
143 /*
144  * Exclusive login to sbp2 device? In most cases, the sbp2 driver should
145  * do an exclusive login, as it's generally unsafe to have two hosts
146  * talking to a single sbp2 device at the same time (filesystem coherency,
147  * etc.). If you're running an sbp2 device that supports multiple logins,
148  * and you're either running read-only filesystems or some sort of special
149  * filesystem supporting multiple hosts, e.g. OpenGFS, Oracle Cluster
150  * File System, or Lustre, then set exclusive_login to zero.
151  *
152  * So far only bridges from Oxford Semiconductor are known to support
153  * concurrent logins. Depending on firmware, four or two concurrent logins
154  * are possible on OXFW911 and newer Oxsemi bridges.
155  */
156 static int sbp2_exclusive_login = 1;
157 module_param_named(exclusive_login, sbp2_exclusive_login, int, 0644);
158 MODULE_PARM_DESC(exclusive_login, "Exclusive login to sbp2 device "
159                  "(default = 1)");
160
161 /*
162  * If any of the following workarounds is required for your device to work,
163  * please submit the kernel messages logged by sbp2 to the linux1394-devel
164  * mailing list.
165  *
166  * - 128kB max transfer
167  *   Limit transfer size. Necessary for some old bridges.
168  *
169  * - 36 byte inquiry
170  *   When scsi_mod probes the device, let the inquiry command look like that
171  *   from MS Windows.
172  *
173  * - skip mode page 8
174  *   Suppress sending of mode_sense for mode page 8 if the device pretends to
175  *   support the SCSI Primary Block commands instead of Reduced Block Commands.
176  *
177  * - fix capacity
178  *   Tell sd_mod to correct the last sector number reported by read_capacity.
179  *   Avoids access beyond actual disk limits on devices with an off-by-one bug.
180  *   Don't use this with devices which don't have this bug.
181  *
182  * - override internal blacklist
183  *   Instead of adding to the built-in blacklist, use only the workarounds
184  *   specified in the module load parameter.
185  *   Useful if a blacklist entry interfered with a non-broken device.
186  */
187 static int sbp2_default_workarounds;
188 module_param_named(workarounds, sbp2_default_workarounds, int, 0644);
189 MODULE_PARM_DESC(workarounds, "Work around device bugs (default = 0"
190         ", 128kB max transfer = " __stringify(SBP2_WORKAROUND_128K_MAX_TRANS)
191         ", 36 byte inquiry = "    __stringify(SBP2_WORKAROUND_INQUIRY_36)
192         ", skip mode page 8 = "   __stringify(SBP2_WORKAROUND_MODE_SENSE_8)
193         ", fix capacity = "       __stringify(SBP2_WORKAROUND_FIX_CAPACITY)
194         ", override internal blacklist = " __stringify(SBP2_WORKAROUND_OVERRIDE)
195         ", or a combination)");
196
197
198 #define SBP2_INFO(fmt, args...) HPSB_INFO("sbp2: "fmt, ## args)
199 #define SBP2_ERR(fmt, args...)  HPSB_ERR("sbp2: "fmt, ## args)
200
201 /*
202  * Globals
203  */
204 static void sbp2scsi_complete_all_commands(struct sbp2_lu *, u32);
205 static void sbp2scsi_complete_command(struct sbp2_lu *, u32, struct scsi_cmnd *,
206                                       void (*)(struct scsi_cmnd *));
207 static struct sbp2_lu *sbp2_alloc_device(struct unit_directory *);
208 static int sbp2_start_device(struct sbp2_lu *);
209 static void sbp2_remove_device(struct sbp2_lu *);
210 static int sbp2_login_device(struct sbp2_lu *);
211 static int sbp2_reconnect_device(struct sbp2_lu *);
212 static int sbp2_logout_device(struct sbp2_lu *);
213 static void sbp2_host_reset(struct hpsb_host *);
214 static int sbp2_handle_status_write(struct hpsb_host *, int, int, quadlet_t *,
215                                     u64, size_t, u16);
216 static int sbp2_agent_reset(struct sbp2_lu *, int);
217 static void sbp2_parse_unit_directory(struct sbp2_lu *,
218                                       struct unit_directory *);
219 static int sbp2_set_busy_timeout(struct sbp2_lu *);
220 static int sbp2_max_speed_and_size(struct sbp2_lu *);
221
222
223 static const u8 sbp2_speedto_max_payload[] = { 0x7, 0x8, 0x9, 0xA, 0xB, 0xC };
224
225 static struct hpsb_highlevel sbp2_highlevel = {
226         .name           = SBP2_DEVICE_NAME,
227         .host_reset     = sbp2_host_reset,
228 };
229
230 static struct hpsb_address_ops sbp2_ops = {
231         .write          = sbp2_handle_status_write
232 };
233
234 #ifdef CONFIG_IEEE1394_SBP2_PHYS_DMA
235 static int sbp2_handle_physdma_write(struct hpsb_host *, int, int, quadlet_t *,
236                                      u64, size_t, u16);
237 static int sbp2_handle_physdma_read(struct hpsb_host *, int, quadlet_t *, u64,
238                                     size_t, u16);
239
240 static struct hpsb_address_ops sbp2_physdma_ops = {
241         .read           = sbp2_handle_physdma_read,
242         .write          = sbp2_handle_physdma_write,
243 };
244 #endif
245
246
247 /*
248  * Interface to driver core and IEEE 1394 core
249  */
250 static struct ieee1394_device_id sbp2_id_table[] = {
251         {
252          .match_flags   = IEEE1394_MATCH_SPECIFIER_ID | IEEE1394_MATCH_VERSION,
253          .specifier_id  = SBP2_UNIT_SPEC_ID_ENTRY & 0xffffff,
254          .version       = SBP2_SW_VERSION_ENTRY & 0xffffff},
255         {}
256 };
257 MODULE_DEVICE_TABLE(ieee1394, sbp2_id_table);
258
259 static int sbp2_probe(struct device *);
260 static int sbp2_remove(struct device *);
261 static int sbp2_update(struct unit_directory *);
262
263 static struct hpsb_protocol_driver sbp2_driver = {
264         .name           = "SBP2 Driver",
265         .id_table       = sbp2_id_table,
266         .update         = sbp2_update,
267         .driver         = {
268                 .name           = SBP2_DEVICE_NAME,
269                 .bus            = &ieee1394_bus_type,
270                 .probe          = sbp2_probe,
271                 .remove         = sbp2_remove,
272         },
273 };
274
275
276 /*
277  * Interface to SCSI core
278  */
279 static int sbp2scsi_queuecommand(struct scsi_cmnd *,
280                                  void (*)(struct scsi_cmnd *));
281 static int sbp2scsi_abort(struct scsi_cmnd *);
282 static int sbp2scsi_reset(struct scsi_cmnd *);
283 static int sbp2scsi_slave_alloc(struct scsi_device *);
284 static int sbp2scsi_slave_configure(struct scsi_device *);
285 static void sbp2scsi_slave_destroy(struct scsi_device *);
286 static ssize_t sbp2_sysfs_ieee1394_id_show(struct device *,
287                                            struct device_attribute *, char *);
288
289 static DEVICE_ATTR(ieee1394_id, S_IRUGO, sbp2_sysfs_ieee1394_id_show, NULL);
290
291 static struct device_attribute *sbp2_sysfs_sdev_attrs[] = {
292         &dev_attr_ieee1394_id,
293         NULL
294 };
295
296 static struct scsi_host_template sbp2_shost_template = {
297         .module                  = THIS_MODULE,
298         .name                    = "SBP-2 IEEE-1394",
299         .proc_name               = SBP2_DEVICE_NAME,
300         .queuecommand            = sbp2scsi_queuecommand,
301         .eh_abort_handler        = sbp2scsi_abort,
302         .eh_device_reset_handler = sbp2scsi_reset,
303         .slave_alloc             = sbp2scsi_slave_alloc,
304         .slave_configure         = sbp2scsi_slave_configure,
305         .slave_destroy           = sbp2scsi_slave_destroy,
306         .this_id                 = -1,
307         .sg_tablesize            = SG_ALL,
308         .use_clustering          = ENABLE_CLUSTERING,
309         .cmd_per_lun             = SBP2_MAX_CMDS,
310         .can_queue               = SBP2_MAX_CMDS,
311         .emulated                = 1,
312         .sdev_attrs              = sbp2_sysfs_sdev_attrs,
313 };
314
315
316 /*
317  * List of devices with known bugs.
318  *
319  * The firmware_revision field, masked with 0xffff00, is the best indicator
320  * for the type of bridge chip of a device.  It yields a few false positives
321  * but this did not break correctly behaving devices so far.
322  */
323 static const struct {
324         u32 firmware_revision;
325         u32 model_id;
326         unsigned workarounds;
327 } sbp2_workarounds_table[] = {
328         /* DViCO Momobay CX-1 with TSB42AA9 bridge */ {
329                 .firmware_revision      = 0x002800,
330                 .model_id               = 0x001010,
331                 .workarounds            = SBP2_WORKAROUND_INQUIRY_36 |
332                                           SBP2_WORKAROUND_MODE_SENSE_8,
333         },
334         /* Initio bridges, actually only needed for some older ones */ {
335                 .firmware_revision      = 0x000200,
336                 .workarounds            = SBP2_WORKAROUND_INQUIRY_36,
337         },
338         /* Symbios bridge */ {
339                 .firmware_revision      = 0xa0b800,
340                 .workarounds            = SBP2_WORKAROUND_128K_MAX_TRANS,
341         },
342         /*
343          * Note about the following Apple iPod blacklist entries:
344          *
345          * There are iPods (2nd gen, 3rd gen) with model_id==0.  Since our
346          * matching logic treats 0 as a wildcard, we cannot match this ID
347          * without rewriting the matching routine.  Fortunately these iPods
348          * do not feature the read_capacity bug according to one report.
349          * Read_capacity behaviour as well as model_id could change due to
350          * Apple-supplied firmware updates though.
351          */
352         /* iPod 4th generation */ {
353                 .firmware_revision      = 0x0a2700,
354                 .model_id               = 0x000021,
355                 .workarounds            = SBP2_WORKAROUND_FIX_CAPACITY,
356         },
357         /* iPod mini */ {
358                 .firmware_revision      = 0x0a2700,
359                 .model_id               = 0x000023,
360                 .workarounds            = SBP2_WORKAROUND_FIX_CAPACITY,
361         },
362         /* iPod Photo */ {
363                 .firmware_revision      = 0x0a2700,
364                 .model_id               = 0x00007e,
365                 .workarounds            = SBP2_WORKAROUND_FIX_CAPACITY,
366         }
367 };
368
369 /**************************************
370  * General utility functions
371  **************************************/
372
373 #ifndef __BIG_ENDIAN
374 /*
375  * Converts a buffer from be32 to cpu byte ordering. Length is in bytes.
376  */
377 static inline void sbp2util_be32_to_cpu_buffer(void *buffer, int length)
378 {
379         u32 *temp = buffer;
380
381         for (length = (length >> 2); length--; )
382                 temp[length] = be32_to_cpu(temp[length]);
383 }
384
385 /*
386  * Converts a buffer from cpu to be32 byte ordering. Length is in bytes.
387  */
388 static inline void sbp2util_cpu_to_be32_buffer(void *buffer, int length)
389 {
390         u32 *temp = buffer;
391
392         for (length = (length >> 2); length--; )
393                 temp[length] = cpu_to_be32(temp[length]);
394 }
395 #else /* BIG_ENDIAN */
396 /* Why waste the cpu cycles? */
397 #define sbp2util_be32_to_cpu_buffer(x,y) do {} while (0)
398 #define sbp2util_cpu_to_be32_buffer(x,y) do {} while (0)
399 #endif
400
401 static DECLARE_WAIT_QUEUE_HEAD(sbp2_access_wq);
402
403 /*
404  * Waits for completion of an SBP-2 access request.
405  * Returns nonzero if timed out or prematurely interrupted.
406  */
407 static int sbp2util_access_timeout(struct sbp2_lu *lu, int timeout)
408 {
409         long leftover;
410
411         leftover = wait_event_interruptible_timeout(
412                         sbp2_access_wq, lu->access_complete, timeout);
413         lu->access_complete = 0;
414         return leftover <= 0;
415 }
416
417 static void sbp2_free_packet(void *packet)
418 {
419         hpsb_free_tlabel(packet);
420         hpsb_free_packet(packet);
421 }
422
423 /*
424  * This is much like hpsb_node_write(), except it ignores the response
425  * subaction and returns immediately. Can be used from atomic context.
426  */
427 static int sbp2util_node_write_no_wait(struct node_entry *ne, u64 addr,
428                                        quadlet_t *buf, size_t len)
429 {
430         struct hpsb_packet *packet;
431
432         packet = hpsb_make_writepacket(ne->host, ne->nodeid, addr, buf, len);
433         if (!packet)
434                 return -ENOMEM;
435
436         hpsb_set_packet_complete_task(packet, sbp2_free_packet, packet);
437         hpsb_node_fill_packet(ne, packet);
438         if (hpsb_send_packet(packet) < 0) {
439                 sbp2_free_packet(packet);
440                 return -EIO;
441         }
442         return 0;
443 }
444
445 static void sbp2util_notify_fetch_agent(struct sbp2_lu *lu, u64 offset,
446                                         quadlet_t *data, size_t len)
447 {
448         /* There is a small window after a bus reset within which the node
449          * entry's generation is current but the reconnect wasn't completed. */
450         if (unlikely(atomic_read(&lu->state) == SBP2LU_STATE_IN_RESET))
451                 return;
452
453         if (hpsb_node_write(lu->ne, lu->command_block_agent_addr + offset,
454                             data, len))
455                 SBP2_ERR("sbp2util_notify_fetch_agent failed.");
456
457         /* Now accept new SCSI commands, unless a bus reset happended during
458          * hpsb_node_write. */
459         if (likely(atomic_read(&lu->state) != SBP2LU_STATE_IN_RESET))
460                 scsi_unblock_requests(lu->shost);
461 }
462
463 static void sbp2util_write_orb_pointer(struct work_struct *work)
464 {
465         quadlet_t data[2];
466
467         data[0] = ORB_SET_NODE_ID((container_of(work, struct sbp2_lu, protocol_work))->hi->host->node_id);
468         data[1] = (container_of(work, struct sbp2_lu, protocol_work))->last_orb_dma;
469         sbp2util_cpu_to_be32_buffer(data, 8);
470         sbp2util_notify_fetch_agent(container_of(work, struct sbp2_lu, protocol_work), SBP2_ORB_POINTER_OFFSET, data, 8);
471 }
472
473 static void sbp2util_write_doorbell(struct work_struct *work)
474 {
475         sbp2util_notify_fetch_agent(container_of(work, struct sbp2_lu, protocol_work), SBP2_DOORBELL_OFFSET, NULL, 4);
476 }
477
478 static int sbp2util_create_command_orb_pool(struct sbp2_lu *lu)
479 {
480         struct sbp2_fwhost_info *hi = lu->hi;
481         int i;
482         unsigned long flags, orbs;
483         struct sbp2_command_info *cmd;
484
485         orbs = sbp2_serialize_io ? 2 : SBP2_MAX_CMDS;
486
487         spin_lock_irqsave(&lu->cmd_orb_lock, flags);
488         for (i = 0; i < orbs; i++) {
489                 cmd = kzalloc(sizeof(*cmd), GFP_ATOMIC);
490                 if (!cmd) {
491                         spin_unlock_irqrestore(&lu->cmd_orb_lock, flags);
492                         return -ENOMEM;
493                 }
494                 cmd->command_orb_dma = pci_map_single(hi->host->pdev,
495                                                 &cmd->command_orb,
496                                                 sizeof(struct sbp2_command_orb),
497                                                 PCI_DMA_TODEVICE);
498                 cmd->sge_dma = pci_map_single(hi->host->pdev,
499                                         &cmd->scatter_gather_element,
500                                         sizeof(cmd->scatter_gather_element),
501                                         PCI_DMA_BIDIRECTIONAL);
502                 INIT_LIST_HEAD(&cmd->list);
503                 list_add_tail(&cmd->list, &lu->cmd_orb_completed);
504         }
505         spin_unlock_irqrestore(&lu->cmd_orb_lock, flags);
506         return 0;
507 }
508
509 static void sbp2util_remove_command_orb_pool(struct sbp2_lu *lu)
510 {
511         struct hpsb_host *host = lu->hi->host;
512         struct list_head *lh, *next;
513         struct sbp2_command_info *cmd;
514         unsigned long flags;
515
516         spin_lock_irqsave(&lu->cmd_orb_lock, flags);
517         if (!list_empty(&lu->cmd_orb_completed))
518                 list_for_each_safe(lh, next, &lu->cmd_orb_completed) {
519                         cmd = list_entry(lh, struct sbp2_command_info, list);
520                         pci_unmap_single(host->pdev, cmd->command_orb_dma,
521                                          sizeof(struct sbp2_command_orb),
522                                          PCI_DMA_TODEVICE);
523                         pci_unmap_single(host->pdev, cmd->sge_dma,
524                                          sizeof(cmd->scatter_gather_element),
525                                          PCI_DMA_BIDIRECTIONAL);
526                         kfree(cmd);
527                 }
528         spin_unlock_irqrestore(&lu->cmd_orb_lock, flags);
529         return;
530 }
531
532 /*
533  * Finds the sbp2_command for a given outstanding command ORB.
534  * Only looks at the in-use list.
535  */
536 static struct sbp2_command_info *sbp2util_find_command_for_orb(
537                                 struct sbp2_lu *lu, dma_addr_t orb)
538 {
539         struct sbp2_command_info *cmd;
540         unsigned long flags;
541
542         spin_lock_irqsave(&lu->cmd_orb_lock, flags);
543         if (!list_empty(&lu->cmd_orb_inuse))
544                 list_for_each_entry(cmd, &lu->cmd_orb_inuse, list)
545                         if (cmd->command_orb_dma == orb) {
546                                 spin_unlock_irqrestore(
547                                                 &lu->cmd_orb_lock, flags);
548                                 return cmd;
549                         }
550         spin_unlock_irqrestore(&lu->cmd_orb_lock, flags);
551         return NULL;
552 }
553
554 /*
555  * Finds the sbp2_command for a given outstanding SCpnt.
556  * Only looks at the in-use list.
557  * Must be called with lu->cmd_orb_lock held.
558  */
559 static struct sbp2_command_info *sbp2util_find_command_for_SCpnt(
560                                 struct sbp2_lu *lu, void *SCpnt)
561 {
562         struct sbp2_command_info *cmd;
563
564         if (!list_empty(&lu->cmd_orb_inuse))
565                 list_for_each_entry(cmd, &lu->cmd_orb_inuse, list)
566                         if (cmd->Current_SCpnt == SCpnt)
567                                 return cmd;
568         return NULL;
569 }
570
571 static struct sbp2_command_info *sbp2util_allocate_command_orb(
572                                 struct sbp2_lu *lu,
573                                 struct scsi_cmnd *Current_SCpnt,
574                                 void (*Current_done)(struct scsi_cmnd *))
575 {
576         struct list_head *lh;
577         struct sbp2_command_info *cmd = NULL;
578         unsigned long flags;
579
580         spin_lock_irqsave(&lu->cmd_orb_lock, flags);
581         if (!list_empty(&lu->cmd_orb_completed)) {
582                 lh = lu->cmd_orb_completed.next;
583                 list_del(lh);
584                 cmd = list_entry(lh, struct sbp2_command_info, list);
585                 cmd->Current_done = Current_done;
586                 cmd->Current_SCpnt = Current_SCpnt;
587                 list_add_tail(&cmd->list, &lu->cmd_orb_inuse);
588         } else
589                 SBP2_ERR("%s: no orbs available", __FUNCTION__);
590         spin_unlock_irqrestore(&lu->cmd_orb_lock, flags);
591         return cmd;
592 }
593
594 static void sbp2util_free_command_dma(struct sbp2_command_info *cmd)
595 {
596         struct sbp2_lu *lu = (struct sbp2_lu *)
597                         cmd->Current_SCpnt->device->host->hostdata[0];
598         struct hpsb_host *host;
599
600         if (!lu) {
601                 SBP2_ERR("%s: lu == NULL", __FUNCTION__);
602                 return;
603         }
604
605         host = lu->ud->ne->host;
606
607         if (cmd->cmd_dma) {
608                 if (cmd->dma_type == CMD_DMA_SINGLE)
609                         pci_unmap_single(host->pdev, cmd->cmd_dma,
610                                          cmd->dma_size, cmd->dma_dir);
611                 else if (cmd->dma_type == CMD_DMA_PAGE)
612                         pci_unmap_page(host->pdev, cmd->cmd_dma,
613                                        cmd->dma_size, cmd->dma_dir);
614                 /* XXX: Check for CMD_DMA_NONE bug */
615                 cmd->dma_type = CMD_DMA_NONE;
616                 cmd->cmd_dma = 0;
617         }
618
619         if (cmd->sge_buffer) {
620                 pci_unmap_sg(host->pdev, cmd->sge_buffer,
621                              cmd->dma_size, cmd->dma_dir);
622                 cmd->sge_buffer = NULL;
623         }
624 }
625
626 /*
627  * This function moves a command to the completed orb list.
628  * Must be called with lu->cmd_orb_lock held.
629  */
630 static void sbp2util_mark_command_completed(
631                 struct sbp2_lu *lu,
632                 struct sbp2_command_info *cmd)
633 {
634         sbp2util_free_command_dma(cmd);
635         list_move_tail(&cmd->list, &lu->cmd_orb_completed);
636 }
637
638 /*
639  * Is lu valid? Is the 1394 node still present?
640  */
641 static inline int sbp2util_node_is_available(struct sbp2_lu *lu)
642 {
643         return lu && lu->ne && !lu->ne->in_limbo;
644 }
645
646 /*********************************************
647  * IEEE-1394 core driver stack related section
648  *********************************************/
649
650 static int sbp2_probe(struct device *dev)
651 {
652         struct unit_directory *ud;
653         struct sbp2_lu *lu;
654
655         ud = container_of(dev, struct unit_directory, device);
656
657         /* Don't probe UD's that have the LUN flag. We'll probe the LUN(s)
658          * instead. */
659         if (ud->flags & UNIT_DIRECTORY_HAS_LUN_DIRECTORY)
660                 return -ENODEV;
661
662         lu = sbp2_alloc_device(ud);
663         if (!lu)
664                 return -ENOMEM;
665
666         sbp2_parse_unit_directory(lu, ud);
667         return sbp2_start_device(lu);
668 }
669
670 static int sbp2_remove(struct device *dev)
671 {
672         struct unit_directory *ud;
673         struct sbp2_lu *lu;
674         struct scsi_device *sdev;
675
676         ud = container_of(dev, struct unit_directory, device);
677         lu = ud->device.driver_data;
678         if (!lu)
679                 return 0;
680
681         if (lu->shost) {
682                 /* Get rid of enqueued commands if there is no chance to
683                  * send them. */
684                 if (!sbp2util_node_is_available(lu))
685                         sbp2scsi_complete_all_commands(lu, DID_NO_CONNECT);
686                 /* scsi_remove_device() may trigger shutdown functions of SCSI
687                  * highlevel drivers which would deadlock if blocked. */
688                 atomic_set(&lu->state, SBP2LU_STATE_IN_SHUTDOWN);
689                 scsi_unblock_requests(lu->shost);
690         }
691         sdev = lu->sdev;
692         if (sdev) {
693                 lu->sdev = NULL;
694                 scsi_remove_device(sdev);
695         }
696
697         sbp2_logout_device(lu);
698         sbp2_remove_device(lu);
699
700         return 0;
701 }
702
703 static int sbp2_update(struct unit_directory *ud)
704 {
705         struct sbp2_lu *lu = ud->device.driver_data;
706
707         if (sbp2_reconnect_device(lu)) {
708                 /* Reconnect has failed. Perhaps we didn't reconnect fast
709                  * enough. Try a regular login, but first log out just in
710                  * case of any weirdness. */
711                 sbp2_logout_device(lu);
712
713                 if (sbp2_login_device(lu)) {
714                         /* Login failed too, just fail, and the backend
715                          * will call our sbp2_remove for us */
716                         SBP2_ERR("Failed to reconnect to sbp2 device!");
717                         return -EBUSY;
718                 }
719         }
720
721         sbp2_set_busy_timeout(lu);
722         sbp2_agent_reset(lu, 1);
723         sbp2_max_speed_and_size(lu);
724
725         /* Complete any pending commands with busy (so they get retried)
726          * and remove them from our queue. */
727         sbp2scsi_complete_all_commands(lu, DID_BUS_BUSY);
728
729         /* Accept new commands unless there was another bus reset in the
730          * meantime. */
731         if (hpsb_node_entry_valid(lu->ne)) {
732                 atomic_set(&lu->state, SBP2LU_STATE_RUNNING);
733                 scsi_unblock_requests(lu->shost);
734         }
735         return 0;
736 }
737
738 static struct sbp2_lu *sbp2_alloc_device(struct unit_directory *ud)
739 {
740         struct sbp2_fwhost_info *hi;
741         struct Scsi_Host *shost = NULL;
742         struct sbp2_lu *lu = NULL;
743
744         lu = kzalloc(sizeof(*lu), GFP_KERNEL);
745         if (!lu) {
746                 SBP2_ERR("failed to create lu");
747                 goto failed_alloc;
748         }
749
750         lu->ne = ud->ne;
751         lu->ud = ud;
752         lu->speed_code = IEEE1394_SPEED_100;
753         lu->max_payload_size = sbp2_speedto_max_payload[IEEE1394_SPEED_100];
754         lu->status_fifo_addr = CSR1212_INVALID_ADDR_SPACE;
755         INIT_LIST_HEAD(&lu->cmd_orb_inuse);
756         INIT_LIST_HEAD(&lu->cmd_orb_completed);
757         INIT_LIST_HEAD(&lu->lu_list);
758         spin_lock_init(&lu->cmd_orb_lock);
759         atomic_set(&lu->state, SBP2LU_STATE_RUNNING);
760         INIT_WORK(&lu->protocol_work, NULL);
761
762         ud->device.driver_data = lu;
763
764         hi = hpsb_get_hostinfo(&sbp2_highlevel, ud->ne->host);
765         if (!hi) {
766                 hi = hpsb_create_hostinfo(&sbp2_highlevel, ud->ne->host,
767                                           sizeof(*hi));
768                 if (!hi) {
769                         SBP2_ERR("failed to allocate hostinfo");
770                         goto failed_alloc;
771                 }
772                 hi->host = ud->ne->host;
773                 INIT_LIST_HEAD(&hi->logical_units);
774
775 #ifdef CONFIG_IEEE1394_SBP2_PHYS_DMA
776                 /* Handle data movement if physical dma is not
777                  * enabled or not supported on host controller */
778                 if (!hpsb_register_addrspace(&sbp2_highlevel, ud->ne->host,
779                                              &sbp2_physdma_ops,
780                                              0x0ULL, 0xfffffffcULL)) {
781                         SBP2_ERR("failed to register lower 4GB address range");
782                         goto failed_alloc;
783                 }
784 #endif
785         }
786
787         /* Prevent unloading of the 1394 host */
788         if (!try_module_get(hi->host->driver->owner)) {
789                 SBP2_ERR("failed to get a reference on 1394 host driver");
790                 goto failed_alloc;
791         }
792
793         lu->hi = hi;
794
795         list_add_tail(&lu->lu_list, &hi->logical_units);
796
797         /* Register the status FIFO address range. We could use the same FIFO
798          * for targets at different nodes. However we need different FIFOs per
799          * target in order to support multi-unit devices.
800          * The FIFO is located out of the local host controller's physical range
801          * but, if possible, within the posted write area. Status writes will
802          * then be performed as unified transactions. This slightly reduces
803          * bandwidth usage, and some Prolific based devices seem to require it.
804          */
805         lu->status_fifo_addr = hpsb_allocate_and_register_addrspace(
806                         &sbp2_highlevel, ud->ne->host, &sbp2_ops,
807                         sizeof(struct sbp2_status_block), sizeof(quadlet_t),
808                         ud->ne->host->low_addr_space, CSR1212_ALL_SPACE_END);
809         if (lu->status_fifo_addr == CSR1212_INVALID_ADDR_SPACE) {
810                 SBP2_ERR("failed to allocate status FIFO address range");
811                 goto failed_alloc;
812         }
813
814         shost = scsi_host_alloc(&sbp2_shost_template, sizeof(unsigned long));
815         if (!shost) {
816                 SBP2_ERR("failed to register scsi host");
817                 goto failed_alloc;
818         }
819
820         shost->hostdata[0] = (unsigned long)lu;
821
822         if (!scsi_add_host(shost, &ud->device)) {
823                 lu->shost = shost;
824                 return lu;
825         }
826
827         SBP2_ERR("failed to add scsi host");
828         scsi_host_put(shost);
829
830 failed_alloc:
831         sbp2_remove_device(lu);
832         return NULL;
833 }
834
835 static void sbp2_host_reset(struct hpsb_host *host)
836 {
837         struct sbp2_fwhost_info *hi;
838         struct sbp2_lu *lu;
839
840         hi = hpsb_get_hostinfo(&sbp2_highlevel, host);
841         if (!hi)
842                 return;
843         list_for_each_entry(lu, &hi->logical_units, lu_list)
844                 if (likely(atomic_read(&lu->state) !=
845                            SBP2LU_STATE_IN_SHUTDOWN)) {
846                         atomic_set(&lu->state, SBP2LU_STATE_IN_RESET);
847                         scsi_block_requests(lu->shost);
848                 }
849 }
850
851 static int sbp2_start_device(struct sbp2_lu *lu)
852 {
853         struct sbp2_fwhost_info *hi = lu->hi;
854         int error;
855
856         lu->login_response = pci_alloc_consistent(hi->host->pdev,
857                                      sizeof(struct sbp2_login_response),
858                                      &lu->login_response_dma);
859         if (!lu->login_response)
860                 goto alloc_fail;
861
862         lu->query_logins_orb = pci_alloc_consistent(hi->host->pdev,
863                                      sizeof(struct sbp2_query_logins_orb),
864                                      &lu->query_logins_orb_dma);
865         if (!lu->query_logins_orb)
866                 goto alloc_fail;
867
868         lu->query_logins_response = pci_alloc_consistent(hi->host->pdev,
869                                      sizeof(struct sbp2_query_logins_response),
870                                      &lu->query_logins_response_dma);
871         if (!lu->query_logins_response)
872                 goto alloc_fail;
873
874         lu->reconnect_orb = pci_alloc_consistent(hi->host->pdev,
875                                      sizeof(struct sbp2_reconnect_orb),
876                                      &lu->reconnect_orb_dma);
877         if (!lu->reconnect_orb)
878                 goto alloc_fail;
879
880         lu->logout_orb = pci_alloc_consistent(hi->host->pdev,
881                                      sizeof(struct sbp2_logout_orb),
882                                      &lu->logout_orb_dma);
883         if (!lu->logout_orb)
884                 goto alloc_fail;
885
886         lu->login_orb = pci_alloc_consistent(hi->host->pdev,
887                                      sizeof(struct sbp2_login_orb),
888                                      &lu->login_orb_dma);
889         if (!lu->login_orb)
890                 goto alloc_fail;
891
892         if (sbp2util_create_command_orb_pool(lu)) {
893                 SBP2_ERR("sbp2util_create_command_orb_pool failed!");
894                 sbp2_remove_device(lu);
895                 return -ENOMEM;
896         }
897
898         /* Wait a second before trying to log in. Previously logged in
899          * initiators need a chance to reconnect. */
900         if (msleep_interruptible(1000)) {
901                 sbp2_remove_device(lu);
902                 return -EINTR;
903         }
904
905         if (sbp2_login_device(lu)) {
906                 sbp2_remove_device(lu);
907                 return -EBUSY;
908         }
909
910         sbp2_set_busy_timeout(lu);
911         sbp2_agent_reset(lu, 1);
912         sbp2_max_speed_and_size(lu);
913
914         error = scsi_add_device(lu->shost, 0, lu->ud->id, 0);
915         if (error) {
916                 SBP2_ERR("scsi_add_device failed");
917                 sbp2_logout_device(lu);
918                 sbp2_remove_device(lu);
919                 return error;
920         }
921
922         return 0;
923
924 alloc_fail:
925         SBP2_ERR("Could not allocate memory for lu");
926         sbp2_remove_device(lu);
927         return -ENOMEM;
928 }
929
930 static void sbp2_remove_device(struct sbp2_lu *lu)
931 {
932         struct sbp2_fwhost_info *hi;
933
934         if (!lu)
935                 return;
936
937         hi = lu->hi;
938
939         if (lu->shost) {
940                 scsi_remove_host(lu->shost);
941                 scsi_host_put(lu->shost);
942         }
943         flush_scheduled_work();
944         sbp2util_remove_command_orb_pool(lu);
945
946         list_del(&lu->lu_list);
947
948         if (lu->login_response)
949                 pci_free_consistent(hi->host->pdev,
950                                     sizeof(struct sbp2_login_response),
951                                     lu->login_response,
952                                     lu->login_response_dma);
953         if (lu->login_orb)
954                 pci_free_consistent(hi->host->pdev,
955                                     sizeof(struct sbp2_login_orb),
956                                     lu->login_orb,
957                                     lu->login_orb_dma);
958         if (lu->reconnect_orb)
959                 pci_free_consistent(hi->host->pdev,
960                                     sizeof(struct sbp2_reconnect_orb),
961                                     lu->reconnect_orb,
962                                     lu->reconnect_orb_dma);
963         if (lu->logout_orb)
964                 pci_free_consistent(hi->host->pdev,
965                                     sizeof(struct sbp2_logout_orb),
966                                     lu->logout_orb,
967                                     lu->logout_orb_dma);
968         if (lu->query_logins_orb)
969                 pci_free_consistent(hi->host->pdev,
970                                     sizeof(struct sbp2_query_logins_orb),
971                                     lu->query_logins_orb,
972                                     lu->query_logins_orb_dma);
973         if (lu->query_logins_response)
974                 pci_free_consistent(hi->host->pdev,
975                                     sizeof(struct sbp2_query_logins_response),
976                                     lu->query_logins_response,
977                                     lu->query_logins_response_dma);
978
979         if (lu->status_fifo_addr != CSR1212_INVALID_ADDR_SPACE)
980                 hpsb_unregister_addrspace(&sbp2_highlevel, hi->host,
981                                           lu->status_fifo_addr);
982
983         lu->ud->device.driver_data = NULL;
984
985         if (hi)
986                 module_put(hi->host->driver->owner);
987
988         kfree(lu);
989 }
990
991 #ifdef CONFIG_IEEE1394_SBP2_PHYS_DMA
992 /*
993  * Deal with write requests on adapters which do not support physical DMA or
994  * have it switched off.
995  */
996 static int sbp2_handle_physdma_write(struct hpsb_host *host, int nodeid,
997                                      int destid, quadlet_t *data, u64 addr,
998                                      size_t length, u16 flags)
999 {
1000         memcpy(bus_to_virt((u32) addr), data, length);
1001         return RCODE_COMPLETE;
1002 }
1003
1004 /*
1005  * Deal with read requests on adapters which do not support physical DMA or
1006  * have it switched off.
1007  */
1008 static int sbp2_handle_physdma_read(struct hpsb_host *host, int nodeid,
1009                                     quadlet_t *data, u64 addr, size_t length,
1010                                     u16 flags)
1011 {
1012         memcpy(data, bus_to_virt((u32) addr), length);
1013         return RCODE_COMPLETE;
1014 }
1015 #endif
1016
1017 /**************************************
1018  * SBP-2 protocol related section
1019  **************************************/
1020
1021 static int sbp2_query_logins(struct sbp2_lu *lu)
1022 {
1023         struct sbp2_fwhost_info *hi = lu->hi;
1024         quadlet_t data[2];
1025         int max_logins;
1026         int active_logins;
1027
1028         lu->query_logins_orb->reserved1 = 0x0;
1029         lu->query_logins_orb->reserved2 = 0x0;
1030
1031         lu->query_logins_orb->query_response_lo = lu->query_logins_response_dma;
1032         lu->query_logins_orb->query_response_hi =
1033                         ORB_SET_NODE_ID(hi->host->node_id);
1034         lu->query_logins_orb->lun_misc =
1035                         ORB_SET_FUNCTION(SBP2_QUERY_LOGINS_REQUEST);
1036         lu->query_logins_orb->lun_misc |= ORB_SET_NOTIFY(1);
1037         lu->query_logins_orb->lun_misc |= ORB_SET_LUN(lu->lun);
1038
1039         lu->query_logins_orb->reserved_resp_length =
1040                 ORB_SET_QUERY_LOGINS_RESP_LENGTH(
1041                         sizeof(struct sbp2_query_logins_response));
1042
1043         lu->query_logins_orb->status_fifo_hi =
1044                 ORB_SET_STATUS_FIFO_HI(lu->status_fifo_addr, hi->host->node_id);
1045         lu->query_logins_orb->status_fifo_lo =
1046                 ORB_SET_STATUS_FIFO_LO(lu->status_fifo_addr);
1047
1048         sbp2util_cpu_to_be32_buffer(lu->query_logins_orb,
1049                                     sizeof(struct sbp2_query_logins_orb));
1050
1051         memset(lu->query_logins_response, 0,
1052                sizeof(struct sbp2_query_logins_response));
1053
1054         data[0] = ORB_SET_NODE_ID(hi->host->node_id);
1055         data[1] = lu->query_logins_orb_dma;
1056         sbp2util_cpu_to_be32_buffer(data, 8);
1057
1058         hpsb_node_write(lu->ne, lu->management_agent_addr, data, 8);
1059
1060         if (sbp2util_access_timeout(lu, 2*HZ)) {
1061                 SBP2_INFO("Error querying logins to SBP-2 device - timed out");
1062                 return -EIO;
1063         }
1064
1065         if (lu->status_block.ORB_offset_lo != lu->query_logins_orb_dma) {
1066                 SBP2_INFO("Error querying logins to SBP-2 device - timed out");
1067                 return -EIO;
1068         }
1069
1070         if (STATUS_TEST_RDS(lu->status_block.ORB_offset_hi_misc)) {
1071                 SBP2_INFO("Error querying logins to SBP-2 device - failed");
1072                 return -EIO;
1073         }
1074
1075         sbp2util_cpu_to_be32_buffer(lu->query_logins_response,
1076                                     sizeof(struct sbp2_query_logins_response));
1077
1078         max_logins = RESPONSE_GET_MAX_LOGINS(
1079                         lu->query_logins_response->length_max_logins);
1080         SBP2_INFO("Maximum concurrent logins supported: %d", max_logins);
1081
1082         active_logins = RESPONSE_GET_ACTIVE_LOGINS(
1083                         lu->query_logins_response->length_max_logins);
1084         SBP2_INFO("Number of active logins: %d", active_logins);
1085
1086         if (active_logins >= max_logins) {
1087                 return -EIO;
1088         }
1089
1090         return 0;
1091 }
1092
1093 static int sbp2_login_device(struct sbp2_lu *lu)
1094 {
1095         struct sbp2_fwhost_info *hi = lu->hi;
1096         quadlet_t data[2];
1097
1098         if (!lu->login_orb)
1099                 return -EIO;
1100
1101         if (!sbp2_exclusive_login && sbp2_query_logins(lu)) {
1102                 SBP2_INFO("Device does not support any more concurrent logins");
1103                 return -EIO;
1104         }
1105
1106         /* assume no password */
1107         lu->login_orb->password_hi = 0;
1108         lu->login_orb->password_lo = 0;
1109
1110         lu->login_orb->login_response_lo = lu->login_response_dma;
1111         lu->login_orb->login_response_hi = ORB_SET_NODE_ID(hi->host->node_id);
1112         lu->login_orb->lun_misc = ORB_SET_FUNCTION(SBP2_LOGIN_REQUEST);
1113
1114         /* one second reconnect time */
1115         lu->login_orb->lun_misc |= ORB_SET_RECONNECT(0);
1116         lu->login_orb->lun_misc |= ORB_SET_EXCLUSIVE(sbp2_exclusive_login);
1117         lu->login_orb->lun_misc |= ORB_SET_NOTIFY(1);
1118         lu->login_orb->lun_misc |= ORB_SET_LUN(lu->lun);
1119
1120         lu->login_orb->passwd_resp_lengths =
1121                 ORB_SET_LOGIN_RESP_LENGTH(sizeof(struct sbp2_login_response));
1122
1123         lu->login_orb->status_fifo_hi =
1124                 ORB_SET_STATUS_FIFO_HI(lu->status_fifo_addr, hi->host->node_id);
1125         lu->login_orb->status_fifo_lo =
1126                 ORB_SET_STATUS_FIFO_LO(lu->status_fifo_addr);
1127
1128         sbp2util_cpu_to_be32_buffer(lu->login_orb,
1129                                     sizeof(struct sbp2_login_orb));
1130
1131         memset(lu->login_response, 0, sizeof(struct sbp2_login_response));
1132
1133         data[0] = ORB_SET_NODE_ID(hi->host->node_id);
1134         data[1] = lu->login_orb_dma;
1135         sbp2util_cpu_to_be32_buffer(data, 8);
1136
1137         hpsb_node_write(lu->ne, lu->management_agent_addr, data, 8);
1138
1139         /* wait up to 20 seconds for login status */
1140         if (sbp2util_access_timeout(lu, 20*HZ)) {
1141                 SBP2_ERR("Error logging into SBP-2 device - timed out");
1142                 return -EIO;
1143         }
1144
1145         /* make sure that the returned status matches the login ORB */
1146         if (lu->status_block.ORB_offset_lo != lu->login_orb_dma) {
1147                 SBP2_ERR("Error logging into SBP-2 device - timed out");
1148                 return -EIO;
1149         }
1150
1151         if (STATUS_TEST_RDS(lu->status_block.ORB_offset_hi_misc)) {
1152                 SBP2_ERR("Error logging into SBP-2 device - failed");
1153                 return -EIO;
1154         }
1155
1156         sbp2util_cpu_to_be32_buffer(lu->login_response,
1157                                     sizeof(struct sbp2_login_response));
1158         lu->command_block_agent_addr =
1159                         ((u64)lu->login_response->command_block_agent_hi) << 32;
1160         lu->command_block_agent_addr |=
1161                         ((u64)lu->login_response->command_block_agent_lo);
1162         lu->command_block_agent_addr &= 0x0000ffffffffffffULL;
1163
1164         SBP2_INFO("Logged into SBP-2 device");
1165         return 0;
1166 }
1167
1168 static int sbp2_logout_device(struct sbp2_lu *lu)
1169 {
1170         struct sbp2_fwhost_info *hi = lu->hi;
1171         quadlet_t data[2];
1172         int error;
1173
1174         lu->logout_orb->reserved1 = 0x0;
1175         lu->logout_orb->reserved2 = 0x0;
1176         lu->logout_orb->reserved3 = 0x0;
1177         lu->logout_orb->reserved4 = 0x0;
1178
1179         lu->logout_orb->login_ID_misc = ORB_SET_FUNCTION(SBP2_LOGOUT_REQUEST);
1180         lu->logout_orb->login_ID_misc |=
1181                         ORB_SET_LOGIN_ID(lu->login_response->length_login_ID);
1182         lu->logout_orb->login_ID_misc |= ORB_SET_NOTIFY(1);
1183
1184         lu->logout_orb->reserved5 = 0x0;
1185         lu->logout_orb->status_fifo_hi =
1186                 ORB_SET_STATUS_FIFO_HI(lu->status_fifo_addr, hi->host->node_id);
1187         lu->logout_orb->status_fifo_lo =
1188                 ORB_SET_STATUS_FIFO_LO(lu->status_fifo_addr);
1189
1190         sbp2util_cpu_to_be32_buffer(lu->logout_orb,
1191                                     sizeof(struct sbp2_logout_orb));
1192
1193         data[0] = ORB_SET_NODE_ID(hi->host->node_id);
1194         data[1] = lu->logout_orb_dma;
1195         sbp2util_cpu_to_be32_buffer(data, 8);
1196
1197         error = hpsb_node_write(lu->ne, lu->management_agent_addr, data, 8);
1198         if (error)
1199                 return error;
1200
1201         /* wait up to 1 second for the device to complete logout */
1202         if (sbp2util_access_timeout(lu, HZ))
1203                 return -EIO;
1204
1205         SBP2_INFO("Logged out of SBP-2 device");
1206         return 0;
1207 }
1208
1209 static int sbp2_reconnect_device(struct sbp2_lu *lu)
1210 {
1211         struct sbp2_fwhost_info *hi = lu->hi;
1212         quadlet_t data[2];
1213         int error;
1214
1215         lu->reconnect_orb->reserved1 = 0x0;
1216         lu->reconnect_orb->reserved2 = 0x0;
1217         lu->reconnect_orb->reserved3 = 0x0;
1218         lu->reconnect_orb->reserved4 = 0x0;
1219
1220         lu->reconnect_orb->login_ID_misc =
1221                         ORB_SET_FUNCTION(SBP2_RECONNECT_REQUEST);
1222         lu->reconnect_orb->login_ID_misc |=
1223                         ORB_SET_LOGIN_ID(lu->login_response->length_login_ID);
1224         lu->reconnect_orb->login_ID_misc |= ORB_SET_NOTIFY(1);
1225
1226         lu->reconnect_orb->reserved5 = 0x0;
1227         lu->reconnect_orb->status_fifo_hi =
1228                 ORB_SET_STATUS_FIFO_HI(lu->status_fifo_addr, hi->host->node_id);
1229         lu->reconnect_orb->status_fifo_lo =
1230                 ORB_SET_STATUS_FIFO_LO(lu->status_fifo_addr);
1231
1232         sbp2util_cpu_to_be32_buffer(lu->reconnect_orb,
1233                                     sizeof(struct sbp2_reconnect_orb));
1234
1235         data[0] = ORB_SET_NODE_ID(hi->host->node_id);
1236         data[1] = lu->reconnect_orb_dma;
1237         sbp2util_cpu_to_be32_buffer(data, 8);
1238
1239         error = hpsb_node_write(lu->ne, lu->management_agent_addr, data, 8);
1240         if (error)
1241                 return error;
1242
1243         /* wait up to 1 second for reconnect status */
1244         if (sbp2util_access_timeout(lu, HZ)) {
1245                 SBP2_ERR("Error reconnecting to SBP-2 device - timed out");
1246                 return -EIO;
1247         }
1248
1249         /* make sure that the returned status matches the reconnect ORB */
1250         if (lu->status_block.ORB_offset_lo != lu->reconnect_orb_dma) {
1251                 SBP2_ERR("Error reconnecting to SBP-2 device - timed out");
1252                 return -EIO;
1253         }
1254
1255         if (STATUS_TEST_RDS(lu->status_block.ORB_offset_hi_misc)) {
1256                 SBP2_ERR("Error reconnecting to SBP-2 device - failed");
1257                 return -EIO;
1258         }
1259
1260         SBP2_INFO("Reconnected to SBP-2 device");
1261         return 0;
1262 }
1263
1264 /*
1265  * Set the target node's Single Phase Retry limit. Affects the target's retry
1266  * behaviour if our node is too busy to accept requests.
1267  */
1268 static int sbp2_set_busy_timeout(struct sbp2_lu *lu)
1269 {
1270         quadlet_t data;
1271
1272         data = cpu_to_be32(SBP2_BUSY_TIMEOUT_VALUE);
1273         if (hpsb_node_write(lu->ne, SBP2_BUSY_TIMEOUT_ADDRESS, &data, 4))
1274                 SBP2_ERR("%s error", __FUNCTION__);
1275         return 0;
1276 }
1277
1278 static void sbp2_parse_unit_directory(struct sbp2_lu *lu,
1279                                       struct unit_directory *ud)
1280 {
1281         struct csr1212_keyval *kv;
1282         struct csr1212_dentry *dentry;
1283         u64 management_agent_addr;
1284         u32 unit_characteristics, firmware_revision;
1285         unsigned workarounds;
1286         int i;
1287
1288         management_agent_addr = 0;
1289         unit_characteristics = 0;
1290         firmware_revision = 0;
1291
1292         csr1212_for_each_dir_entry(ud->ne->csr, kv, ud->ud_kv, dentry) {
1293                 switch (kv->key.id) {
1294                 case CSR1212_KV_ID_DEPENDENT_INFO:
1295                         if (kv->key.type == CSR1212_KV_TYPE_CSR_OFFSET)
1296                                 management_agent_addr =
1297                                     CSR1212_REGISTER_SPACE_BASE +
1298                                     (kv->value.csr_offset << 2);
1299
1300                         else if (kv->key.type == CSR1212_KV_TYPE_IMMEDIATE)
1301                                 lu->lun = ORB_SET_LUN(kv->value.immediate);
1302                         break;
1303
1304                 case SBP2_UNIT_CHARACTERISTICS_KEY:
1305                         /* FIXME: This is ignored so far.
1306                          * See SBP-2 clause 7.4.8. */
1307                         unit_characteristics = kv->value.immediate;
1308                         break;
1309
1310                 case SBP2_FIRMWARE_REVISION_KEY:
1311                         firmware_revision = kv->value.immediate;
1312                         break;
1313
1314                 default:
1315                         /* FIXME: Check for SBP2_DEVICE_TYPE_AND_LUN_KEY.
1316                          * Its "ordered" bit has consequences for command ORB
1317                          * list handling. See SBP-2 clauses 4.6, 7.4.11, 10.2 */
1318                         break;
1319                 }
1320         }
1321
1322         workarounds = sbp2_default_workarounds;
1323
1324         if (!(workarounds & SBP2_WORKAROUND_OVERRIDE))
1325                 for (i = 0; i < ARRAY_SIZE(sbp2_workarounds_table); i++) {
1326                         if (sbp2_workarounds_table[i].firmware_revision &&
1327                             sbp2_workarounds_table[i].firmware_revision !=
1328                             (firmware_revision & 0xffff00))
1329                                 continue;
1330                         if (sbp2_workarounds_table[i].model_id &&
1331                             sbp2_workarounds_table[i].model_id != ud->model_id)
1332                                 continue;
1333                         workarounds |= sbp2_workarounds_table[i].workarounds;
1334                         break;
1335                 }
1336
1337         if (workarounds)
1338                 SBP2_INFO("Workarounds for node " NODE_BUS_FMT ": 0x%x "
1339                           "(firmware_revision 0x%06x, vendor_id 0x%06x,"
1340                           " model_id 0x%06x)",
1341                           NODE_BUS_ARGS(ud->ne->host, ud->ne->nodeid),
1342                           workarounds, firmware_revision,
1343                           ud->vendor_id ? ud->vendor_id : ud->ne->vendor_id,
1344                           ud->model_id);
1345
1346         /* We would need one SCSI host template for each target to adjust
1347          * max_sectors on the fly, therefore warn only. */
1348         if (workarounds & SBP2_WORKAROUND_128K_MAX_TRANS &&
1349             (sbp2_max_sectors * 512) > (128 * 1024))
1350                 SBP2_INFO("Node " NODE_BUS_FMT ": Bridge only supports 128KB "
1351                           "max transfer size. WARNING: Current max_sectors "
1352                           "setting is larger than 128KB (%d sectors)",
1353                           NODE_BUS_ARGS(ud->ne->host, ud->ne->nodeid),
1354                           sbp2_max_sectors);
1355
1356         /* If this is a logical unit directory entry, process the parent
1357          * to get the values. */
1358         if (ud->flags & UNIT_DIRECTORY_LUN_DIRECTORY) {
1359                 struct unit_directory *parent_ud = container_of(
1360                         ud->device.parent, struct unit_directory, device);
1361                 sbp2_parse_unit_directory(lu, parent_ud);
1362         } else {
1363                 lu->management_agent_addr = management_agent_addr;
1364                 lu->workarounds = workarounds;
1365                 if (ud->flags & UNIT_DIRECTORY_HAS_LUN)
1366                         lu->lun = ORB_SET_LUN(ud->lun);
1367         }
1368 }
1369
1370 #define SBP2_PAYLOAD_TO_BYTES(p) (1 << ((p) + 2))
1371
1372 /*
1373  * This function is called in order to determine the max speed and packet
1374  * size we can use in our ORBs. Note, that we (the driver and host) only
1375  * initiate the transaction. The SBP-2 device actually transfers the data
1376  * (by reading from the DMA area we tell it). This means that the SBP-2
1377  * device decides the actual maximum data it can transfer. We just tell it
1378  * the speed that it needs to use, and the max_rec the host supports, and
1379  * it takes care of the rest.
1380  */
1381 static int sbp2_max_speed_and_size(struct sbp2_lu *lu)
1382 {
1383         struct sbp2_fwhost_info *hi = lu->hi;
1384         u8 payload;
1385
1386         lu->speed_code = hi->host->speed[NODEID_TO_NODE(lu->ne->nodeid)];
1387
1388         if (lu->speed_code > sbp2_max_speed) {
1389                 lu->speed_code = sbp2_max_speed;
1390                 SBP2_INFO("Reducing speed to %s",
1391                           hpsb_speedto_str[sbp2_max_speed]);
1392         }
1393
1394         /* Payload size is the lesser of what our speed supports and what
1395          * our host supports.  */
1396         payload = min(sbp2_speedto_max_payload[lu->speed_code],
1397                       (u8) (hi->host->csr.max_rec - 1));
1398
1399         /* If physical DMA is off, work around limitation in ohci1394:
1400          * packet size must not exceed PAGE_SIZE */
1401         if (lu->ne->host->low_addr_space < (1ULL << 32))
1402                 while (SBP2_PAYLOAD_TO_BYTES(payload) + 24 > PAGE_SIZE &&
1403                        payload)
1404                         payload--;
1405
1406         SBP2_INFO("Node " NODE_BUS_FMT ": Max speed [%s] - Max payload [%u]",
1407                   NODE_BUS_ARGS(hi->host, lu->ne->nodeid),
1408                   hpsb_speedto_str[lu->speed_code],
1409                   SBP2_PAYLOAD_TO_BYTES(payload));
1410
1411         lu->max_payload_size = payload;
1412         return 0;
1413 }
1414
1415 static int sbp2_agent_reset(struct sbp2_lu *lu, int wait)
1416 {
1417         quadlet_t data;
1418         u64 addr;
1419         int retval;
1420         unsigned long flags;
1421
1422         /* cancel_delayed_work(&lu->protocol_work); */
1423         if (wait)
1424                 flush_scheduled_work();
1425
1426         data = ntohl(SBP2_AGENT_RESET_DATA);
1427         addr = lu->command_block_agent_addr + SBP2_AGENT_RESET_OFFSET;
1428
1429         if (wait)
1430                 retval = hpsb_node_write(lu->ne, addr, &data, 4);
1431         else
1432                 retval = sbp2util_node_write_no_wait(lu->ne, addr, &data, 4);
1433
1434         if (retval < 0) {
1435                 SBP2_ERR("hpsb_node_write failed.\n");
1436                 return -EIO;
1437         }
1438
1439         /* make sure that the ORB_POINTER is written on next command */
1440         spin_lock_irqsave(&lu->cmd_orb_lock, flags);
1441         lu->last_orb = NULL;
1442         spin_unlock_irqrestore(&lu->cmd_orb_lock, flags);
1443
1444         return 0;
1445 }
1446
1447 static void sbp2_prep_command_orb_sg(struct sbp2_command_orb *orb,
1448                                      struct sbp2_fwhost_info *hi,
1449                                      struct sbp2_command_info *cmd,
1450                                      unsigned int scsi_use_sg,
1451                                      struct scatterlist *sgpnt,
1452                                      u32 orb_direction,
1453                                      enum dma_data_direction dma_dir)
1454 {
1455         cmd->dma_dir = dma_dir;
1456         orb->data_descriptor_hi = ORB_SET_NODE_ID(hi->host->node_id);
1457         orb->misc |= ORB_SET_DIRECTION(orb_direction);
1458
1459         /* special case if only one element (and less than 64KB in size) */
1460         if ((scsi_use_sg == 1) &&
1461             (sgpnt[0].length <= SBP2_MAX_SG_ELEMENT_LENGTH)) {
1462
1463                 cmd->dma_size = sgpnt[0].length;
1464                 cmd->dma_type = CMD_DMA_PAGE;
1465                 cmd->cmd_dma = pci_map_page(hi->host->pdev,
1466                                             sgpnt[0].page, sgpnt[0].offset,
1467                                             cmd->dma_size, cmd->dma_dir);
1468
1469                 orb->data_descriptor_lo = cmd->cmd_dma;
1470                 orb->misc |= ORB_SET_DATA_SIZE(cmd->dma_size);
1471
1472         } else {
1473                 struct sbp2_unrestricted_page_table *sg_element =
1474                                                 &cmd->scatter_gather_element[0];
1475                 u32 sg_count, sg_len;
1476                 dma_addr_t sg_addr;
1477                 int i, count = pci_map_sg(hi->host->pdev, sgpnt, scsi_use_sg,
1478                                           dma_dir);
1479
1480                 cmd->dma_size = scsi_use_sg;
1481                 cmd->sge_buffer = sgpnt;
1482
1483                 /* use page tables (s/g) */
1484                 orb->misc |= ORB_SET_PAGE_TABLE_PRESENT(0x1);
1485                 orb->data_descriptor_lo = cmd->sge_dma;
1486
1487                 /* loop through and fill out our SBP-2 page tables
1488                  * (and split up anything too large) */
1489                 for (i = 0, sg_count = 0 ; i < count; i++, sgpnt++) {
1490                         sg_len = sg_dma_len(sgpnt);
1491                         sg_addr = sg_dma_address(sgpnt);
1492                         while (sg_len) {
1493                                 sg_element[sg_count].segment_base_lo = sg_addr;
1494                                 if (sg_len > SBP2_MAX_SG_ELEMENT_LENGTH) {
1495                                         sg_element[sg_count].length_segment_base_hi =
1496                                                 PAGE_TABLE_SET_SEGMENT_LENGTH(SBP2_MAX_SG_ELEMENT_LENGTH);
1497                                         sg_addr += SBP2_MAX_SG_ELEMENT_LENGTH;
1498                                         sg_len -= SBP2_MAX_SG_ELEMENT_LENGTH;
1499                                 } else {
1500                                         sg_element[sg_count].length_segment_base_hi =
1501                                                 PAGE_TABLE_SET_SEGMENT_LENGTH(sg_len);
1502                                         sg_len = 0;
1503                                 }
1504                                 sg_count++;
1505                         }
1506                 }
1507
1508                 orb->misc |= ORB_SET_DATA_SIZE(sg_count);
1509
1510                 sbp2util_cpu_to_be32_buffer(sg_element,
1511                                 (sizeof(struct sbp2_unrestricted_page_table)) *
1512                                 sg_count);
1513         }
1514 }
1515
1516 static void sbp2_prep_command_orb_no_sg(struct sbp2_command_orb *orb,
1517                                         struct sbp2_fwhost_info *hi,
1518                                         struct sbp2_command_info *cmd,
1519                                         struct scatterlist *sgpnt,
1520                                         u32 orb_direction,
1521                                         unsigned int scsi_request_bufflen,
1522                                         void *scsi_request_buffer,
1523                                         enum dma_data_direction dma_dir)
1524 {
1525         cmd->dma_dir = dma_dir;
1526         cmd->dma_size = scsi_request_bufflen;
1527         cmd->dma_type = CMD_DMA_SINGLE;
1528         cmd->cmd_dma = pci_map_single(hi->host->pdev, scsi_request_buffer,
1529                                       cmd->dma_size, cmd->dma_dir);
1530         orb->data_descriptor_hi = ORB_SET_NODE_ID(hi->host->node_id);
1531         orb->misc |= ORB_SET_DIRECTION(orb_direction);
1532
1533         /* handle case where we get a command w/o s/g enabled
1534          * (but check for transfers larger than 64K) */
1535         if (scsi_request_bufflen <= SBP2_MAX_SG_ELEMENT_LENGTH) {
1536
1537                 orb->data_descriptor_lo = cmd->cmd_dma;
1538                 orb->misc |= ORB_SET_DATA_SIZE(scsi_request_bufflen);
1539
1540         } else {
1541                 /* The buffer is too large. Turn this into page tables. */
1542
1543                 struct sbp2_unrestricted_page_table *sg_element =
1544                                                 &cmd->scatter_gather_element[0];
1545                 u32 sg_count, sg_len;
1546                 dma_addr_t sg_addr;
1547
1548                 orb->data_descriptor_lo = cmd->sge_dma;
1549                 orb->misc |= ORB_SET_PAGE_TABLE_PRESENT(0x1);
1550
1551                 /* fill out our SBP-2 page tables; split up the large buffer */
1552                 sg_count = 0;
1553                 sg_len = scsi_request_bufflen;
1554                 sg_addr = cmd->cmd_dma;
1555                 while (sg_len) {
1556                         sg_element[sg_count].segment_base_lo = sg_addr;
1557                         if (sg_len > SBP2_MAX_SG_ELEMENT_LENGTH) {
1558                                 sg_element[sg_count].length_segment_base_hi =
1559                                         PAGE_TABLE_SET_SEGMENT_LENGTH(SBP2_MAX_SG_ELEMENT_LENGTH);
1560                                 sg_addr += SBP2_MAX_SG_ELEMENT_LENGTH;
1561                                 sg_len -= SBP2_MAX_SG_ELEMENT_LENGTH;
1562                         } else {
1563                                 sg_element[sg_count].length_segment_base_hi =
1564                                         PAGE_TABLE_SET_SEGMENT_LENGTH(sg_len);
1565                                 sg_len = 0;
1566                         }
1567                         sg_count++;
1568                 }
1569
1570                 orb->misc |= ORB_SET_DATA_SIZE(sg_count);
1571
1572                 sbp2util_cpu_to_be32_buffer(sg_element,
1573                                 (sizeof(struct sbp2_unrestricted_page_table)) *
1574                                 sg_count);
1575         }
1576 }
1577
1578 static void sbp2_create_command_orb(struct sbp2_lu *lu,
1579                                     struct sbp2_command_info *cmd,
1580                                     unchar *scsi_cmd,
1581                                     unsigned int scsi_use_sg,
1582                                     unsigned int scsi_request_bufflen,
1583                                     void *scsi_request_buffer,
1584                                     enum dma_data_direction dma_dir)
1585 {
1586         struct sbp2_fwhost_info *hi = lu->hi;
1587         struct scatterlist *sgpnt = (struct scatterlist *)scsi_request_buffer;
1588         struct sbp2_command_orb *orb = &cmd->command_orb;
1589         u32 orb_direction;
1590
1591         /*
1592          * Set-up our command ORB.
1593          *
1594          * NOTE: We're doing unrestricted page tables (s/g), as this is
1595          * best performance (at least with the devices I have). This means
1596          * that data_size becomes the number of s/g elements, and
1597          * page_size should be zero (for unrestricted).
1598          */
1599         orb->next_ORB_hi = ORB_SET_NULL_PTR(1);
1600         orb->next_ORB_lo = 0x0;
1601         orb->misc = ORB_SET_MAX_PAYLOAD(lu->max_payload_size);
1602         orb->misc |= ORB_SET_SPEED(lu->speed_code);
1603         orb->misc |= ORB_SET_NOTIFY(1);
1604
1605         if (dma_dir == DMA_NONE)
1606                 orb_direction = ORB_DIRECTION_NO_DATA_TRANSFER;
1607         else if (dma_dir == DMA_TO_DEVICE && scsi_request_bufflen)
1608                 orb_direction = ORB_DIRECTION_WRITE_TO_MEDIA;
1609         else if (dma_dir == DMA_FROM_DEVICE && scsi_request_bufflen)
1610                 orb_direction = ORB_DIRECTION_READ_FROM_MEDIA;
1611         else {
1612                 SBP2_INFO("Falling back to DMA_NONE");
1613                 orb_direction = ORB_DIRECTION_NO_DATA_TRANSFER;
1614         }
1615
1616         /* set up our page table stuff */
1617         if (orb_direction == ORB_DIRECTION_NO_DATA_TRANSFER) {
1618                 orb->data_descriptor_hi = 0x0;
1619                 orb->data_descriptor_lo = 0x0;
1620                 orb->misc |= ORB_SET_DIRECTION(1);
1621         } else if (scsi_use_sg)
1622                 sbp2_prep_command_orb_sg(orb, hi, cmd, scsi_use_sg, sgpnt,
1623                                          orb_direction, dma_dir);
1624         else
1625                 sbp2_prep_command_orb_no_sg(orb, hi, cmd, sgpnt, orb_direction,
1626                                             scsi_request_bufflen,
1627                                             scsi_request_buffer, dma_dir);
1628
1629         sbp2util_cpu_to_be32_buffer(orb, sizeof(*orb));
1630
1631         memset(orb->cdb, 0, 12);
1632         memcpy(orb->cdb, scsi_cmd, COMMAND_SIZE(*scsi_cmd));
1633 }
1634
1635 static void sbp2_link_orb_command(struct sbp2_lu *lu,
1636                                   struct sbp2_command_info *cmd)
1637 {
1638         struct sbp2_fwhost_info *hi = lu->hi;
1639         struct sbp2_command_orb *last_orb;
1640         dma_addr_t last_orb_dma;
1641         u64 addr = lu->command_block_agent_addr;
1642         quadlet_t data[2];
1643         size_t length;
1644         unsigned long flags;
1645
1646         pci_dma_sync_single_for_device(hi->host->pdev, cmd->command_orb_dma,
1647                                        sizeof(struct sbp2_command_orb),
1648                                        PCI_DMA_TODEVICE);
1649         pci_dma_sync_single_for_device(hi->host->pdev, cmd->sge_dma,
1650                                        sizeof(cmd->scatter_gather_element),
1651                                        PCI_DMA_BIDIRECTIONAL);
1652
1653         /* check to see if there are any previous orbs to use */
1654         spin_lock_irqsave(&lu->cmd_orb_lock, flags);
1655         last_orb = lu->last_orb;
1656         last_orb_dma = lu->last_orb_dma;
1657         if (!last_orb) {
1658                 /*
1659                  * last_orb == NULL means: We know that the target's fetch agent
1660                  * is not active right now.
1661                  */
1662                 addr += SBP2_ORB_POINTER_OFFSET;
1663                 data[0] = ORB_SET_NODE_ID(hi->host->node_id);
1664                 data[1] = cmd->command_orb_dma;
1665                 sbp2util_cpu_to_be32_buffer(data, 8);
1666                 length = 8;
1667         } else {
1668                 /*
1669                  * last_orb != NULL means: We know that the target's fetch agent
1670                  * is (very probably) not dead or in reset state right now.
1671                  * We have an ORB already sent that we can append a new one to.
1672                  * The target's fetch agent may or may not have read this
1673                  * previous ORB yet.
1674                  */
1675                 pci_dma_sync_single_for_cpu(hi->host->pdev, last_orb_dma,
1676                                             sizeof(struct sbp2_command_orb),
1677                                             PCI_DMA_TODEVICE);
1678                 last_orb->next_ORB_lo = cpu_to_be32(cmd->command_orb_dma);
1679                 wmb();
1680                 /* Tells hardware that this pointer is valid */
1681                 last_orb->next_ORB_hi = 0;
1682                 pci_dma_sync_single_for_device(hi->host->pdev, last_orb_dma,
1683                                                sizeof(struct sbp2_command_orb),
1684                                                PCI_DMA_TODEVICE);
1685                 addr += SBP2_DOORBELL_OFFSET;
1686                 data[0] = 0;
1687                 length = 4;
1688         }
1689         lu->last_orb = &cmd->command_orb;
1690         lu->last_orb_dma = cmd->command_orb_dma;
1691         spin_unlock_irqrestore(&lu->cmd_orb_lock, flags);
1692
1693         if (sbp2util_node_write_no_wait(lu->ne, addr, data, length)) {
1694                 /*
1695                  * sbp2util_node_write_no_wait failed. We certainly ran out
1696                  * of transaction labels, perhaps just because there were no
1697                  * context switches which gave khpsbpkt a chance to collect
1698                  * free tlabels. Try again in non-atomic context. If necessary,
1699                  * the workqueue job will sleep to guaranteedly get a tlabel.
1700                  * We do not accept new commands until the job is over.
1701                  */
1702                 scsi_block_requests(lu->shost);
1703                 PREPARE_WORK(&lu->protocol_work,
1704                              last_orb ? sbp2util_write_doorbell:
1705                                         sbp2util_write_orb_pointer
1706                              /* */);
1707                 schedule_work(&lu->protocol_work);
1708         }
1709 }
1710
1711 static int sbp2_send_command(struct sbp2_lu *lu, struct scsi_cmnd *SCpnt,
1712                              void (*done)(struct scsi_cmnd *))
1713 {
1714         unchar *scsi_cmd = (unchar *)SCpnt->cmnd;
1715         unsigned int request_bufflen = SCpnt->request_bufflen;
1716         struct sbp2_command_info *cmd;
1717
1718         cmd = sbp2util_allocate_command_orb(lu, SCpnt, done);
1719         if (!cmd)
1720                 return -EIO;
1721
1722         sbp2_create_command_orb(lu, cmd, scsi_cmd, SCpnt->use_sg,
1723                                 request_bufflen, SCpnt->request_buffer,
1724                                 SCpnt->sc_data_direction);
1725         sbp2_link_orb_command(lu, cmd);
1726
1727         return 0;
1728 }
1729
1730 /*
1731  * Translates SBP-2 status into SCSI sense data for check conditions
1732  */
1733 static unsigned int sbp2_status_to_sense_data(unchar *sbp2_status,
1734                                               unchar *sense_data)
1735 {
1736         /* OK, it's pretty ugly... ;-) */
1737         sense_data[0] = 0x70;
1738         sense_data[1] = 0x0;
1739         sense_data[2] = sbp2_status[9];
1740         sense_data[3] = sbp2_status[12];
1741         sense_data[4] = sbp2_status[13];
1742         sense_data[5] = sbp2_status[14];
1743         sense_data[6] = sbp2_status[15];
1744         sense_data[7] = 10;
1745         sense_data[8] = sbp2_status[16];
1746         sense_data[9] = sbp2_status[17];
1747         sense_data[10] = sbp2_status[18];
1748         sense_data[11] = sbp2_status[19];
1749         sense_data[12] = sbp2_status[10];
1750         sense_data[13] = sbp2_status[11];
1751         sense_data[14] = sbp2_status[20];
1752         sense_data[15] = sbp2_status[21];
1753
1754         return sbp2_status[8] & 0x3f;
1755 }
1756
1757 static int sbp2_handle_status_write(struct hpsb_host *host, int nodeid,
1758                                     int destid, quadlet_t *data, u64 addr,
1759                                     size_t length, u16 fl)
1760 {
1761         struct sbp2_fwhost_info *hi;
1762         struct sbp2_lu *lu = NULL, *lu_tmp;
1763         struct scsi_cmnd *SCpnt = NULL;
1764         struct sbp2_status_block *sb;
1765         u32 scsi_status = SBP2_SCSI_STATUS_GOOD;
1766         struct sbp2_command_info *cmd;
1767         unsigned long flags;
1768
1769         if (unlikely(length < 8 || length > sizeof(struct sbp2_status_block))) {
1770                 SBP2_ERR("Wrong size of status block");
1771                 return RCODE_ADDRESS_ERROR;
1772         }
1773         if (unlikely(!host)) {
1774                 SBP2_ERR("host is NULL - this is bad!");
1775                 return RCODE_ADDRESS_ERROR;
1776         }
1777         hi = hpsb_get_hostinfo(&sbp2_highlevel, host);
1778         if (unlikely(!hi)) {
1779                 SBP2_ERR("host info is NULL - this is bad!");
1780                 return RCODE_ADDRESS_ERROR;
1781         }
1782
1783         /* Find the unit which wrote the status. */
1784         list_for_each_entry(lu_tmp, &hi->logical_units, lu_list) {
1785                 if (lu_tmp->ne->nodeid == nodeid &&
1786                     lu_tmp->status_fifo_addr == addr) {
1787                         lu = lu_tmp;
1788                         break;
1789                 }
1790         }
1791         if (unlikely(!lu)) {
1792                 SBP2_ERR("lu is NULL - device is gone?");
1793                 return RCODE_ADDRESS_ERROR;
1794         }
1795
1796         /* Put response into lu status fifo buffer. The first two bytes
1797          * come in big endian bit order. Often the target writes only a
1798          * truncated status block, minimally the first two quadlets. The rest
1799          * is implied to be zeros. */
1800         sb = &lu->status_block;
1801         memset(sb->command_set_dependent, 0, sizeof(sb->command_set_dependent));
1802         memcpy(sb, data, length);
1803         sbp2util_be32_to_cpu_buffer(sb, 8);
1804
1805         /* Ignore unsolicited status. Handle command ORB status. */
1806         if (unlikely(STATUS_GET_SRC(sb->ORB_offset_hi_misc) == 2))
1807                 cmd = NULL;
1808         else
1809                 cmd = sbp2util_find_command_for_orb(lu, sb->ORB_offset_lo);
1810         if (cmd) {
1811                 pci_dma_sync_single_for_cpu(hi->host->pdev,
1812                                 cmd->command_orb_dma,
1813                                 sizeof(struct sbp2_command_orb),
1814                                 PCI_DMA_TODEVICE);
1815                 pci_dma_sync_single_for_cpu(hi->host->pdev,
1816                                 cmd->sge_dma,
1817                                 sizeof(cmd->scatter_gather_element),
1818                                 PCI_DMA_BIDIRECTIONAL);
1819                 /* Grab SCSI command pointers and check status. */
1820                 /*
1821                  * FIXME: If the src field in the status is 1, the ORB DMA must
1822                  * not be reused until status for a subsequent ORB is received.
1823                  */
1824                 SCpnt = cmd->Current_SCpnt;
1825                 spin_lock_irqsave(&lu->cmd_orb_lock, flags);
1826                 sbp2util_mark_command_completed(lu, cmd);
1827                 spin_unlock_irqrestore(&lu->cmd_orb_lock, flags);
1828
1829                 if (SCpnt) {
1830                         u32 h = sb->ORB_offset_hi_misc;
1831                         u32 r = STATUS_GET_RESP(h);
1832
1833                         if (r != RESP_STATUS_REQUEST_COMPLETE) {
1834                                 SBP2_INFO("resp 0x%x, sbp_status 0x%x",
1835                                           r, STATUS_GET_SBP_STATUS(h));
1836                                 scsi_status =
1837                                         r == RESP_STATUS_TRANSPORT_FAILURE ?
1838                                         SBP2_SCSI_STATUS_BUSY :
1839                                         SBP2_SCSI_STATUS_COMMAND_TERMINATED;
1840                         }
1841
1842                         if (STATUS_GET_LEN(h) > 1)
1843                                 scsi_status = sbp2_status_to_sense_data(
1844                                         (unchar *)sb, SCpnt->sense_buffer);
1845
1846                         if (STATUS_TEST_DEAD(h))
1847                                 sbp2_agent_reset(lu, 0);
1848                 }
1849
1850                 /* Check here to see if there are no commands in-use. If there
1851                  * are none, we know that the fetch agent left the active state
1852                  * _and_ that we did not reactivate it yet. Therefore clear
1853                  * last_orb so that next time we write directly to the
1854                  * ORB_POINTER register. That way the fetch agent does not need
1855                  * to refetch the next_ORB. */
1856                 spin_lock_irqsave(&lu->cmd_orb_lock, flags);
1857                 if (list_empty(&lu->cmd_orb_inuse))
1858                         lu->last_orb = NULL;
1859                 spin_unlock_irqrestore(&lu->cmd_orb_lock, flags);
1860
1861         } else {
1862                 /* It's probably status after a management request. */
1863                 if ((sb->ORB_offset_lo == lu->reconnect_orb_dma) ||
1864                     (sb->ORB_offset_lo == lu->login_orb_dma) ||
1865                     (sb->ORB_offset_lo == lu->query_logins_orb_dma) ||
1866                     (sb->ORB_offset_lo == lu->logout_orb_dma)) {
1867                         lu->access_complete = 1;
1868                         wake_up_interruptible(&sbp2_access_wq);
1869                 }
1870         }
1871
1872         if (SCpnt)
1873                 sbp2scsi_complete_command(lu, scsi_status, SCpnt,
1874                                           cmd->Current_done);
1875         return RCODE_COMPLETE;
1876 }
1877
1878 /**************************************
1879  * SCSI interface related section
1880  **************************************/
1881
1882 static int sbp2scsi_queuecommand(struct scsi_cmnd *SCpnt,
1883                                  void (*done)(struct scsi_cmnd *))
1884 {
1885         struct sbp2_lu *lu = (struct sbp2_lu *)SCpnt->device->host->hostdata[0];
1886         struct sbp2_fwhost_info *hi;
1887         int result = DID_NO_CONNECT << 16;
1888
1889         if (unlikely(!sbp2util_node_is_available(lu)))
1890                 goto done;
1891
1892         hi = lu->hi;
1893
1894         if (unlikely(!hi)) {
1895                 SBP2_ERR("sbp2_fwhost_info is NULL - this is bad!");
1896                 goto done;
1897         }
1898
1899         /* Multiple units are currently represented to the SCSI core as separate
1900          * targets, not as one target with multiple LUs. Therefore return
1901          * selection time-out to any IO directed at non-zero LUNs. */
1902         if (unlikely(SCpnt->device->lun))
1903                 goto done;
1904
1905         /* handle the request sense command here (auto-request sense) */
1906         if (SCpnt->cmnd[0] == REQUEST_SENSE) {
1907                 memcpy(SCpnt->request_buffer, SCpnt->sense_buffer,
1908                        SCpnt->request_bufflen);
1909                 memset(SCpnt->sense_buffer, 0, sizeof(SCpnt->sense_buffer));
1910                 sbp2scsi_complete_command(lu, SBP2_SCSI_STATUS_GOOD, SCpnt,
1911                                           done);
1912                 return 0;
1913         }
1914
1915         if (unlikely(!hpsb_node_entry_valid(lu->ne))) {
1916                 SBP2_ERR("Bus reset in progress - rejecting command");
1917                 result = DID_BUS_BUSY << 16;
1918                 goto done;
1919         }
1920
1921         /* Bidirectional commands are not yet implemented,
1922          * and unknown transfer direction not handled. */
1923         if (unlikely(SCpnt->sc_data_direction == DMA_BIDIRECTIONAL)) {
1924                 SBP2_ERR("Cannot handle DMA_BIDIRECTIONAL - rejecting command");
1925                 result = DID_ERROR << 16;
1926                 goto done;
1927         }
1928
1929         if (sbp2_send_command(lu, SCpnt, done)) {
1930                 SBP2_ERR("Error sending SCSI command");
1931                 sbp2scsi_complete_command(lu,
1932                                           SBP2_SCSI_STATUS_SELECTION_TIMEOUT,
1933                                           SCpnt, done);
1934         }
1935         return 0;
1936
1937 done:
1938         SCpnt->result = result;
1939         done(SCpnt);
1940         return 0;
1941 }
1942
1943 static void sbp2scsi_complete_all_commands(struct sbp2_lu *lu, u32 status)
1944 {
1945         struct sbp2_fwhost_info *hi = lu->hi;
1946         struct list_head *lh;
1947         struct sbp2_command_info *cmd;
1948         unsigned long flags;
1949
1950         spin_lock_irqsave(&lu->cmd_orb_lock, flags);
1951         while (!list_empty(&lu->cmd_orb_inuse)) {
1952                 lh = lu->cmd_orb_inuse.next;
1953                 cmd = list_entry(lh, struct sbp2_command_info, list);
1954                 pci_dma_sync_single_for_cpu(hi->host->pdev,
1955                                 cmd->command_orb_dma,
1956                                 sizeof(struct sbp2_command_orb),
1957                                 PCI_DMA_TODEVICE);
1958                 pci_dma_sync_single_for_cpu(hi->host->pdev, cmd->sge_dma,
1959                                 sizeof(cmd->scatter_gather_element),
1960                                 PCI_DMA_BIDIRECTIONAL);
1961                 sbp2util_mark_command_completed(lu, cmd);
1962                 if (cmd->Current_SCpnt) {
1963                         cmd->Current_SCpnt->result = status << 16;
1964                         cmd->Current_done(cmd->Current_SCpnt);
1965                 }
1966         }
1967         spin_unlock_irqrestore(&lu->cmd_orb_lock, flags);
1968
1969         return;
1970 }
1971
1972 /*
1973  * Complete a regular SCSI command. Can be called in atomic context.
1974  */
1975 static void sbp2scsi_complete_command(struct sbp2_lu *lu, u32 scsi_status,
1976                                       struct scsi_cmnd *SCpnt,
1977                                       void (*done)(struct scsi_cmnd *))
1978 {
1979         if (!SCpnt) {
1980                 SBP2_ERR("SCpnt is NULL");
1981                 return;
1982         }
1983
1984         switch (scsi_status) {
1985         case SBP2_SCSI_STATUS_GOOD:
1986                 SCpnt->result = DID_OK << 16;
1987                 break;
1988
1989         case SBP2_SCSI_STATUS_BUSY:
1990                 SBP2_ERR("SBP2_SCSI_STATUS_BUSY");
1991                 SCpnt->result = DID_BUS_BUSY << 16;
1992                 break;
1993
1994         case SBP2_SCSI_STATUS_CHECK_CONDITION:
1995                 SCpnt->result = CHECK_CONDITION << 1 | DID_OK << 16;
1996                 break;
1997
1998         case SBP2_SCSI_STATUS_SELECTION_TIMEOUT:
1999                 SBP2_ERR("SBP2_SCSI_STATUS_SELECTION_TIMEOUT");
2000                 SCpnt->result = DID_NO_CONNECT << 16;
2001                 scsi_print_command(SCpnt);
2002                 break;
2003
2004         case SBP2_SCSI_STATUS_CONDITION_MET:
2005         case SBP2_SCSI_STATUS_RESERVATION_CONFLICT:
2006         case SBP2_SCSI_STATUS_COMMAND_TERMINATED:
2007                 SBP2_ERR("Bad SCSI status = %x", scsi_status);
2008                 SCpnt->result = DID_ERROR << 16;
2009                 scsi_print_command(SCpnt);
2010                 break;
2011
2012         default:
2013                 SBP2_ERR("Unsupported SCSI status = %x", scsi_status);
2014                 SCpnt->result = DID_ERROR << 16;
2015         }
2016
2017         /* If a bus reset is in progress and there was an error, complete
2018          * the command as busy so that it will get retried. */
2019         if (!hpsb_node_entry_valid(lu->ne)
2020             && (scsi_status != SBP2_SCSI_STATUS_GOOD)) {
2021                 SBP2_ERR("Completing command with busy (bus reset)");
2022                 SCpnt->result = DID_BUS_BUSY << 16;
2023         }
2024
2025         /* Tell the SCSI stack that we're done with this command. */
2026         done(SCpnt);
2027 }
2028
2029 static int sbp2scsi_slave_alloc(struct scsi_device *sdev)
2030 {
2031         struct sbp2_lu *lu = (struct sbp2_lu *)sdev->host->hostdata[0];
2032
2033         lu->sdev = sdev;
2034         sdev->allow_restart = 1;
2035
2036         if (lu->workarounds & SBP2_WORKAROUND_INQUIRY_36)
2037                 sdev->inquiry_len = 36;
2038         return 0;
2039 }
2040
2041 static int sbp2scsi_slave_configure(struct scsi_device *sdev)
2042 {
2043         struct sbp2_lu *lu = (struct sbp2_lu *)sdev->host->hostdata[0];
2044
2045         blk_queue_dma_alignment(sdev->request_queue, (512 - 1));
2046         sdev->use_10_for_rw = 1;
2047
2048         if (sdev->type == TYPE_DISK &&
2049             lu->workarounds & SBP2_WORKAROUND_MODE_SENSE_8)
2050                 sdev->skip_ms_page_8 = 1;
2051         if (lu->workarounds & SBP2_WORKAROUND_FIX_CAPACITY)
2052                 sdev->fix_capacity = 1;
2053         return 0;
2054 }
2055
2056 static void sbp2scsi_slave_destroy(struct scsi_device *sdev)
2057 {
2058         ((struct sbp2_lu *)sdev->host->hostdata[0])->sdev = NULL;
2059         return;
2060 }
2061
2062 /*
2063  * Called by scsi stack when something has really gone wrong.
2064  * Usually called when a command has timed-out for some reason.
2065  */
2066 static int sbp2scsi_abort(struct scsi_cmnd *SCpnt)
2067 {
2068         struct sbp2_lu *lu = (struct sbp2_lu *)SCpnt->device->host->hostdata[0];
2069         struct sbp2_fwhost_info *hi = lu->hi;
2070         struct sbp2_command_info *cmd;
2071         unsigned long flags;
2072
2073         SBP2_INFO("aborting sbp2 command");
2074         scsi_print_command(SCpnt);
2075
2076         if (sbp2util_node_is_available(lu)) {
2077                 sbp2_agent_reset(lu, 1);
2078
2079                 /* Return a matching command structure to the free pool. */
2080                 spin_lock_irqsave(&lu->cmd_orb_lock, flags);
2081                 cmd = sbp2util_find_command_for_SCpnt(lu, SCpnt);
2082                 if (cmd) {
2083                         pci_dma_sync_single_for_cpu(hi->host->pdev,
2084                                         cmd->command_orb_dma,
2085                                         sizeof(struct sbp2_command_orb),
2086                                         PCI_DMA_TODEVICE);
2087                         pci_dma_sync_single_for_cpu(hi->host->pdev,
2088                                         cmd->sge_dma,
2089                                         sizeof(cmd->scatter_gather_element),
2090                                         PCI_DMA_BIDIRECTIONAL);
2091                         sbp2util_mark_command_completed(lu, cmd);
2092                         if (cmd->Current_SCpnt) {
2093                                 cmd->Current_SCpnt->result = DID_ABORT << 16;
2094                                 cmd->Current_done(cmd->Current_SCpnt);
2095                         }
2096                 }
2097                 spin_unlock_irqrestore(&lu->cmd_orb_lock, flags);
2098
2099                 sbp2scsi_complete_all_commands(lu, DID_BUS_BUSY);
2100         }
2101
2102         return SUCCESS;
2103 }
2104
2105 /*
2106  * Called by scsi stack when something has really gone wrong.
2107  */
2108 static int sbp2scsi_reset(struct scsi_cmnd *SCpnt)
2109 {
2110         struct sbp2_lu *lu = (struct sbp2_lu *)SCpnt->device->host->hostdata[0];
2111
2112         SBP2_INFO("reset requested");
2113
2114         if (sbp2util_node_is_available(lu)) {
2115                 SBP2_INFO("generating sbp2 fetch agent reset");
2116                 sbp2_agent_reset(lu, 1);
2117         }
2118
2119         return SUCCESS;
2120 }
2121
2122 static ssize_t sbp2_sysfs_ieee1394_id_show(struct device *dev,
2123                                            struct device_attribute *attr,
2124                                            char *buf)
2125 {
2126         struct scsi_device *sdev;
2127         struct sbp2_lu *lu;
2128
2129         if (!(sdev = to_scsi_device(dev)))
2130                 return 0;
2131
2132         if (!(lu = (struct sbp2_lu *)sdev->host->hostdata[0]))
2133                 return 0;
2134
2135         return sprintf(buf, "%016Lx:%d:%d\n", (unsigned long long)lu->ne->guid,
2136                        lu->ud->id, ORB_SET_LUN(lu->lun));
2137 }
2138
2139 MODULE_AUTHOR("Ben Collins <bcollins@debian.org>");
2140 MODULE_DESCRIPTION("IEEE-1394 SBP-2 protocol driver");
2141 MODULE_SUPPORTED_DEVICE(SBP2_DEVICE_NAME);
2142 MODULE_LICENSE("GPL");
2143
2144 static int sbp2_module_init(void)
2145 {
2146         int ret;
2147
2148         if (sbp2_serialize_io) {
2149                 sbp2_shost_template.can_queue = 1;
2150                 sbp2_shost_template.cmd_per_lun = 1;
2151         }
2152
2153         if (sbp2_default_workarounds & SBP2_WORKAROUND_128K_MAX_TRANS &&
2154             (sbp2_max_sectors * 512) > (128 * 1024))
2155                 sbp2_max_sectors = 128 * 1024 / 512;
2156         sbp2_shost_template.max_sectors = sbp2_max_sectors;
2157
2158         hpsb_register_highlevel(&sbp2_highlevel);
2159         ret = hpsb_register_protocol(&sbp2_driver);
2160         if (ret) {
2161                 SBP2_ERR("Failed to register protocol");
2162                 hpsb_unregister_highlevel(&sbp2_highlevel);
2163                 return ret;
2164         }
2165         return 0;
2166 }
2167
2168 static void __exit sbp2_module_exit(void)
2169 {
2170         hpsb_unregister_protocol(&sbp2_driver);
2171         hpsb_unregister_highlevel(&sbp2_highlevel);
2172 }
2173
2174 module_init(sbp2_module_init);
2175 module_exit(sbp2_module_exit);