firewire: Only use INIT_DELAYED_WORK for first initialization.
[sfrench/cifs-2.6.git] / drivers / firewire / fw-sbp2.c
1 /*                                              -*- c-basic-offset: 8 -*-
2  * fw-spb2.c -- 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 /* The basic structure of this driver is based the old storage driver,
22  * drivers/ieee1394/sbp2.c, originally written by
23  *     James Goodwin <jamesg@filanet.com>
24  * with later contributions and ongoing maintenance from
25  *     Ben Collins <bcollins@debian.org>,
26  *     Stefan Richter <stefanr@s5r6.in-berlin.de>
27  * and many others.
28  */
29
30 #include <linux/kernel.h>
31 #include <linux/module.h>
32 #include <linux/mod_devicetable.h>
33 #include <linux/device.h>
34 #include <linux/scatterlist.h>
35 #include <linux/dma-mapping.h>
36 #include <linux/timer.h>
37
38 #include <scsi/scsi.h>
39 #include <scsi/scsi_cmnd.h>
40 #include <scsi/scsi_dbg.h>
41 #include <scsi/scsi_device.h>
42 #include <scsi/scsi_host.h>
43
44 #include "fw-transaction.h"
45 #include "fw-topology.h"
46 #include "fw-device.h"
47
48 /* I don't know why the SCSI stack doesn't define something like this... */
49 typedef void (*scsi_done_fn_t) (struct scsi_cmnd *);
50
51 static const char sbp2_driver_name[] = "sbp2";
52
53 struct sbp2_device {
54         struct fw_unit *unit;
55         struct fw_address_handler address_handler;
56         struct list_head orb_list;
57         u64 management_agent_address;
58         u64 command_block_agent_address;
59         u32 workarounds;
60         int login_id;
61
62         /* We cache these addresses and only update them once we've
63          * logged in or reconnected to the sbp2 device.  That way, any
64          * IO to the device will automatically fail and get retried if
65          * it happens in a window where the device is not ready to
66          * handle it (e.g. after a bus reset but before we reconnect). */
67         int node_id;
68         int address_high;
69         int generation;
70
71         /* Timer for flushing ORBs. */
72         struct timer_list orb_timer;
73
74         int retries;
75         struct delayed_work work;
76         struct Scsi_Host *scsi_host;
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
134 struct sbp2_status {
135         u32 status;
136         u32 orb_low;
137         u8 data[24];
138 };
139
140 struct sbp2_pointer {
141         u32 high;
142         u32 low;
143 };
144
145 struct 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
164 struct 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
182 struct sbp2_login_response {
183         u32 misc;
184         struct sbp2_pointer command_block_agent;
185         u32 reconnect_hold;
186 };
187
188 #define command_orb_data_size(v)        ((v))
189 #define command_orb_page_size(v)        ((v) << 16)
190 #define command_orb_page_table_present  ((1) << 19)
191 #define command_orb_max_payload(v)      ((v) << 20)
192 #define command_orb_speed(v)            ((v) << 24)
193 #define command_orb_direction(v)        ((v) << 27)
194 #define command_orb_request_format(v)   ((v) << 29)
195 #define command_orb_notify              ((1) << 31)
196
197 struct sbp2_command_orb {
198         struct sbp2_orb base;
199         struct {
200                 struct sbp2_pointer next;
201                 struct sbp2_pointer data_descriptor;
202                 u32 misc;
203                 u8 command_block[12];
204         } request;
205         struct scsi_cmnd *cmd;
206         scsi_done_fn_t done;
207         struct fw_unit *unit;
208
209         struct sbp2_pointer page_table[SG_ALL];
210         dma_addr_t page_table_bus;
211         dma_addr_t request_buffer_bus;
212 };
213
214 /*
215  * List of devices with known bugs.
216  *
217  * The firmware_revision field, masked with 0xffff00, is the best
218  * indicator for the type of bridge chip of a device.  It yields a few
219  * false positives but this did not break correctly behaving devices
220  * so far.  We use ~0 as a wildcard, since the 24 bit values we get
221  * from the config rom can never match that.
222  */
223 static const struct {
224         u32 firmware_revision;
225         u32 model;
226         unsigned workarounds;
227 } sbp2_workarounds_table[] = {
228         /* DViCO Momobay CX-1 with TSB42AA9 bridge */ {
229                 .firmware_revision      = 0x002800,
230                 .model                  = 0x001010,
231                 .workarounds            = SBP2_WORKAROUND_INQUIRY_36 |
232                                           SBP2_WORKAROUND_MODE_SENSE_8,
233         },
234         /* Initio bridges, actually only needed for some older ones */ {
235                 .firmware_revision      = 0x000200,
236                 .model                  = ~0,
237                 .workarounds            = SBP2_WORKAROUND_INQUIRY_36,
238         },
239         /* Symbios bridge */ {
240                 .firmware_revision      = 0xa0b800,
241                 .model                  = ~0,
242                 .workarounds            = SBP2_WORKAROUND_128K_MAX_TRANS,
243         },
244         /* There are iPods (2nd gen, 3rd gen) with model_id == 0, but
245          * these iPods do not feature the read_capacity bug according
246          * to one report.  Read_capacity behaviour as well as model_id
247          * could change due to Apple-supplied firmware updates though. */
248         /* iPod 4th generation. */ {
249                 .firmware_revision      = 0x0a2700,
250                 .model                  = 0x000021,
251                 .workarounds            = SBP2_WORKAROUND_FIX_CAPACITY,
252         },
253         /* iPod mini */ {
254                 .firmware_revision      = 0x0a2700,
255                 .model                  = 0x000023,
256                 .workarounds            = SBP2_WORKAROUND_FIX_CAPACITY,
257         },
258         /* iPod Photo */ {
259                 .firmware_revision      = 0x0a2700,
260                 .model                  = 0x00007e,
261                 .workarounds            = SBP2_WORKAROUND_FIX_CAPACITY,
262         }
263 };
264
265 static void
266 sbp2_status_write(struct fw_card *card, struct fw_request *request,
267                   int tcode, int destination, int source,
268                   int generation, int speed,
269                   unsigned long long offset,
270                   void *payload, size_t length, void *callback_data)
271 {
272         struct sbp2_device *sd = callback_data;
273         struct sbp2_orb *orb;
274         struct sbp2_status status;
275         size_t header_size;
276         unsigned long flags;
277
278         if (tcode != TCODE_WRITE_BLOCK_REQUEST ||
279             length == 0 || length > sizeof status) {
280                 fw_send_response(card, request, RCODE_TYPE_ERROR);
281                 return;
282         }
283
284         header_size = min(length, 2 * sizeof(u32));
285         fw_memcpy_from_be32(&status, payload, header_size);
286         if (length > header_size)
287                 memcpy(status.data, payload + 8, length - header_size);
288         if (status_get_source(status) == 2 || status_get_source(status) == 3) {
289                 fw_notify("non-orb related status write, not handled\n");
290                 fw_send_response(card, request, RCODE_COMPLETE);
291                 return;
292         }
293
294         /* Lookup the orb corresponding to this status write. */
295         spin_lock_irqsave(&card->lock, flags);
296         list_for_each_entry(orb, &sd->orb_list, link) {
297                 if (status_get_orb_high(status) == 0 &&
298                     status_get_orb_low(status) == orb->request_bus) {
299                         list_del(&orb->link);
300                         break;
301                 }
302         }
303         spin_unlock_irqrestore(&card->lock, flags);
304
305         if (&orb->link != &sd->orb_list)
306                 orb->callback(orb, &status);
307         else
308                 fw_error("status write for unknown orb\n");
309
310         fw_send_response(card, request, RCODE_COMPLETE);
311 }
312
313 static void
314 complete_transaction(struct fw_card *card, int rcode,
315                      void *payload, size_t length, void *data)
316 {
317         struct sbp2_orb *orb = data;
318         unsigned long flags;
319
320         orb->rcode = rcode;
321         if (rcode != RCODE_COMPLETE) {
322                 spin_lock_irqsave(&card->lock, flags);
323                 list_del(&orb->link);
324                 spin_unlock_irqrestore(&card->lock, flags);
325                 orb->callback(orb, NULL);
326         }
327 }
328
329 static void
330 sbp2_send_orb(struct sbp2_orb *orb, struct fw_unit *unit,
331               int node_id, int generation, u64 offset)
332 {
333         struct fw_device *device = fw_device(unit->device.parent);
334         struct sbp2_device *sd = unit->device.driver_data;
335         unsigned long flags;
336
337         orb->pointer.high = 0;
338         orb->pointer.low = orb->request_bus;
339         fw_memcpy_to_be32(&orb->pointer, &orb->pointer, sizeof orb->pointer);
340
341         spin_lock_irqsave(&device->card->lock, flags);
342         list_add_tail(&orb->link, &sd->orb_list);
343         spin_unlock_irqrestore(&device->card->lock, flags);
344
345         mod_timer(&sd->orb_timer,
346                   jiffies + DIV_ROUND_UP(SBP2_ORB_TIMEOUT * HZ, 1000));
347
348         fw_send_request(device->card, &orb->t, TCODE_WRITE_BLOCK_REQUEST,
349                         node_id, generation,
350                         device->node->max_speed, offset,
351                         &orb->pointer, sizeof orb->pointer,
352                         complete_transaction, orb);
353 }
354
355 static void sbp2_cancel_orbs(struct fw_unit *unit)
356 {
357         struct fw_device *device = fw_device(unit->device.parent);
358         struct sbp2_device *sd = unit->device.driver_data;
359         struct sbp2_orb *orb, *next;
360         struct list_head list;
361         unsigned long flags;
362
363         INIT_LIST_HEAD(&list);
364         spin_lock_irqsave(&device->card->lock, flags);
365         list_splice_init(&sd->orb_list, &list);
366         spin_unlock_irqrestore(&device->card->lock, flags);
367
368         list_for_each_entry_safe(orb, next, &list, link) {
369                 if (fw_cancel_transaction(device->card, &orb->t) == 0)
370                         continue;
371
372                 orb->rcode = RCODE_CANCELLED;
373                 orb->callback(orb, NULL);
374         }
375 }
376
377 static void orb_timer_callback(unsigned long data)
378 {
379         struct sbp2_device *sd = (struct sbp2_device *)data;
380
381         sbp2_cancel_orbs(sd->unit);
382 }
383
384 static void
385 complete_management_orb(struct sbp2_orb *base_orb, struct sbp2_status *status)
386 {
387         struct sbp2_management_orb *orb =
388             (struct sbp2_management_orb *)base_orb;
389
390         if (status)
391                 memcpy(&orb->status, status, sizeof *status);
392         complete(&orb->done);
393 }
394
395 static int
396 sbp2_send_management_orb(struct fw_unit *unit, int node_id, int generation,
397                          int function, int lun, void *response)
398 {
399         struct fw_device *device = fw_device(unit->device.parent);
400         struct sbp2_device *sd = unit->device.driver_data;
401         struct sbp2_management_orb *orb;
402         int retval = -ENOMEM;
403
404         orb = kzalloc(sizeof *orb, GFP_ATOMIC);
405         if (orb == NULL)
406                 return -ENOMEM;
407
408         /* The sbp2 device is going to send a block read request to
409          * read out the request from host memory, so map it for
410          * dma. */
411         orb->base.request_bus =
412                 dma_map_single(device->card->device, &orb->request,
413                                sizeof orb->request, DMA_TO_DEVICE);
414         if (dma_mapping_error(orb->base.request_bus))
415                 goto out;
416
417         orb->response_bus =
418                 dma_map_single(device->card->device, &orb->response,
419                                sizeof orb->response, DMA_FROM_DEVICE);
420         if (dma_mapping_error(orb->response_bus))
421                 goto out;
422
423         orb->request.response.high    = 0;
424         orb->request.response.low     = orb->response_bus;
425
426         orb->request.misc =
427                 management_orb_notify |
428                 management_orb_function(function) |
429                 management_orb_lun(lun);
430         orb->request.length =
431                 management_orb_response_length(sizeof orb->response);
432
433         orb->request.status_fifo.high = sd->address_handler.offset >> 32;
434         orb->request.status_fifo.low  = sd->address_handler.offset;
435
436         /* FIXME: Yeah, ok this isn't elegant, we hardwire exclusive
437          * login and 1 second reconnect time.  The reconnect setting
438          * is probably fine, but the exclusive login should be an
439          * option. */
440         if (function == SBP2_LOGIN_REQUEST) {
441                 orb->request.misc |=
442                         management_orb_exclusive |
443                         management_orb_reconnect(0);
444         }
445
446         fw_memcpy_to_be32(&orb->request, &orb->request, sizeof orb->request);
447
448         init_completion(&orb->done);
449         orb->base.callback = complete_management_orb;
450         sbp2_send_orb(&orb->base, unit,
451                       node_id, generation, sd->management_agent_address);
452
453         wait_for_completion(&orb->done);
454
455         /* FIXME: Handle bus reset race here. */
456
457         retval = -EIO;
458         if (orb->base.rcode != RCODE_COMPLETE) {
459                 fw_error("management write failed, rcode 0x%02x\n",
460                          orb->base.rcode);
461                 goto out;
462         }
463
464         if (orb->base.rcode == RCODE_CANCELLED) {
465                 fw_error("orb reply timed out, rcode=0x%02x\n",
466                          orb->base.rcode);
467                 goto out;
468         }
469
470         if (status_get_response(orb->status) != 0 ||
471             status_get_sbp_status(orb->status) != 0) {
472                 fw_error("error status: %d:%d\n",
473                          status_get_response(orb->status),
474                          status_get_sbp_status(orb->status));
475                 goto out;
476         }
477
478         retval = 0;
479  out:
480         dma_unmap_single(device->card->device, orb->base.request_bus,
481                          sizeof orb->request, DMA_TO_DEVICE);
482         dma_unmap_single(device->card->device, orb->response_bus,
483                          sizeof orb->response, DMA_FROM_DEVICE);
484
485         if (response)
486                 fw_memcpy_from_be32(response,
487                                     orb->response, sizeof orb->response);
488         kfree(orb);
489
490         return retval;
491 }
492
493 static void
494 complete_agent_reset_write(struct fw_card *card, int rcode,
495                            void *payload, size_t length, void *data)
496 {
497         struct fw_transaction *t = data;
498
499         fw_notify("agent reset write rcode=%d\n", rcode);
500         kfree(t);
501 }
502
503 static int sbp2_agent_reset(struct fw_unit *unit)
504 {
505         struct fw_device *device = fw_device(unit->device.parent);
506         struct sbp2_device *sd = unit->device.driver_data;
507         struct fw_transaction *t;
508         static u32 zero;
509
510         t = kzalloc(sizeof *t, GFP_ATOMIC);
511         if (t == NULL)
512                 return -ENOMEM;
513
514         fw_send_request(device->card, t, TCODE_WRITE_QUADLET_REQUEST,
515                         sd->node_id, sd->generation, SCODE_400,
516                         sd->command_block_agent_address + SBP2_AGENT_RESET,
517                         &zero, sizeof zero, complete_agent_reset_write, t);
518
519         return 0;
520 }
521
522 static int add_scsi_devices(struct fw_unit *unit);
523 static void remove_scsi_devices(struct fw_unit *unit);
524 static void sbp2_reconnect(struct work_struct *work);
525
526 static void sbp2_login(struct work_struct *work)
527 {
528         struct sbp2_device *sd =
529                 container_of(work, struct sbp2_device, work.work);
530         struct fw_unit *unit = sd->unit;
531         struct fw_device *device = fw_device(unit->device.parent);
532         struct sbp2_login_response response;
533         int generation, node_id, local_node_id, lun, retval;
534
535         /* FIXME: Make this work for multi-lun devices. */
536         lun = 0;
537
538         generation    = device->card->generation;
539         node_id       = device->node->node_id;
540         local_node_id = device->card->local_node->node_id;
541
542         if (sbp2_send_management_orb(unit, node_id, generation,
543                                      SBP2_LOGIN_REQUEST, lun, &response) < 0) {
544                 if (sd->retries++ < 5) {
545                         fw_error("login attempt %d for %s failed, "
546                                  "rescheduling\n",
547                                  sd->retries, unit->device.bus_id);
548                         schedule_delayed_work(&sd->work, DIV_ROUND_UP(HZ, 5));
549                 } else {
550                         fw_error("failed to login to %s\n",
551                                  unit->device.bus_id);
552                         remove_scsi_devices(unit);
553                 }
554                 return;
555         }
556
557         sd->generation   = generation;
558         sd->node_id      = node_id;
559         sd->address_high = local_node_id << 16;
560
561         /* Get command block agent offset and login id. */
562         sd->command_block_agent_address =
563                 ((u64) response.command_block_agent.high << 32) |
564                 response.command_block_agent.low;
565         sd->login_id = login_response_get_login_id(response);
566
567         fw_notify("logged in to sbp2 unit %s\n", unit->device.bus_id);
568         fw_notify(" - management_agent_address: 0x%012llx\n",
569                   (unsigned long long) sd->management_agent_address);
570         fw_notify(" - command_block_agent_address: 0x%012llx\n",
571                   (unsigned long long) sd->command_block_agent_address);
572         fw_notify(" - status write address: 0x%012llx\n",
573                   (unsigned long long) sd->address_handler.offset);
574
575 #if 0
576         /* FIXME: The linux1394 sbp2 does this last step. */
577         sbp2_set_busy_timeout(scsi_id);
578 #endif
579
580         PREPARE_DELAYED_WORK(&sd->work, sbp2_reconnect);
581         sbp2_agent_reset(unit);
582
583         retval = add_scsi_devices(unit);
584         if (retval < 0) {
585                 sbp2_send_management_orb(unit, sd->node_id, sd->generation,
586                                          SBP2_LOGOUT_REQUEST, sd->login_id,
587                                          NULL);
588                 /* Set this back to sbp2_login so we fall back and
589                  * retry login on bus reset. */
590                 PREPARE_DELAYED_WORK(&sd->work, sbp2_login);
591         }
592 }
593
594 static int sbp2_probe(struct device *dev)
595 {
596         struct fw_unit *unit = fw_unit(dev);
597         struct fw_device *device = fw_device(unit->device.parent);
598         struct sbp2_device *sd;
599         struct fw_csr_iterator ci;
600         int i, key, value;
601         u32 model, firmware_revision;
602
603         sd = kzalloc(sizeof *sd, GFP_KERNEL);
604         if (sd == NULL)
605                 return -ENOMEM;
606
607         unit->device.driver_data = sd;
608         sd->unit = unit;
609         INIT_LIST_HEAD(&sd->orb_list);
610         setup_timer(&sd->orb_timer, orb_timer_callback, (unsigned long)sd);
611
612         sd->address_handler.length = 0x100;
613         sd->address_handler.address_callback = sbp2_status_write;
614         sd->address_handler.callback_data = sd;
615
616         if (fw_core_add_address_handler(&sd->address_handler,
617                                         &fw_high_memory_region) < 0) {
618                 kfree(sd);
619                 return -EBUSY;
620         }
621
622         if (fw_device_enable_phys_dma(device) < 0) {
623                 fw_core_remove_address_handler(&sd->address_handler);
624                 kfree(sd);
625                 return -EBUSY;
626         }
627
628         /* Scan unit directory to get management agent address,
629          * firmware revison and model.  Initialize firmware_revision
630          * and model to values that wont match anything in our table. */
631         firmware_revision = 0xff000000;
632         model = 0xff000000;
633         fw_csr_iterator_init(&ci, unit->directory);
634         while (fw_csr_iterator_next(&ci, &key, &value)) {
635                 switch (key) {
636                 case CSR_DEPENDENT_INFO | CSR_OFFSET:
637                         sd->management_agent_address =
638                                 0xfffff0000000ULL + 4 * value;
639                         break;
640                 case SBP2_FIRMWARE_REVISION:
641                         firmware_revision = value;
642                         break;
643                 case CSR_MODEL:
644                         model = value;
645                         break;
646                 }
647         }
648
649         for (i = 0; i < ARRAY_SIZE(sbp2_workarounds_table); i++) {
650                 if (sbp2_workarounds_table[i].firmware_revision !=
651                     (firmware_revision & 0xffffff00))
652                         continue;
653                 if (sbp2_workarounds_table[i].model != model &&
654                     sbp2_workarounds_table[i].model != ~0)
655                         continue;
656                 sd->workarounds |= sbp2_workarounds_table[i].workarounds;
657                 break;
658         }
659
660         if (sd->workarounds)
661                 fw_notify("Workarounds for node %s: 0x%x "
662                           "(firmware_revision 0x%06x, model_id 0x%06x)\n",
663                           unit->device.bus_id,
664                           sd->workarounds, firmware_revision, model);
665
666         /* We schedule work to do the login so we can easily
667          * reschedule retries. */
668         INIT_DELAYED_WORK(&sd->work, sbp2_login);
669         schedule_delayed_work(&sd->work, 0);
670
671         return 0;
672 }
673
674 static int sbp2_remove(struct device *dev)
675 {
676         struct fw_unit *unit = fw_unit(dev);
677         struct sbp2_device *sd = unit->device.driver_data;
678
679         sbp2_send_management_orb(unit, sd->node_id, sd->generation,
680                                  SBP2_LOGOUT_REQUEST, sd->login_id, NULL);
681
682         remove_scsi_devices(unit);
683         del_timer_sync(&sd->orb_timer);
684
685         fw_core_remove_address_handler(&sd->address_handler);
686         kfree(sd);
687
688         fw_notify("removed sbp2 unit %s\n", dev->bus_id);
689
690         return 0;
691 }
692
693 static void sbp2_reconnect(struct work_struct *work)
694 {
695         struct sbp2_device *sd =
696                 container_of(work, struct sbp2_device, work.work);
697         struct fw_unit *unit = sd->unit;
698         struct fw_device *device = fw_device(unit->device.parent);
699         int generation, node_id, local_node_id;
700
701         generation    = device->card->generation;
702         node_id       = device->node->node_id;
703         local_node_id = device->card->local_node->node_id;
704
705         if (sbp2_send_management_orb(unit, node_id, generation,
706                                      SBP2_RECONNECT_REQUEST,
707                                      sd->login_id, NULL) < 0) {
708                 if (sd->retries++ < 5) {
709                         fw_error("reconnect attempt %d for %s failed, "
710                                  "rescheduling\n",
711                                  sd->retries, unit->device.bus_id);
712                 } else {
713                         fw_error("failed to reconnect to %s\n",
714                                  unit->device.bus_id);
715                         /* Fall back and try to log in again. */
716                         sd->retries = 0;
717                         PREPARE_DELAYED_WORK(&sd->work, sbp2_login);
718                 }
719                 schedule_delayed_work(&sd->work, DIV_ROUND_UP(HZ, 5));
720                 return;
721         }
722
723         sd->generation   = generation;
724         sd->node_id      = node_id;
725         sd->address_high = local_node_id << 16;
726
727         fw_notify("reconnected to unit %s\n", unit->device.bus_id);
728         sbp2_agent_reset(unit);
729         sbp2_cancel_orbs(unit);
730 }
731
732 static void sbp2_update(struct fw_unit *unit)
733 {
734         struct fw_device *device = fw_device(unit->device.parent);
735         struct sbp2_device *sd = unit->device.driver_data;
736
737         sd->retries = 0;
738         fw_device_enable_phys_dma(device);
739         schedule_delayed_work(&sd->work, 0);
740 }
741
742 #define SBP2_UNIT_SPEC_ID_ENTRY 0x0000609e
743 #define SBP2_SW_VERSION_ENTRY   0x00010483
744
745 static const struct fw_device_id sbp2_id_table[] = {
746         {
747                 .match_flags  = FW_MATCH_SPECIFIER_ID | FW_MATCH_VERSION,
748                 .specifier_id = SBP2_UNIT_SPEC_ID_ENTRY,
749                 .version      = SBP2_SW_VERSION_ENTRY,
750         },
751         { }
752 };
753
754 static struct fw_driver sbp2_driver = {
755         .driver   = {
756                 .owner  = THIS_MODULE,
757                 .name   = sbp2_driver_name,
758                 .bus    = &fw_bus_type,
759                 .probe  = sbp2_probe,
760                 .remove = sbp2_remove,
761         },
762         .update   = sbp2_update,
763         .id_table = sbp2_id_table,
764 };
765
766 static unsigned int sbp2_status_to_sense_data(u8 * sbp2_status, u8 * sense_data)
767 {
768         sense_data[0] = 0x70;
769         sense_data[1] = 0x0;
770         sense_data[2] = sbp2_status[1];
771         sense_data[3] = sbp2_status[4];
772         sense_data[4] = sbp2_status[5];
773         sense_data[5] = sbp2_status[6];
774         sense_data[6] = sbp2_status[7];
775         sense_data[7] = 10;
776         sense_data[8] = sbp2_status[8];
777         sense_data[9] = sbp2_status[9];
778         sense_data[10] = sbp2_status[10];
779         sense_data[11] = sbp2_status[11];
780         sense_data[12] = sbp2_status[2];
781         sense_data[13] = sbp2_status[3];
782         sense_data[14] = sbp2_status[12];
783         sense_data[15] = sbp2_status[13];
784
785         switch (sbp2_status[0] & 0x3f) {
786         case SAM_STAT_GOOD:
787                 return DID_OK;
788
789         case SAM_STAT_CHECK_CONDITION:
790                 /* return CHECK_CONDITION << 1 | DID_OK << 16; */
791                 return DID_OK;
792
793         case SAM_STAT_BUSY:
794                 return DID_BUS_BUSY;
795
796         case SAM_STAT_CONDITION_MET:
797         case SAM_STAT_RESERVATION_CONFLICT:
798         case SAM_STAT_COMMAND_TERMINATED:
799         default:
800                 return DID_ERROR;
801         }
802 }
803
804 static void
805 complete_command_orb(struct sbp2_orb *base_orb, struct sbp2_status *status)
806 {
807         struct sbp2_command_orb *orb = (struct sbp2_command_orb *)base_orb;
808         struct fw_unit *unit = orb->unit;
809         struct fw_device *device = fw_device(unit->device.parent);
810         struct scatterlist *sg;
811         int result;
812
813         if (status != NULL) {
814                 if (status_get_dead(*status)) {
815                         fw_notify("agent died, issuing agent reset\n");
816                         sbp2_agent_reset(unit);
817                 }
818
819                 switch (status_get_response(*status)) {
820                 case SBP2_STATUS_REQUEST_COMPLETE:
821                         result = DID_OK;
822                         break;
823                 case SBP2_STATUS_TRANSPORT_FAILURE:
824                         result = DID_BUS_BUSY;
825                         break;
826                 case SBP2_STATUS_ILLEGAL_REQUEST:
827                 case SBP2_STATUS_VENDOR_DEPENDENT:
828                 default:
829                         result = DID_ERROR;
830                         break;
831                 }
832
833                 if (result == DID_OK && status_get_len(*status) > 1)
834                         result = sbp2_status_to_sense_data(status_get_data(*status),
835                                                            orb->cmd->sense_buffer);
836         } else {
837                 /* If the orb completes with status == NULL, something
838                  * went wrong, typically a bus reset happened mid-orb
839                  * or when sending the write (less likely). */
840                 fw_notify("no command orb status, rcode=%d\n",
841                           orb->base.rcode);
842                 result = DID_BUS_BUSY;
843         }
844
845         dma_unmap_single(device->card->device, orb->base.request_bus,
846                          sizeof orb->request, DMA_TO_DEVICE);
847
848         if (orb->cmd->use_sg > 0) {
849                 sg = (struct scatterlist *)orb->cmd->request_buffer;
850                 dma_unmap_sg(device->card->device, sg, orb->cmd->use_sg,
851                              orb->cmd->sc_data_direction);
852         }
853
854         if (orb->page_table_bus != 0)
855                 dma_unmap_single(device->card->device, orb->page_table_bus,
856                                  sizeof orb->page_table_bus, DMA_TO_DEVICE);
857
858         if (orb->request_buffer_bus != 0)
859                 dma_unmap_single(device->card->device, orb->request_buffer_bus,
860                                  sizeof orb->request_buffer_bus,
861                                  DMA_FROM_DEVICE);
862
863         orb->cmd->result = result << 16;
864         orb->done(orb->cmd);
865
866         kfree(orb);
867 }
868
869 static void sbp2_command_orb_map_scatterlist(struct sbp2_command_orb *orb)
870 {
871         struct fw_unit *unit =
872                 (struct fw_unit *)orb->cmd->device->host->hostdata[0];
873         struct fw_device *device = fw_device(unit->device.parent);
874         struct sbp2_device *sd = unit->device.driver_data;
875         struct scatterlist *sg;
876         int sg_len, l, i, j, count;
877         size_t size;
878         dma_addr_t sg_addr;
879
880         sg = (struct scatterlist *)orb->cmd->request_buffer;
881         count = dma_map_sg(device->card->device, sg, orb->cmd->use_sg,
882                            orb->cmd->sc_data_direction);
883
884         /* Handle the special case where there is only one element in
885          * the scatter list by converting it to an immediate block
886          * request. This is also a workaround for broken devices such
887          * as the second generation iPod which doesn't support page
888          * tables. */
889         if (count == 1 && sg_dma_len(sg) < SBP2_MAX_SG_ELEMENT_LENGTH) {
890                 orb->request.data_descriptor.high = sd->address_high;
891                 orb->request.data_descriptor.low  = sg_dma_address(sg);
892                 orb->request.misc |=
893                         command_orb_data_size(sg_dma_len(sg));
894                 return;
895         }
896
897         /* Convert the scatterlist to an sbp2 page table.  If any
898          * scatterlist entries are too big for sbp2 we split the as we go. */
899         for (i = 0, j = 0; i < count; i++) {
900                 sg_len = sg_dma_len(sg + i);
901                 sg_addr = sg_dma_address(sg + i);
902                 while (sg_len) {
903                         l = min(sg_len, SBP2_MAX_SG_ELEMENT_LENGTH);
904                         orb->page_table[j].low = sg_addr;
905                         orb->page_table[j].high = (l << 16);
906                         sg_addr += l;
907                         sg_len -= l;
908                         j++;
909                 }
910         }
911
912         size = sizeof orb->page_table[0] * j;
913
914         /* The data_descriptor pointer is the one case where we need
915          * to fill in the node ID part of the address.  All other
916          * pointers assume that the data referenced reside on the
917          * initiator (i.e. us), but data_descriptor can refer to data
918          * on other nodes so we need to put our ID in descriptor.high. */
919
920         orb->page_table_bus =
921                 dma_map_single(device->card->device, orb->page_table,
922                                size, DMA_TO_DEVICE);
923         orb->request.data_descriptor.high = sd->address_high;
924         orb->request.data_descriptor.low  = orb->page_table_bus;
925         orb->request.misc |=
926                 command_orb_page_table_present |
927                 command_orb_data_size(j);
928
929         fw_memcpy_to_be32(orb->page_table, orb->page_table, size);
930 }
931
932 static void sbp2_command_orb_map_buffer(struct sbp2_command_orb *orb)
933 {
934         struct fw_unit *unit =
935                 (struct fw_unit *)orb->cmd->device->host->hostdata[0];
936         struct fw_device *device = fw_device(unit->device.parent);
937         struct sbp2_device *sd = unit->device.driver_data;
938
939         /* As for map_scatterlist, we need to fill in the high bits of
940          * the data_descriptor pointer. */
941
942         orb->request_buffer_bus =
943                 dma_map_single(device->card->device,
944                                orb->cmd->request_buffer,
945                                orb->cmd->request_bufflen,
946                                orb->cmd->sc_data_direction);
947         orb->request.data_descriptor.high = sd->address_high;
948         orb->request.data_descriptor.low  = orb->request_buffer_bus;
949         orb->request.misc |=
950                 command_orb_data_size(orb->cmd->request_bufflen);
951 }
952
953 /* SCSI stack integration */
954
955 static int sbp2_scsi_queuecommand(struct scsi_cmnd *cmd, scsi_done_fn_t done)
956 {
957         struct fw_unit *unit = (struct fw_unit *)cmd->device->host->hostdata[0];
958         struct fw_device *device = fw_device(unit->device.parent);
959         struct sbp2_device *sd = unit->device.driver_data;
960         struct sbp2_command_orb *orb;
961
962         /* Bidirectional commands are not yet implemented, and unknown
963          * transfer direction not handled. */
964         if (cmd->sc_data_direction == DMA_BIDIRECTIONAL) {
965                 fw_error("Cannot handle DMA_BIDIRECTIONAL - rejecting command");
966                 goto fail_alloc;
967         }
968
969         orb = kzalloc(sizeof *orb, GFP_ATOMIC);
970         if (orb == NULL) {
971                 fw_notify("failed to alloc orb\n");
972                 goto fail_alloc;
973         }
974
975         orb->base.request_bus =
976                 dma_map_single(device->card->device, &orb->request,
977                                sizeof orb->request, DMA_TO_DEVICE);
978         if (dma_mapping_error(orb->base.request_bus))
979                 goto fail_mapping;
980
981         orb->unit = unit;
982         orb->done = done;
983         orb->cmd  = cmd;
984
985         orb->request.next.high   = SBP2_ORB_NULL;
986         orb->request.next.low    = 0x0;
987         /* At speed 100 we can do 512 bytes per packet, at speed 200,
988          * 1024 bytes per packet etc.  The SBP-2 max_payload field
989          * specifies the max payload size as 2 ^ (max_payload + 2), so
990          * if we set this to max_speed + 7, we get the right value. */
991         orb->request.misc =
992                 command_orb_max_payload(device->node->max_speed + 7) |
993                 command_orb_speed(device->node->max_speed) |
994                 command_orb_notify;
995
996         if (cmd->sc_data_direction == DMA_FROM_DEVICE)
997                 orb->request.misc |=
998                         command_orb_direction(SBP2_DIRECTION_FROM_MEDIA);
999         else if (cmd->sc_data_direction == DMA_TO_DEVICE)
1000                 orb->request.misc |=
1001                         command_orb_direction(SBP2_DIRECTION_TO_MEDIA);
1002
1003         if (cmd->use_sg) {
1004                 sbp2_command_orb_map_scatterlist(orb);
1005         } else if (cmd->request_bufflen > SBP2_MAX_SG_ELEMENT_LENGTH) {
1006                 /* FIXME: Need to split this into a sg list... but
1007                  * could we get the scsi or blk layer to do that by
1008                  * reporting our max supported block size? */
1009                 fw_error("command > 64k\n");
1010                 goto fail_bufflen;
1011         } else if (cmd->request_bufflen > 0) {
1012                 sbp2_command_orb_map_buffer(orb);
1013         }
1014
1015         fw_memcpy_to_be32(&orb->request, &orb->request, sizeof orb->request);
1016
1017         memset(orb->request.command_block,
1018                0, sizeof orb->request.command_block);
1019         memcpy(orb->request.command_block, cmd->cmnd, COMMAND_SIZE(*cmd->cmnd));
1020
1021         orb->base.callback = complete_command_orb;
1022
1023         sbp2_send_orb(&orb->base, unit, sd->node_id, sd->generation,
1024                       sd->command_block_agent_address + SBP2_ORB_POINTER);
1025
1026         return 0;
1027
1028  fail_bufflen:
1029         dma_unmap_single(device->card->device, orb->base.request_bus,
1030                          sizeof orb->request, DMA_TO_DEVICE);
1031  fail_mapping:
1032         kfree(orb);
1033  fail_alloc:
1034         cmd->result = DID_ERROR << 16;
1035         done(cmd);
1036         return 0;
1037 }
1038
1039 static int sbp2_scsi_slave_alloc(struct scsi_device *sdev)
1040 {
1041         struct fw_unit *unit = (struct fw_unit *)sdev->host->hostdata[0];
1042         struct sbp2_device *sd = unit->device.driver_data;
1043
1044         sdev->allow_restart = 1;
1045
1046         if (sd->workarounds & SBP2_WORKAROUND_INQUIRY_36)
1047                 sdev->inquiry_len = 36;
1048         return 0;
1049 }
1050
1051 static int sbp2_scsi_slave_configure(struct scsi_device *sdev)
1052 {
1053         struct fw_unit *unit = (struct fw_unit *)sdev->host->hostdata[0];
1054         struct sbp2_device *sd = unit->device.driver_data;
1055
1056         sdev->use_10_for_rw = 1;
1057
1058         if (sdev->type == TYPE_ROM)
1059                 sdev->use_10_for_ms = 1;
1060         if (sdev->type == TYPE_DISK &&
1061             sd->workarounds & SBP2_WORKAROUND_MODE_SENSE_8)
1062                 sdev->skip_ms_page_8 = 1;
1063         if (sd->workarounds & SBP2_WORKAROUND_FIX_CAPACITY) {
1064                 fw_notify("setting fix_capacity for %s\n", unit->device.bus_id);
1065                 sdev->fix_capacity = 1;
1066         }
1067
1068         return 0;
1069 }
1070
1071 /*
1072  * Called by scsi stack when something has really gone wrong.  Usually
1073  * called when a command has timed-out for some reason.
1074  */
1075 static int sbp2_scsi_abort(struct scsi_cmnd *cmd)
1076 {
1077         struct fw_unit *unit = (struct fw_unit *)cmd->device->host->hostdata[0];
1078
1079         fw_notify("sbp2_scsi_abort\n");
1080
1081         sbp2_cancel_orbs(unit);
1082
1083         return SUCCESS;
1084 }
1085
1086 static struct scsi_host_template scsi_driver_template = {
1087         .module                 = THIS_MODULE,
1088         .name                   = "SBP-2 IEEE-1394",
1089         .proc_name              = (char *)sbp2_driver_name,
1090         .queuecommand           = sbp2_scsi_queuecommand,
1091         .slave_alloc            = sbp2_scsi_slave_alloc,
1092         .slave_configure        = sbp2_scsi_slave_configure,
1093         .eh_abort_handler       = sbp2_scsi_abort,
1094         .this_id                = -1,
1095         .sg_tablesize           = SG_ALL,
1096         .use_clustering         = ENABLE_CLUSTERING,
1097         .cmd_per_lun            = 1,
1098         .can_queue              = 1,
1099 };
1100
1101 static int add_scsi_devices(struct fw_unit *unit)
1102 {
1103         struct sbp2_device *sd = unit->device.driver_data;
1104         int retval, lun;
1105
1106         if (sd->scsi_host != NULL)
1107                 return 0;
1108
1109         sd->scsi_host = scsi_host_alloc(&scsi_driver_template,
1110                                         sizeof(unsigned long));
1111         if (sd->scsi_host == NULL) {
1112                 fw_error("failed to register scsi host\n");
1113                 return -1;
1114         }
1115
1116         sd->scsi_host->hostdata[0] = (unsigned long)unit;
1117         retval = scsi_add_host(sd->scsi_host, &unit->device);
1118         if (retval < 0) {
1119                 fw_error("failed to add scsi host\n");
1120                 scsi_host_put(sd->scsi_host);
1121                 return retval;
1122         }
1123
1124         /* FIXME: Loop over luns here. */
1125         lun = 0;
1126         retval = scsi_add_device(sd->scsi_host, 0, 0, lun);
1127         if (retval < 0) {
1128                 fw_error("failed to add scsi device\n");
1129                 scsi_remove_host(sd->scsi_host);
1130                 scsi_host_put(sd->scsi_host);
1131                 return retval;
1132         }
1133
1134         return 0;
1135 }
1136
1137 static void remove_scsi_devices(struct fw_unit *unit)
1138 {
1139         struct sbp2_device *sd = unit->device.driver_data;
1140
1141         if (sd->scsi_host != NULL) {
1142                 scsi_remove_host(sd->scsi_host);
1143                 scsi_host_put(sd->scsi_host);
1144         }
1145         sd->scsi_host = NULL;
1146 }
1147
1148 MODULE_AUTHOR("Kristian Hoegsberg <krh@bitplanet.net>");
1149 MODULE_DESCRIPTION("SCSI over IEEE1394");
1150 MODULE_LICENSE("GPL");
1151 MODULE_DEVICE_TABLE(ieee1394, sbp2_id_table);
1152
1153 static int __init sbp2_init(void)
1154 {
1155         return driver_register(&sbp2_driver.driver);
1156 }
1157
1158 static void __exit sbp2_cleanup(void)
1159 {
1160         driver_unregister(&sbp2_driver.driver);
1161 }
1162
1163 module_init(sbp2_init);
1164 module_exit(sbp2_cleanup);