1/*
2 * SBP2 driver (SCSI over IEEE1394)
3 *
4 * Copyright (C) 2005-2007  Kristian Hoegsberg <krh@bitplanet.net>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 */
20
21/*
22 * The basic structure of this driver is based on the old storage driver,
23 * drivers/ieee1394/sbp2.c, originally written by
24 *     James Goodwin <jamesg@filanet.com>
25 * with later contributions and ongoing maintenance from
26 *     Ben Collins <bcollins@debian.org>,
27 *     Stefan Richter <stefanr@s5r6.in-berlin.de>
28 * and many others.
29 */
30
31#include <linux/kernel.h>
32#include <linux/module.h>
33#include <linux/mod_devicetable.h>
34#include <linux/device.h>
35#include <linux/scatterlist.h>
36#include <linux/dma-mapping.h>
37#include <linux/timer.h>
38
39#include <scsi/scsi.h>
40#include <scsi/scsi_cmnd.h>
41#include <scsi/scsi_dbg.h>
42#include <scsi/scsi_device.h>
43#include <scsi/scsi_host.h>
44
45#include "fw-transaction.h"
46#include "fw-topology.h"
47#include "fw-device.h"
48
49/* I don't know why the SCSI stack doesn't define something like this... */
50typedef void (*scsi_done_fn_t)(struct scsi_cmnd *);
51
52static const char sbp2_driver_name[] = "sbp2";
53
54struct sbp2_device {
55	struct kref kref;
56	struct fw_unit *unit;
57	struct fw_address_handler address_handler;
58	struct list_head orb_list;
59	u64 management_agent_address;
60	u64 command_block_agent_address;
61	u32 workarounds;
62	int login_id;
63
64	/*
65	 * We cache these addresses and only update them once we've
66	 * logged in or reconnected to the sbp2 device.  That way, any
67	 * IO to the device will automatically fail and get retried if
68	 * it happens in a window where the device is not ready to
69	 * handle it (e.g. after a bus reset but before we reconnect).
70	 */
71	int node_id;
72	int address_high;
73	int generation;
74
75	int retries;
76	struct delayed_work work;
77};
78
79#define SBP2_MAX_SG_ELEMENT_LENGTH	0xf000
80#define SBP2_MAX_SECTORS		255	/* Max sectors supported */
81#define SBP2_ORB_TIMEOUT		2000	/* Timeout in ms */
82
83#define SBP2_ORB_NULL			0x80000000
84
85#define SBP2_DIRECTION_TO_MEDIA		0x0
86#define SBP2_DIRECTION_FROM_MEDIA	0x1
87
88/* Unit directory keys */
89#define SBP2_COMMAND_SET_SPECIFIER	0x38
90#define SBP2_COMMAND_SET		0x39
91#define SBP2_COMMAND_SET_REVISION	0x3b
92#define SBP2_FIRMWARE_REVISION		0x3c
93
94/* Flags for detected oddities and brokeness */
95#define SBP2_WORKAROUND_128K_MAX_TRANS	0x1
96#define SBP2_WORKAROUND_INQUIRY_36	0x2
97#define SBP2_WORKAROUND_MODE_SENSE_8	0x4
98#define SBP2_WORKAROUND_FIX_CAPACITY	0x8
99#define SBP2_WORKAROUND_OVERRIDE	0x100
100
101/* Management orb opcodes */
102#define SBP2_LOGIN_REQUEST		0x0
103#define SBP2_QUERY_LOGINS_REQUEST	0x1
104#define SBP2_RECONNECT_REQUEST		0x3
105#define SBP2_SET_PASSWORD_REQUEST	0x4
106#define SBP2_LOGOUT_REQUEST		0x7
107#define SBP2_ABORT_TASK_REQUEST		0xb
108#define SBP2_ABORT_TASK_SET		0xc
109#define SBP2_LOGICAL_UNIT_RESET		0xe
110#define SBP2_TARGET_RESET_REQUEST	0xf
111
112/* Offsets for command block agent registers */
113#define SBP2_AGENT_STATE		0x00
114#define SBP2_AGENT_RESET		0x04
115#define SBP2_ORB_POINTER		0x08
116#define SBP2_DOORBELL			0x10
117#define SBP2_UNSOLICITED_STATUS_ENABLE	0x14
118
119/* Status write response codes */
120#define SBP2_STATUS_REQUEST_COMPLETE	0x0
121#define SBP2_STATUS_TRANSPORT_FAILURE	0x1
122#define SBP2_STATUS_ILLEGAL_REQUEST	0x2
123#define SBP2_STATUS_VENDOR_DEPENDENT	0x3
124
125#define STATUS_GET_ORB_HIGH(v)		((v).status & 0xffff)
126#define STATUS_GET_SBP_STATUS(v)	(((v).status >> 16) & 0xff)
127#define STATUS_GET_LEN(v)		(((v).status >> 24) & 0x07)
128#define STATUS_GET_DEAD(v)		(((v).status >> 27) & 0x01)
129#define STATUS_GET_RESPONSE(v)		(((v).status >> 28) & 0x03)
130#define STATUS_GET_SOURCE(v)		(((v).status >> 30) & 0x03)
131#define STATUS_GET_ORB_LOW(v)		((v).orb_low)
132#define STATUS_GET_DATA(v)		((v).data)
133
134struct sbp2_status {
135	u32 status;
136	u32 orb_low;
137	u8 data[24];
138};
139
140struct sbp2_pointer {
141	u32 high;
142	u32 low;
143};
144
145struct sbp2_orb {
146	struct fw_transaction t;
147	dma_addr_t request_bus;
148	int rcode;
149	struct sbp2_pointer pointer;
150	void (*callback)(struct sbp2_orb * orb, struct sbp2_status * status);
151	struct list_head link;
152};
153
154#define MANAGEMENT_ORB_LUN(v)			((v))
155#define MANAGEMENT_ORB_FUNCTION(v)		((v) << 16)
156#define MANAGEMENT_ORB_RECONNECT(v)		((v) << 20)
157#define MANAGEMENT_ORB_EXCLUSIVE		((1) << 28)
158#define MANAGEMENT_ORB_REQUEST_FORMAT(v)	((v) << 29)
159#define MANAGEMENT_ORB_NOTIFY			((1) << 31)
160
161#define MANAGEMENT_ORB_RESPONSE_LENGTH(v)	((v))
162#define MANAGEMENT_ORB_PASSWORD_LENGTH(v)	((v) << 16)
163
164struct sbp2_management_orb {
165	struct sbp2_orb base;
166	struct {
167		struct sbp2_pointer password;
168		struct sbp2_pointer response;
169		u32 misc;
170		u32 length;
171		struct sbp2_pointer status_fifo;
172	} request;
173	__be32 response[4];
174	dma_addr_t response_bus;
175	struct completion done;
176	struct sbp2_status status;
177};
178
179#define LOGIN_RESPONSE_GET_LOGIN_ID(v)	((v).misc & 0xffff)
180#define LOGIN_RESPONSE_GET_LENGTH(v)	(((v).misc >> 16) & 0xffff)
181
182struct sbp2_login_response {
183	u32 misc;
184	struct sbp2_pointer command_block_agent;
185	u32 reconnect_hold;
186};
187#define COMMAND_ORB_DATA_SIZE(v)	((v))
188#define COMMAND_ORB_PAGE_SIZE(v)	((v) << 16)
189#define COMMAND_ORB_PAGE_TABLE_PRESENT	((1) << 19)
190#define COMMAND_ORB_MAX_PAYLOAD(v)	((v) << 20)
191#define COMMAND_ORB_SPEED(v)		((v) << 24)
192#define COMMAND_ORB_DIRECTION(v)	((v) << 27)
193#define COMMAND_ORB_REQUEST_FORMAT(v)	((v) << 29)
194#define COMMAND_ORB_NOTIFY		((1) << 31)
195
196struct sbp2_command_orb {
197	struct sbp2_orb base;
198	struct {
199		struct sbp2_pointer next;
200		struct sbp2_pointer data_descriptor;
201		u32 misc;
202		u8 command_block[12];
203	} request;
204	struct scsi_cmnd *cmd;
205	scsi_done_fn_t done;
206	struct fw_unit *unit;
207
208	struct sbp2_pointer page_table[SG_ALL];
209	dma_addr_t page_table_bus;
210	dma_addr_t request_buffer_bus;
211};
212
213/*
214 * List of devices with known bugs.
215 *
216 * The firmware_revision field, masked with 0xffff00, is the best
217 * indicator for the type of bridge chip of a device.  It yields a few
218 * false positives but this did not break correctly behaving devices
219 * so far.  We use ~0 as a wildcard, since the 24 bit values we get
220 * from the config rom can never match that.
221 */
222static const struct {
223	u32 firmware_revision;
224	u32 model;
225	unsigned workarounds;
226} sbp2_workarounds_table[] = {
227	/* DViCO Momobay CX-1 with TSB42AA9 bridge */ {
228		.firmware_revision	= 0x002800,
229		.model			= 0x001010,
230		.workarounds		= SBP2_WORKAROUND_INQUIRY_36 |
231					  SBP2_WORKAROUND_MODE_SENSE_8,
232	},
233	/* Initio bridges, actually only needed for some older ones */ {
234		.firmware_revision	= 0x000200,
235		.model			= ~0,
236		.workarounds		= SBP2_WORKAROUND_INQUIRY_36,
237	},
238	/* Symbios bridge */ {
239		.firmware_revision	= 0xa0b800,
240		.model			= ~0,
241		.workarounds		= SBP2_WORKAROUND_128K_MAX_TRANS,
242	},
243
244	/*
245	 * There are iPods (2nd gen, 3rd gen) with model_id == 0, but
246	 * these iPods do not feature the read_capacity bug according
247	 * to one report.  Read_capacity behaviour as well as model_id
248	 * could change due to Apple-supplied firmware updates though.
249	 */
250
251	/* iPod 4th generation. */ {
252		.firmware_revision	= 0x0a2700,
253		.model			= 0x000021,
254		.workarounds		= SBP2_WORKAROUND_FIX_CAPACITY,
255	},
256	/* iPod mini */ {
257		.firmware_revision	= 0x0a2700,
258		.model			= 0x000023,
259		.workarounds		= SBP2_WORKAROUND_FIX_CAPACITY,
260	},
261	/* iPod Photo */ {
262		.firmware_revision	= 0x0a2700,
263		.model			= 0x00007e,
264		.workarounds		= SBP2_WORKAROUND_FIX_CAPACITY,
265	}
266};
267
268static void
269sbp2_status_write(struct fw_card *card, struct fw_request *request,
270		  int tcode, int destination, int source,
271		  int generation, int speed,
272		  unsigned long long offset,
273		  void *payload, size_t length, void *callback_data)
274{
275	struct sbp2_device *sd = callback_data;
276	struct sbp2_orb *orb;
277	struct sbp2_status status;
278	size_t header_size;
279	unsigned long flags;
280
281	if (tcode != TCODE_WRITE_BLOCK_REQUEST ||
282	    length == 0 || length > sizeof(status)) {
283		fw_send_response(card, request, RCODE_TYPE_ERROR);
284		return;
285	}
286
287	header_size = min(length, 2 * sizeof(u32));
288	fw_memcpy_from_be32(&status, payload, header_size);
289	if (length > header_size)
290		memcpy(status.data, payload + 8, length - header_size);
291	if (STATUS_GET_SOURCE(status) == 2 || STATUS_GET_SOURCE(status) == 3) {
292		fw_notify("non-orb related status write, not handled\n");
293		fw_send_response(card, request, RCODE_COMPLETE);
294		return;
295	}
296
297	/* Lookup the orb corresponding to this status write. */
298	spin_lock_irqsave(&card->lock, flags);
299	list_for_each_entry(orb, &sd->orb_list, link) {
300		if (STATUS_GET_ORB_HIGH(status) == 0 &&
301		    STATUS_GET_ORB_LOW(status) == orb->request_bus &&
302		    orb->rcode == RCODE_COMPLETE) {
303			list_del(&orb->link);
304			break;
305		}
306	}
307	spin_unlock_irqrestore(&card->lock, flags);
308
309	if (&orb->link != &sd->orb_list)
310		orb->callback(orb, &status);
311	else
312		fw_error("status write for unknown orb\n");
313
314	fw_send_response(card, request, RCODE_COMPLETE);
315}
316
317static void
318complete_transaction(struct fw_card *card, int rcode,
319		     void *payload, size_t length, void *data)
320{
321	struct sbp2_orb *orb = data;
322	unsigned long flags;
323
324	orb->rcode = rcode;
325	if (rcode != RCODE_COMPLETE) {
326		spin_lock_irqsave(&card->lock, flags);
327		list_del(&orb->link);
328		spin_unlock_irqrestore(&card->lock, flags);
329		orb->callback(orb, NULL);
330	}
331}
332
333static void
334sbp2_send_orb(struct sbp2_orb *orb, struct fw_unit *unit,
335	      int node_id, int generation, u64 offset)
336{
337	struct fw_device *device = fw_device(unit->device.parent);
338	struct sbp2_device *sd = unit->device.driver_data;
339	unsigned long flags;
340
341	orb->pointer.high = 0;
342	orb->pointer.low = orb->request_bus;
343	fw_memcpy_to_be32(&orb->pointer, &orb->pointer, sizeof(orb->pointer));
344
345	spin_lock_irqsave(&device->card->lock, flags);
346	list_add_tail(&orb->link, &sd->orb_list);
347	spin_unlock_irqrestore(&device->card->lock, flags);
348
349	fw_send_request(device->card, &orb->t, TCODE_WRITE_BLOCK_REQUEST,
350			node_id, generation,
351			device->node->max_speed, offset,
352			&orb->pointer, sizeof(orb->pointer),
353			complete_transaction, orb);
354}
355
356static int sbp2_cancel_orbs(struct fw_unit *unit)
357{
358	struct fw_device *device = fw_device(unit->device.parent);
359	struct sbp2_device *sd = unit->device.driver_data;
360	struct sbp2_orb *orb, *next;
361	struct list_head list;
362	unsigned long flags;
363	int retval = -ENOENT;
364
365	INIT_LIST_HEAD(&list);
366	spin_lock_irqsave(&device->card->lock, flags);
367	list_splice_init(&sd->orb_list, &list);
368	spin_unlock_irqrestore(&device->card->lock, flags);
369
370	list_for_each_entry_safe(orb, next, &list, link) {
371		retval = 0;
372		if (fw_cancel_transaction(device->card, &orb->t) == 0)
373			continue;
374
375		orb->rcode = RCODE_CANCELLED;
376		orb->callback(orb, NULL);
377	}
378
379	return retval;
380}
381
382static void
383complete_management_orb(struct sbp2_orb *base_orb, struct sbp2_status *status)
384{
385	struct sbp2_management_orb *orb =
386	    (struct sbp2_management_orb *)base_orb;
387
388	if (status)
389		memcpy(&orb->status, status, sizeof(*status));
390	complete(&orb->done);
391}
392
393static int
394sbp2_send_management_orb(struct fw_unit *unit, int node_id, int generation,
395			 int function, int lun, void *response)
396{
397	struct fw_device *device = fw_device(unit->device.parent);
398	struct sbp2_device *sd = unit->device.driver_data;
399	struct sbp2_management_orb *orb;
400	int retval = -ENOMEM;
401
402	orb = kzalloc(sizeof(*orb), GFP_ATOMIC);
403	if (orb == NULL)
404		return -ENOMEM;
405
406	/*
407	 * The sbp2 device is going to send a block read request to
408	 * read out the request from host memory, so map it for dma.
409	 */
410	orb->base.request_bus =
411		dma_map_single(device->card->device, &orb->request,
412			       sizeof(orb->request), DMA_TO_DEVICE);
413	if (dma_mapping_error(orb->base.request_bus))
414		goto out;
415
416	orb->response_bus =
417		dma_map_single(device->card->device, &orb->response,
418			       sizeof(orb->response), DMA_FROM_DEVICE);
419	if (dma_mapping_error(orb->response_bus))
420		goto out;
421
422	orb->request.response.high    = 0;
423	orb->request.response.low     = orb->response_bus;
424
425	orb->request.misc =
426		MANAGEMENT_ORB_NOTIFY |
427		MANAGEMENT_ORB_FUNCTION(function) |
428		MANAGEMENT_ORB_LUN(lun);
429	orb->request.length =
430		MANAGEMENT_ORB_RESPONSE_LENGTH(sizeof(orb->response));
431
432	orb->request.status_fifo.high = sd->address_handler.offset >> 32;
433	orb->request.status_fifo.low  = sd->address_handler.offset;
434
435	if (function == SBP2_LOGIN_REQUEST) {
436		orb->request.misc |=
437			MANAGEMENT_ORB_EXCLUSIVE |
438			MANAGEMENT_ORB_RECONNECT(0);
439	}
440
441	fw_memcpy_to_be32(&orb->request, &orb->request, sizeof(orb->request));
442
443	init_completion(&orb->done);
444	orb->base.callback = complete_management_orb;
445
446	sbp2_send_orb(&orb->base, unit,
447		      node_id, generation, sd->management_agent_address);
448
449	wait_for_completion_timeout(&orb->done,
450				    msecs_to_jiffies(SBP2_ORB_TIMEOUT));
451
452	retval = -EIO;
453	if (sbp2_cancel_orbs(unit) == 0) {
454		fw_error("orb reply timed out, rcode=0x%02x\n",
455			 orb->base.rcode);
456		goto out;
457	}
458
459	if (orb->base.rcode != RCODE_COMPLETE) {
460		fw_error("management write failed, rcode 0x%02x\n",
461			 orb->base.rcode);
462		goto out;
463	}
464
465	if (STATUS_GET_RESPONSE(orb->status) != 0 ||
466	    STATUS_GET_SBP_STATUS(orb->status) != 0) {
467		fw_error("error status: %d:%d\n",
468			 STATUS_GET_RESPONSE(orb->status),
469			 STATUS_GET_SBP_STATUS(orb->status));
470		goto out;
471	}
472
473	retval = 0;
474 out:
475	dma_unmap_single(device->card->device, orb->base.request_bus,
476			 sizeof(orb->request), DMA_TO_DEVICE);
477	dma_unmap_single(device->card->device, orb->response_bus,
478			 sizeof(orb->response), DMA_FROM_DEVICE);
479
480	if (response)
481		fw_memcpy_from_be32(response,
482				    orb->response, sizeof(orb->response));
483	kfree(orb);
484
485	return retval;
486}
487
488static void
489complete_agent_reset_write(struct fw_card *card, int rcode,
490			   void *payload, size_t length, void *data)
491{
492	struct fw_transaction *t = data;
493
494	kfree(t);
495}
496
497static int sbp2_agent_reset(struct fw_unit *unit)
498{
499	struct fw_device *device = fw_device(unit->device.parent);
500	struct sbp2_device *sd = unit->device.driver_data;
501	struct fw_transaction *t;
502	static u32 zero;
503
504	t = kzalloc(sizeof(*t), GFP_ATOMIC);
505	if (t == NULL)
506		return -ENOMEM;
507
508	fw_send_request(device->card, t, TCODE_WRITE_QUADLET_REQUEST,
509			sd->node_id, sd->generation, SCODE_400,
510			sd->command_block_agent_address + SBP2_AGENT_RESET,
511			&zero, sizeof(zero), complete_agent_reset_write, t);
512
513	return 0;
514}
515
516static void sbp2_reconnect(struct work_struct *work);
517static struct scsi_host_template scsi_driver_template;
518
519static void
520release_sbp2_device(struct kref *kref)
521{
522	struct sbp2_device *sd = container_of(kref, struct sbp2_device, kref);
523	struct Scsi_Host *host =
524		container_of((void *)sd, struct Scsi_Host, hostdata[0]);
525
526	sbp2_send_management_orb(sd->unit, sd->node_id, sd->generation,
527				 SBP2_LOGOUT_REQUEST, sd->login_id, NULL);
528
529	scsi_remove_host(host);
530	fw_core_remove_address_handler(&sd->address_handler);
531	fw_notify("removed sbp2 unit %s\n", sd->unit->device.bus_id);
532	put_device(&sd->unit->device);
533	scsi_host_put(host);
534}
535
536static void sbp2_login(struct work_struct *work)
537{
538	struct sbp2_device *sd =
539		container_of(work, struct sbp2_device, work.work);
540	struct Scsi_Host *host =
541		container_of((void *)sd, struct Scsi_Host, hostdata[0]);
542	struct fw_unit *unit = sd->unit;
543	struct fw_device *device = fw_device(unit->device.parent);
544	struct sbp2_login_response response;
545	int generation, node_id, local_node_id, lun, retval;
546
547	lun = 0;
548
549	generation    = device->card->generation;
550	node_id       = device->node->node_id;
551	local_node_id = device->card->local_node->node_id;
552
553	if (sbp2_send_management_orb(unit, node_id, generation,
554				     SBP2_LOGIN_REQUEST, lun, &response) < 0) {
555		if (sd->retries++ < 5) {
556			schedule_delayed_work(&sd->work, DIV_ROUND_UP(HZ, 5));
557		} else {
558			fw_error("failed to login to %s\n",
559				 unit->device.bus_id);
560			kref_put(&sd->kref, release_sbp2_device);
561		}
562		return;
563	}
564
565	sd->generation   = generation;
566	sd->node_id      = node_id;
567	sd->address_high = local_node_id << 16;
568
569	/* Get command block agent offset and login id. */
570	sd->command_block_agent_address =
571		((u64) (response.command_block_agent.high & 0xffff) << 32) |
572		response.command_block_agent.low;
573	sd->login_id = LOGIN_RESPONSE_GET_LOGIN_ID(response);
574
575	fw_notify("logged in to sbp2 unit %s (%d retries)\n",
576		  unit->device.bus_id, sd->retries);
577	fw_notify(" - management_agent_address:    0x%012llx\n",
578		  (unsigned long long) sd->management_agent_address);
579	fw_notify(" - command_block_agent_address: 0x%012llx\n",
580		  (unsigned long long) sd->command_block_agent_address);
581	fw_notify(" - status write address:        0x%012llx\n",
582		  (unsigned long long) sd->address_handler.offset);
583
584
585	PREPARE_DELAYED_WORK(&sd->work, sbp2_reconnect);
586	sbp2_agent_reset(unit);
587
588	lun = 0;
589	retval = scsi_add_device(host, 0, 0, lun);
590	if (retval < 0) {
591		sbp2_send_management_orb(unit, sd->node_id, sd->generation,
592					 SBP2_LOGOUT_REQUEST, sd->login_id,
593					 NULL);
594		/*
595		 * Set this back to sbp2_login so we fall back and
596		 * retry login on bus reset.
597		 */
598		PREPARE_DELAYED_WORK(&sd->work, sbp2_login);
599	}
600	kref_put(&sd->kref, release_sbp2_device);
601}
602
603static int sbp2_probe(struct device *dev)
604{
605	struct fw_unit *unit = fw_unit(dev);
606	struct fw_device *device = fw_device(unit->device.parent);
607	struct sbp2_device *sd;
608	struct fw_csr_iterator ci;
609	struct Scsi_Host *host;
610	int i, key, value, err;
611	u32 model, firmware_revision;
612
613	err = -ENOMEM;
614	host = scsi_host_alloc(&scsi_driver_template, sizeof(*sd));
615	if (host == NULL)
616		goto fail;
617
618	sd = (struct sbp2_device *) host->hostdata;
619	unit->device.driver_data = sd;
620	sd->unit = unit;
621	INIT_LIST_HEAD(&sd->orb_list);
622	kref_init(&sd->kref);
623
624	sd->address_handler.length = 0x100;
625	sd->address_handler.address_callback = sbp2_status_write;
626	sd->address_handler.callback_data = sd;
627
628	err = fw_core_add_address_handler(&sd->address_handler,
629					  &fw_high_memory_region);
630	if (err < 0)
631		goto fail_host;
632
633	err = fw_device_enable_phys_dma(device);
634	if (err < 0)
635		goto fail_address_handler;
636
637	err = scsi_add_host(host, &unit->device);
638	if (err < 0)
639		goto fail_address_handler;
640
641	/*
642	 * Scan unit directory to get management agent address,
643	 * firmware revison and model.  Initialize firmware_revision
644	 * and model to values that wont match anything in our table.
645	 */
646	firmware_revision = 0xff000000;
647	model = 0xff000000;
648	fw_csr_iterator_init(&ci, unit->directory);
649	while (fw_csr_iterator_next(&ci, &key, &value)) {
650		switch (key) {
651		case CSR_DEPENDENT_INFO | CSR_OFFSET:
652			sd->management_agent_address =
653				0xfffff0000000ULL + 4 * value;
654			break;
655		case SBP2_FIRMWARE_REVISION:
656			firmware_revision = value;
657			break;
658		case CSR_MODEL:
659			model = value;
660			break;
661		}
662	}
663
664	for (i = 0; i < ARRAY_SIZE(sbp2_workarounds_table); i++) {
665		if (sbp2_workarounds_table[i].firmware_revision !=
666		    (firmware_revision & 0xffffff00))
667			continue;
668		if (sbp2_workarounds_table[i].model != model &&
669		    sbp2_workarounds_table[i].model != ~0)
670			continue;
671		sd->workarounds |= sbp2_workarounds_table[i].workarounds;
672		break;
673	}
674
675	if (sd->workarounds)
676		fw_notify("Workarounds for node %s: 0x%x "
677			  "(firmware_revision 0x%06x, model_id 0x%06x)\n",
678			  unit->device.bus_id,
679			  sd->workarounds, firmware_revision, model);
680
681	get_device(&unit->device);
682
683	/*
684	 * We schedule work to do the login so we can easily
685	 * reschedule retries. Always get the ref before scheduling
686	 * work.
687	 */
688	INIT_DELAYED_WORK(&sd->work, sbp2_login);
689	if (schedule_delayed_work(&sd->work, 0))
690		kref_get(&sd->kref);
691
692	return 0;
693
694 fail_address_handler:
695	fw_core_remove_address_handler(&sd->address_handler);
696 fail_host:
697	scsi_host_put(host);
698 fail:
699	return err;
700}
701
702static int sbp2_remove(struct device *dev)
703{
704	struct fw_unit *unit = fw_unit(dev);
705	struct sbp2_device *sd = unit->device.driver_data;
706
707	kref_put(&sd->kref, release_sbp2_device);
708
709	return 0;
710}
711
712static void sbp2_reconnect(struct work_struct *work)
713{
714	struct sbp2_device *sd =
715		container_of(work, struct sbp2_device, work.work);
716	struct fw_unit *unit = sd->unit;
717	struct fw_device *device = fw_device(unit->device.parent);
718	int generation, node_id, local_node_id;
719
720	generation    = device->card->generation;
721	node_id       = device->node->node_id;
722	local_node_id = device->card->local_node->node_id;
723
724	if (sbp2_send_management_orb(unit, node_id, generation,
725				     SBP2_RECONNECT_REQUEST,
726				     sd->login_id, NULL) < 0) {
727		if (sd->retries++ >= 5) {
728			fw_error("failed to reconnect to %s\n",
729				 unit->device.bus_id);
730			/* Fall back and try to log in again. */
731			sd->retries = 0;
732			PREPARE_DELAYED_WORK(&sd->work, sbp2_login);
733		}
734		schedule_delayed_work(&sd->work, DIV_ROUND_UP(HZ, 5));
735		return;
736	}
737
738	sd->generation   = generation;
739	sd->node_id      = node_id;
740	sd->address_high = local_node_id << 16;
741
742	fw_notify("reconnected to unit %s (%d retries)\n",
743		  unit->device.bus_id, sd->retries);
744	sbp2_agent_reset(unit);
745	sbp2_cancel_orbs(unit);
746	kref_put(&sd->kref, release_sbp2_device);
747}
748
749static void sbp2_update(struct fw_unit *unit)
750{
751	struct fw_device *device = fw_device(unit->device.parent);
752	struct sbp2_device *sd = unit->device.driver_data;
753
754	sd->retries = 0;
755	fw_device_enable_phys_dma(device);
756	if (schedule_delayed_work(&sd->work, 0))
757		kref_get(&sd->kref);
758}
759
760#define SBP2_UNIT_SPEC_ID_ENTRY	0x0000609e
761#define SBP2_SW_VERSION_ENTRY	0x00010483
762
763static const struct fw_device_id sbp2_id_table[] = {
764	{
765		.match_flags  = FW_MATCH_SPECIFIER_ID | FW_MATCH_VERSION,
766		.specifier_id = SBP2_UNIT_SPEC_ID_ENTRY,
767		.version      = SBP2_SW_VERSION_ENTRY,
768	},
769	{ }
770};
771
772static struct fw_driver sbp2_driver = {
773	.driver   = {
774		.owner  = THIS_MODULE,
775		.name   = sbp2_driver_name,
776		.bus    = &fw_bus_type,
777		.probe  = sbp2_probe,
778		.remove = sbp2_remove,
779	},
780	.update   = sbp2_update,
781	.id_table = sbp2_id_table,
782};
783
784static unsigned int
785sbp2_status_to_sense_data(u8 *sbp2_status, u8 *sense_data)
786{
787	int sam_status;
788
789	sense_data[0] = 0x70;
790	sense_data[1] = 0x0;
791	sense_data[2] = sbp2_status[1];
792	sense_data[3] = sbp2_status[4];
793	sense_data[4] = sbp2_status[5];
794	sense_data[5] = sbp2_status[6];
795	sense_data[6] = sbp2_status[7];
796	sense_data[7] = 10;
797	sense_data[8] = sbp2_status[8];
798	sense_data[9] = sbp2_status[9];
799	sense_data[10] = sbp2_status[10];
800	sense_data[11] = sbp2_status[11];
801	sense_data[12] = sbp2_status[2];
802	sense_data[13] = sbp2_status[3];
803	sense_data[14] = sbp2_status[12];
804	sense_data[15] = sbp2_status[13];
805
806	sam_status = sbp2_status[0] & 0x3f;
807
808	switch (sam_status) {
809	case SAM_STAT_GOOD:
810	case SAM_STAT_CHECK_CONDITION:
811	case SAM_STAT_CONDITION_MET:
812	case SAM_STAT_BUSY:
813	case SAM_STAT_RESERVATION_CONFLICT:
814	case SAM_STAT_COMMAND_TERMINATED:
815		return DID_OK << 16 | sam_status;
816
817	default:
818		return DID_ERROR << 16;
819	}
820}
821
822static void
823complete_command_orb(struct sbp2_orb *base_orb, struct sbp2_status *status)
824{
825	struct sbp2_command_orb *orb = (struct sbp2_command_orb *)base_orb;
826	struct fw_unit *unit = orb->unit;
827	struct fw_device *device = fw_device(unit->device.parent);
828	struct scatterlist *sg;
829	int result;
830
831	if (status != NULL) {
832		if (STATUS_GET_DEAD(*status))
833			sbp2_agent_reset(unit);
834
835		switch (STATUS_GET_RESPONSE(*status)) {
836		case SBP2_STATUS_REQUEST_COMPLETE:
837			result = DID_OK << 16;
838			break;
839		case SBP2_STATUS_TRANSPORT_FAILURE:
840			result = DID_BUS_BUSY << 16;
841			break;
842		case SBP2_STATUS_ILLEGAL_REQUEST:
843		case SBP2_STATUS_VENDOR_DEPENDENT:
844		default:
845			result = DID_ERROR << 16;
846			break;
847		}
848
849		if (result == DID_OK << 16 && STATUS_GET_LEN(*status) > 1)
850			result = sbp2_status_to_sense_data(STATUS_GET_DATA(*status),
851							   orb->cmd->sense_buffer);
852	} else {
853		/*
854		 * If the orb completes with status == NULL, something
855		 * went wrong, typically a bus reset happened mid-orb
856		 * or when sending the write (less likely).
857		 */
858		result = DID_BUS_BUSY << 16;
859	}
860
861	dma_unmap_single(device->card->device, orb->base.request_bus,
862			 sizeof(orb->request), DMA_TO_DEVICE);
863
864	if (orb->cmd->use_sg > 0) {
865		sg = (struct scatterlist *)orb->cmd->request_buffer;
866		dma_unmap_sg(device->card->device, sg, orb->cmd->use_sg,
867			     orb->cmd->sc_data_direction);
868	}
869
870	if (orb->page_table_bus != 0)
871		dma_unmap_single(device->card->device, orb->page_table_bus,
872				 sizeof(orb->page_table_bus), DMA_TO_DEVICE);
873
874	if (orb->request_buffer_bus != 0)
875		dma_unmap_single(device->card->device, orb->request_buffer_bus,
876				 sizeof(orb->request_buffer_bus),
877				 DMA_FROM_DEVICE);
878
879	orb->cmd->result = result;
880	orb->done(orb->cmd);
881	kfree(orb);
882}
883
884static int sbp2_command_orb_map_scatterlist(struct sbp2_command_orb *orb)
885{
886	struct sbp2_device *sd =
887		(struct sbp2_device *)orb->cmd->device->host->hostdata;
888	struct fw_unit *unit = sd->unit;
889	struct fw_device *device = fw_device(unit->device.parent);
890	struct scatterlist *sg;
891	int sg_len, l, i, j, count;
892	size_t size;
893	dma_addr_t sg_addr;
894
895	sg = (struct scatterlist *)orb->cmd->request_buffer;
896	count = dma_map_sg(device->card->device, sg, orb->cmd->use_sg,
897			   orb->cmd->sc_data_direction);
898	if (count == 0)
899		goto fail;
900
901	if (count == 1 && sg_dma_len(sg) < SBP2_MAX_SG_ELEMENT_LENGTH) {
902		orb->request.data_descriptor.high = sd->address_high;
903		orb->request.data_descriptor.low  = sg_dma_address(sg);
904		orb->request.misc |=
905			COMMAND_ORB_DATA_SIZE(sg_dma_len(sg));
906		return 0;
907	}
908
909	/*
910	 * Convert the scatterlist to an sbp2 page table.  If any
911	 * scatterlist entries are too big for sbp2, we split them as we
912	 * go.  Even if we ask the block I/O layer to not give us sg
913	 * elements larger than 65535 bytes, some IOMMUs may merge sg elements
914	 * during DMA mapping, and Linux currently doesn't prevent this.
915	 */
916	for (i = 0, j = 0; i < count; i++) {
917		sg_len = sg_dma_len(sg + i);
918		sg_addr = sg_dma_address(sg + i);
919		while (sg_len) {
920			l = min(sg_len, SBP2_MAX_SG_ELEMENT_LENGTH);
921			orb->page_table[j].low = sg_addr;
922			orb->page_table[j].high = (l << 16);
923			sg_addr += l;
924			sg_len -= l;
925			j++;
926		}
927	}
928
929	size = sizeof(orb->page_table[0]) * j;
930
931	/*
932	 * The data_descriptor pointer is the one case where we need
933	 * to fill in the node ID part of the address.  All other
934	 * pointers assume that the data referenced reside on the
935	 * initiator (i.e. us), but data_descriptor can refer to data
936	 * on other nodes so we need to put our ID in descriptor.high.
937	 */
938
939	orb->page_table_bus =
940		dma_map_single(device->card->device, orb->page_table,
941			       size, DMA_TO_DEVICE);
942	if (dma_mapping_error(orb->page_table_bus))
943		goto fail_page_table;
944	orb->request.data_descriptor.high = sd->address_high;
945	orb->request.data_descriptor.low  = orb->page_table_bus;
946	orb->request.misc |=
947		COMMAND_ORB_PAGE_TABLE_PRESENT |
948		COMMAND_ORB_DATA_SIZE(j);
949
950	fw_memcpy_to_be32(orb->page_table, orb->page_table, size);
951
952	return 0;
953
954 fail_page_table:
955	dma_unmap_sg(device->card->device, sg, orb->cmd->use_sg,
956		     orb->cmd->sc_data_direction);
957 fail:
958	return -ENOMEM;
959}
960
961/* SCSI stack integration */
962
963static int sbp2_scsi_queuecommand(struct scsi_cmnd *cmd, scsi_done_fn_t done)
964{
965	struct sbp2_device *sd =
966		(struct sbp2_device *)cmd->device->host->hostdata;
967	struct fw_unit *unit = sd->unit;
968	struct fw_device *device = fw_device(unit->device.parent);
969	struct sbp2_command_orb *orb;
970
971	/*
972	 * Bidirectional commands are not yet implemented, and unknown
973	 * transfer direction not handled.
974	 */
975	if (cmd->sc_data_direction == DMA_BIDIRECTIONAL) {
976		fw_error("Cannot handle DMA_BIDIRECTIONAL - rejecting command");
977		cmd->result = DID_ERROR << 16;
978		done(cmd);
979		return 0;
980	}
981
982	orb = kzalloc(sizeof(*orb), GFP_ATOMIC);
983	if (orb == NULL) {
984		fw_notify("failed to alloc orb\n");
985		goto fail_alloc;
986	}
987
988	/* Initialize rcode to something not RCODE_COMPLETE. */
989	orb->base.rcode = -1;
990	orb->base.request_bus =
991		dma_map_single(device->card->device, &orb->request,
992			       sizeof(orb->request), DMA_TO_DEVICE);
993	if (dma_mapping_error(orb->base.request_bus))
994		goto fail_mapping;
995
996	orb->unit = unit;
997	orb->done = done;
998	orb->cmd  = cmd;
999
1000	orb->request.next.high   = SBP2_ORB_NULL;
1001	orb->request.next.low    = 0x0;
1002	/*
1003	 * At speed 100 we can do 512 bytes per packet, at speed 200,
1004	 * 1024 bytes per packet etc.  The SBP-2 max_payload field
1005	 * specifies the max payload size as 2 ^ (max_payload + 2), so
1006	 * if we set this to max_speed + 7, we get the right value.
1007	 */
1008	orb->request.misc =
1009		COMMAND_ORB_MAX_PAYLOAD(device->node->max_speed + 7) |
1010		COMMAND_ORB_SPEED(device->node->max_speed) |
1011		COMMAND_ORB_NOTIFY;
1012
1013	if (cmd->sc_data_direction == DMA_FROM_DEVICE)
1014		orb->request.misc |=
1015			COMMAND_ORB_DIRECTION(SBP2_DIRECTION_FROM_MEDIA);
1016	else if (cmd->sc_data_direction == DMA_TO_DEVICE)
1017		orb->request.misc |=
1018			COMMAND_ORB_DIRECTION(SBP2_DIRECTION_TO_MEDIA);
1019
1020	if (cmd->use_sg && sbp2_command_orb_map_scatterlist(orb) < 0)
1021		goto fail_map_payload;
1022
1023	fw_memcpy_to_be32(&orb->request, &orb->request, sizeof(orb->request));
1024
1025	memset(orb->request.command_block,
1026	       0, sizeof(orb->request.command_block));
1027	memcpy(orb->request.command_block, cmd->cmnd, COMMAND_SIZE(*cmd->cmnd));
1028
1029	orb->base.callback = complete_command_orb;
1030
1031	sbp2_send_orb(&orb->base, unit, sd->node_id, sd->generation,
1032		      sd->command_block_agent_address + SBP2_ORB_POINTER);
1033
1034	return 0;
1035
1036 fail_map_payload:
1037	dma_unmap_single(device->card->device, orb->base.request_bus,
1038			 sizeof(orb->request), DMA_TO_DEVICE);
1039 fail_mapping:
1040	kfree(orb);
1041 fail_alloc:
1042	return SCSI_MLQUEUE_HOST_BUSY;
1043}
1044
1045static int sbp2_scsi_slave_alloc(struct scsi_device *sdev)
1046{
1047	struct sbp2_device *sd = (struct sbp2_device *)sdev->host->hostdata;
1048
1049	sdev->allow_restart = 1;
1050
1051	if (sd->workarounds & SBP2_WORKAROUND_INQUIRY_36)
1052		sdev->inquiry_len = 36;
1053	return 0;
1054}
1055
1056static int sbp2_scsi_slave_configure(struct scsi_device *sdev)
1057{
1058	struct sbp2_device *sd = (struct sbp2_device *)sdev->host->hostdata;
1059	struct fw_unit *unit = sd->unit;
1060
1061	sdev->use_10_for_rw = 1;
1062
1063	if (sdev->type == TYPE_ROM)
1064		sdev->use_10_for_ms = 1;
1065	if (sdev->type == TYPE_DISK &&
1066	    sd->workarounds & SBP2_WORKAROUND_MODE_SENSE_8)
1067		sdev->skip_ms_page_8 = 1;
1068	if (sd->workarounds & SBP2_WORKAROUND_FIX_CAPACITY) {
1069		fw_notify("setting fix_capacity for %s\n", unit->device.bus_id);
1070		sdev->fix_capacity = 1;
1071	}
1072
1073	return 0;
1074}
1075
1076/*
1077 * Called by scsi stack when something has really gone wrong.  Usually
1078 * called when a command has timed-out for some reason.
1079 */
1080static int sbp2_scsi_abort(struct scsi_cmnd *cmd)
1081{
1082	struct sbp2_device *sd =
1083		(struct sbp2_device *)cmd->device->host->hostdata;
1084	struct fw_unit *unit = sd->unit;
1085
1086	fw_notify("sbp2_scsi_abort\n");
1087	sbp2_agent_reset(unit);
1088	sbp2_cancel_orbs(unit);
1089
1090	return SUCCESS;
1091}
1092
1093/*
1094 * Format of /sys/bus/scsi/devices/.../ieee1394_id:
1095 * u64 EUI-64 : u24 directory_ID : u16 LUN  (all printed in hexadecimal)
1096 *
1097 * This is the concatenation of target port identifier and logical unit
1098 * identifier as per SAM-2...SAM-4 annex A.
1099 */
1100static ssize_t
1101sbp2_sysfs_ieee1394_id_show(struct device *dev, struct device_attribute *attr,
1102			    char *buf)
1103{
1104	struct scsi_device *sdev = to_scsi_device(dev);
1105	struct sbp2_device *sd;
1106	struct fw_unit *unit;
1107	struct fw_device *device;
1108	u32 directory_id;
1109	struct fw_csr_iterator ci;
1110	int key, value, lun;
1111
1112	if (!sdev)
1113		return 0;
1114	sd = (struct sbp2_device *)sdev->host->hostdata;
1115	unit = sd->unit;
1116	device = fw_device(unit->device.parent);
1117
1118	/* implicit directory ID */
1119	directory_id = ((unit->directory - device->config_rom) * 4
1120			+ CSR_CONFIG_ROM) & 0xffffff;
1121
1122	/* explicit directory ID, overrides implicit ID if present */
1123	fw_csr_iterator_init(&ci, unit->directory);
1124	while (fw_csr_iterator_next(&ci, &key, &value))
1125		if (key == CSR_DIRECTORY_ID) {
1126			directory_id = value;
1127			break;
1128		}
1129
1130	lun = 0;
1131
1132	return sprintf(buf, "%08x%08x:%06x:%04x\n",
1133			device->config_rom[3], device->config_rom[4],
1134			directory_id, lun);
1135}
1136
1137static DEVICE_ATTR(ieee1394_id, S_IRUGO, sbp2_sysfs_ieee1394_id_show, NULL);
1138
1139static struct device_attribute *sbp2_scsi_sysfs_attrs[] = {
1140	&dev_attr_ieee1394_id,
1141	NULL
1142};
1143
1144static struct scsi_host_template scsi_driver_template = {
1145	.module			= THIS_MODULE,
1146	.name			= "SBP-2 IEEE-1394",
1147	.proc_name		= (char *)sbp2_driver_name,
1148	.queuecommand		= sbp2_scsi_queuecommand,
1149	.slave_alloc		= sbp2_scsi_slave_alloc,
1150	.slave_configure	= sbp2_scsi_slave_configure,
1151	.eh_abort_handler	= sbp2_scsi_abort,
1152	.this_id		= -1,
1153	.sg_tablesize		= SG_ALL,
1154	.use_clustering		= ENABLE_CLUSTERING,
1155	.cmd_per_lun		= 1,
1156	.can_queue		= 1,
1157	.sdev_attrs		= sbp2_scsi_sysfs_attrs,
1158};
1159
1160MODULE_AUTHOR("Kristian Hoegsberg <krh@bitplanet.net>");
1161MODULE_DESCRIPTION("SCSI over IEEE1394");
1162MODULE_LICENSE("GPL");
1163MODULE_DEVICE_TABLE(ieee1394, sbp2_id_table);
1164
1165/* Provide a module alias so root-on-sbp2 initrds don't break. */
1166#ifndef CONFIG_IEEE1394_SBP2_MODULE
1167MODULE_ALIAS("sbp2");
1168#endif
1169
1170static int __init sbp2_init(void)
1171{
1172	return driver_register(&sbp2_driver.driver);
1173}
1174
1175static void __exit sbp2_cleanup(void)
1176{
1177	driver_unregister(&sbp2_driver.driver);
1178}
1179
1180module_init(sbp2_init);
1181module_exit(sbp2_cleanup);
1182