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