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