Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/avi/kvm
[linux-2.6] / drivers / block / sx8.c
1 /*
2  *  sx8.c: Driver for Promise SATA SX8 looks-like-I2O hardware
3  *
4  *  Copyright 2004-2005 Red Hat, Inc.
5  *
6  *  Author/maintainer:  Jeff Garzik <jgarzik@pobox.com>
7  *
8  *  This file is subject to the terms and conditions of the GNU General Public
9  *  License.  See the file "COPYING" in the main directory of this archive
10  *  for more details.
11  */
12
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/init.h>
16 #include <linux/pci.h>
17 #include <linux/slab.h>
18 #include <linux/spinlock.h>
19 #include <linux/blkdev.h>
20 #include <linux/sched.h>
21 #include <linux/interrupt.h>
22 #include <linux/compiler.h>
23 #include <linux/workqueue.h>
24 #include <linux/bitops.h>
25 #include <linux/delay.h>
26 #include <linux/time.h>
27 #include <linux/hdreg.h>
28 #include <linux/dma-mapping.h>
29 #include <linux/completion.h>
30 #include <asm/io.h>
31 #include <asm/uaccess.h>
32
33 #if 0
34 #define CARM_DEBUG
35 #define CARM_VERBOSE_DEBUG
36 #else
37 #undef CARM_DEBUG
38 #undef CARM_VERBOSE_DEBUG
39 #endif
40 #undef CARM_NDEBUG
41
42 #define DRV_NAME "sx8"
43 #define DRV_VERSION "1.0"
44 #define PFX DRV_NAME ": "
45
46 MODULE_AUTHOR("Jeff Garzik");
47 MODULE_LICENSE("GPL");
48 MODULE_DESCRIPTION("Promise SATA SX8 block driver");
49 MODULE_VERSION(DRV_VERSION);
50
51 /*
52  * SX8 hardware has a single message queue for all ATA ports.
53  * When this driver was written, the hardware (firmware?) would
54  * corrupt data eventually, if more than one request was outstanding.
55  * As one can imagine, having 8 ports bottlenecking on a single
56  * command hurts performance.
57  *
58  * Based on user reports, later versions of the hardware (firmware?)
59  * seem to be able to survive with more than one command queued.
60  *
61  * Therefore, we default to the safe option -- 1 command -- but
62  * allow the user to increase this.
63  *
64  * SX8 should be able to support up to ~60 queued commands (CARM_MAX_REQ),
65  * but problems seem to occur when you exceed ~30, even on newer hardware.
66  */
67 static int max_queue = 1;
68 module_param(max_queue, int, 0444);
69 MODULE_PARM_DESC(max_queue, "Maximum number of queued commands. (min==1, max==30, safe==1)");
70
71
72 #define NEXT_RESP(idx)  ((idx + 1) % RMSG_Q_LEN)
73
74 /* 0xf is just arbitrary, non-zero noise; this is sorta like poisoning */
75 #define TAG_ENCODE(tag) (((tag) << 16) | 0xf)
76 #define TAG_DECODE(tag) (((tag) >> 16) & 0x1f)
77 #define TAG_VALID(tag)  ((((tag) & 0xf) == 0xf) && (TAG_DECODE(tag) < 32))
78
79 /* note: prints function name for you */
80 #ifdef CARM_DEBUG
81 #define DPRINTK(fmt, args...) printk(KERN_ERR "%s: " fmt, __FUNCTION__, ## args)
82 #ifdef CARM_VERBOSE_DEBUG
83 #define VPRINTK(fmt, args...) printk(KERN_ERR "%s: " fmt, __FUNCTION__, ## args)
84 #else
85 #define VPRINTK(fmt, args...)
86 #endif  /* CARM_VERBOSE_DEBUG */
87 #else
88 #define DPRINTK(fmt, args...)
89 #define VPRINTK(fmt, args...)
90 #endif  /* CARM_DEBUG */
91
92 #ifdef CARM_NDEBUG
93 #define assert(expr)
94 #else
95 #define assert(expr) \
96         if(unlikely(!(expr))) {                                   \
97         printk(KERN_ERR "Assertion failed! %s,%s,%s,line=%d\n", \
98         #expr,__FILE__,__FUNCTION__,__LINE__);          \
99         }
100 #endif
101
102 /* defines only for the constants which don't work well as enums */
103 struct carm_host;
104
105 enum {
106         /* adapter-wide limits */
107         CARM_MAX_PORTS          = 8,
108         CARM_SHM_SIZE           = (4096 << 7),
109         CARM_MINORS_PER_MAJOR   = 256 / CARM_MAX_PORTS,
110         CARM_MAX_WAIT_Q         = CARM_MAX_PORTS + 1,
111
112         /* command message queue limits */
113         CARM_MAX_REQ            = 64,          /* max command msgs per host */
114         CARM_MSG_LOW_WATER      = (CARM_MAX_REQ / 4),        /* refill mark */
115
116         /* S/G limits, host-wide and per-request */
117         CARM_MAX_REQ_SG         = 32,        /* max s/g entries per request */
118         CARM_MAX_HOST_SG        = 600,          /* max s/g entries per host */
119         CARM_SG_LOW_WATER       = (CARM_MAX_HOST_SG / 4),   /* re-fill mark */
120
121         /* hardware registers */
122         CARM_IHQP               = 0x1c,
123         CARM_INT_STAT           = 0x10, /* interrupt status */
124         CARM_INT_MASK           = 0x14, /* interrupt mask */
125         CARM_HMUC               = 0x18, /* host message unit control */
126         RBUF_ADDR_LO            = 0x20, /* response msg DMA buf low 32 bits */
127         RBUF_ADDR_HI            = 0x24, /* response msg DMA buf high 32 bits */
128         RBUF_BYTE_SZ            = 0x28,
129         CARM_RESP_IDX           = 0x2c,
130         CARM_CMS0               = 0x30, /* command message size reg 0 */
131         CARM_LMUC               = 0x48,
132         CARM_HMPHA              = 0x6c,
133         CARM_INITC              = 0xb5,
134
135         /* bits in CARM_INT_{STAT,MASK} */
136         INT_RESERVED            = 0xfffffff0,
137         INT_WATCHDOG            = (1 << 3),     /* watchdog timer */
138         INT_Q_OVERFLOW          = (1 << 2),     /* cmd msg q overflow */
139         INT_Q_AVAILABLE         = (1 << 1),     /* cmd msg q has free space */
140         INT_RESPONSE            = (1 << 0),     /* response msg available */
141         INT_ACK_MASK            = INT_WATCHDOG | INT_Q_OVERFLOW,
142         INT_DEF_MASK            = INT_RESERVED | INT_Q_OVERFLOW |
143                                   INT_RESPONSE,
144
145         /* command messages, and related register bits */
146         CARM_HAVE_RESP          = 0x01,
147         CARM_MSG_READ           = 1,
148         CARM_MSG_WRITE          = 2,
149         CARM_MSG_VERIFY         = 3,
150         CARM_MSG_GET_CAPACITY   = 4,
151         CARM_MSG_FLUSH          = 5,
152         CARM_MSG_IOCTL          = 6,
153         CARM_MSG_ARRAY          = 8,
154         CARM_MSG_MISC           = 9,
155         CARM_CME                = (1 << 2),
156         CARM_RME                = (1 << 1),
157         CARM_WZBC               = (1 << 0),
158         CARM_RMI                = (1 << 0),
159         CARM_Q_FULL             = (1 << 3),
160         CARM_MSG_SIZE           = 288,
161         CARM_Q_LEN              = 48,
162
163         /* CARM_MSG_IOCTL messages */
164         CARM_IOC_SCAN_CHAN      = 5,    /* scan channels for devices */
165         CARM_IOC_GET_TCQ        = 13,   /* get tcq/ncq depth */
166         CARM_IOC_SET_TCQ        = 14,   /* set tcq/ncq depth */
167
168         IOC_SCAN_CHAN_NODEV     = 0x1f,
169         IOC_SCAN_CHAN_OFFSET    = 0x40,
170
171         /* CARM_MSG_ARRAY messages */
172         CARM_ARRAY_INFO         = 0,
173
174         ARRAY_NO_EXIST          = (1 << 31),
175
176         /* response messages */
177         RMSG_SZ                 = 8,    /* sizeof(struct carm_response) */
178         RMSG_Q_LEN              = 48,   /* resp. msg list length */
179         RMSG_OK                 = 1,    /* bit indicating msg was successful */
180                                         /* length of entire resp. msg buffer */
181         RBUF_LEN                = RMSG_SZ * RMSG_Q_LEN,
182
183         PDC_SHM_SIZE            = (4096 << 7), /* length of entire h/w buffer */
184
185         /* CARM_MSG_MISC messages */
186         MISC_GET_FW_VER         = 2,
187         MISC_ALLOC_MEM          = 3,
188         MISC_SET_TIME           = 5,
189
190         /* MISC_GET_FW_VER feature bits */
191         FW_VER_4PORT            = (1 << 2), /* 1=4 ports, 0=8 ports */
192         FW_VER_NON_RAID         = (1 << 1), /* 1=non-RAID firmware, 0=RAID */
193         FW_VER_ZCR              = (1 << 0), /* zero channel RAID (whatever that is) */
194
195         /* carm_host flags */
196         FL_NON_RAID             = FW_VER_NON_RAID,
197         FL_4PORT                = FW_VER_4PORT,
198         FL_FW_VER_MASK          = (FW_VER_NON_RAID | FW_VER_4PORT),
199         FL_DAC                  = (1 << 16),
200         FL_DYN_MAJOR            = (1 << 17),
201 };
202
203 enum {
204         CARM_SG_BOUNDARY        = 0xffffUL,         /* s/g segment boundary */
205 };
206
207 enum scatter_gather_types {
208         SGT_32BIT               = 0,
209         SGT_64BIT               = 1,
210 };
211
212 enum host_states {
213         HST_INVALID,            /* invalid state; never used */
214         HST_ALLOC_BUF,          /* setting up master SHM area */
215         HST_ERROR,              /* we never leave here */
216         HST_PORT_SCAN,          /* start dev scan */
217         HST_DEV_SCAN_START,     /* start per-device probe */
218         HST_DEV_SCAN,           /* continue per-device probe */
219         HST_DEV_ACTIVATE,       /* activate devices we found */
220         HST_PROBE_FINISHED,     /* probe is complete */
221         HST_PROBE_START,        /* initiate probe */
222         HST_SYNC_TIME,          /* tell firmware what time it is */
223         HST_GET_FW_VER,         /* get firmware version, adapter port cnt */
224 };
225
226 #ifdef CARM_DEBUG
227 static const char *state_name[] = {
228         "HST_INVALID",
229         "HST_ALLOC_BUF",
230         "HST_ERROR",
231         "HST_PORT_SCAN",
232         "HST_DEV_SCAN_START",
233         "HST_DEV_SCAN",
234         "HST_DEV_ACTIVATE",
235         "HST_PROBE_FINISHED",
236         "HST_PROBE_START",
237         "HST_SYNC_TIME",
238         "HST_GET_FW_VER",
239 };
240 #endif
241
242 struct carm_port {
243         unsigned int                    port_no;
244         struct gendisk                  *disk;
245         struct carm_host                *host;
246
247         /* attached device characteristics */
248         u64                             capacity;
249         char                            name[41];
250         u16                             dev_geom_head;
251         u16                             dev_geom_sect;
252         u16                             dev_geom_cyl;
253 };
254
255 struct carm_request {
256         unsigned int                    tag;
257         int                             n_elem;
258         unsigned int                    msg_type;
259         unsigned int                    msg_subtype;
260         unsigned int                    msg_bucket;
261         struct request                  *rq;
262         struct carm_port                *port;
263         struct scatterlist              sg[CARM_MAX_REQ_SG];
264 };
265
266 struct carm_host {
267         unsigned long                   flags;
268         void                            __iomem *mmio;
269         void                            *shm;
270         dma_addr_t                      shm_dma;
271
272         int                             major;
273         int                             id;
274         char                            name[32];
275
276         spinlock_t                      lock;
277         struct pci_dev                  *pdev;
278         unsigned int                    state;
279         u32                             fw_ver;
280
281         struct request_queue            *oob_q;
282         unsigned int                    n_oob;
283
284         unsigned int                    hw_sg_used;
285
286         unsigned int                    resp_idx;
287
288         unsigned int                    wait_q_prod;
289         unsigned int                    wait_q_cons;
290         struct request_queue            *wait_q[CARM_MAX_WAIT_Q];
291
292         unsigned int                    n_msgs;
293         u64                             msg_alloc;
294         struct carm_request             req[CARM_MAX_REQ];
295         void                            *msg_base;
296         dma_addr_t                      msg_dma;
297
298         int                             cur_scan_dev;
299         unsigned long                   dev_active;
300         unsigned long                   dev_present;
301         struct carm_port                port[CARM_MAX_PORTS];
302
303         struct work_struct              fsm_task;
304
305         struct completion               probe_comp;
306 };
307
308 struct carm_response {
309         __le32 ret_handle;
310         __le32 status;
311 }  __attribute__((packed));
312
313 struct carm_msg_sg {
314         __le32 start;
315         __le32 len;
316 }  __attribute__((packed));
317
318 struct carm_msg_rw {
319         u8 type;
320         u8 id;
321         u8 sg_count;
322         u8 sg_type;
323         __le32 handle;
324         __le32 lba;
325         __le16 lba_count;
326         __le16 lba_high;
327         struct carm_msg_sg sg[32];
328 }  __attribute__((packed));
329
330 struct carm_msg_allocbuf {
331         u8 type;
332         u8 subtype;
333         u8 n_sg;
334         u8 sg_type;
335         __le32 handle;
336         __le32 addr;
337         __le32 len;
338         __le32 evt_pool;
339         __le32 n_evt;
340         __le32 rbuf_pool;
341         __le32 n_rbuf;
342         __le32 msg_pool;
343         __le32 n_msg;
344         struct carm_msg_sg sg[8];
345 }  __attribute__((packed));
346
347 struct carm_msg_ioctl {
348         u8 type;
349         u8 subtype;
350         u8 array_id;
351         u8 reserved1;
352         __le32 handle;
353         __le32 data_addr;
354         u32 reserved2;
355 }  __attribute__((packed));
356
357 struct carm_msg_sync_time {
358         u8 type;
359         u8 subtype;
360         u16 reserved1;
361         __le32 handle;
362         u32 reserved2;
363         __le32 timestamp;
364 }  __attribute__((packed));
365
366 struct carm_msg_get_fw_ver {
367         u8 type;
368         u8 subtype;
369         u16 reserved1;
370         __le32 handle;
371         __le32 data_addr;
372         u32 reserved2;
373 }  __attribute__((packed));
374
375 struct carm_fw_ver {
376         __le32 version;
377         u8 features;
378         u8 reserved1;
379         u16 reserved2;
380 }  __attribute__((packed));
381
382 struct carm_array_info {
383         __le32 size;
384
385         __le16 size_hi;
386         __le16 stripe_size;
387
388         __le32 mode;
389
390         __le16 stripe_blk_sz;
391         __le16 reserved1;
392
393         __le16 cyl;
394         __le16 head;
395
396         __le16 sect;
397         u8 array_id;
398         u8 reserved2;
399
400         char name[40];
401
402         __le32 array_status;
403
404         /* device list continues beyond this point? */
405 }  __attribute__((packed));
406
407 static int carm_init_one (struct pci_dev *pdev, const struct pci_device_id *ent);
408 static void carm_remove_one (struct pci_dev *pdev);
409 static int carm_bdev_getgeo(struct block_device *bdev, struct hd_geometry *geo);
410
411 static struct pci_device_id carm_pci_tbl[] = {
412         { PCI_VENDOR_ID_PROMISE, 0x8000, PCI_ANY_ID, PCI_ANY_ID, 0, 0, },
413         { PCI_VENDOR_ID_PROMISE, 0x8002, PCI_ANY_ID, PCI_ANY_ID, 0, 0, },
414         { }     /* terminate list */
415 };
416 MODULE_DEVICE_TABLE(pci, carm_pci_tbl);
417
418 static struct pci_driver carm_driver = {
419         .name           = DRV_NAME,
420         .id_table       = carm_pci_tbl,
421         .probe          = carm_init_one,
422         .remove         = carm_remove_one,
423 };
424
425 static struct block_device_operations carm_bd_ops = {
426         .owner          = THIS_MODULE,
427         .getgeo         = carm_bdev_getgeo,
428 };
429
430 static unsigned int carm_host_id;
431 static unsigned long carm_major_alloc;
432
433
434
435 static int carm_bdev_getgeo(struct block_device *bdev, struct hd_geometry *geo)
436 {
437         struct carm_port *port = bdev->bd_disk->private_data;
438
439         geo->heads = (u8) port->dev_geom_head;
440         geo->sectors = (u8) port->dev_geom_sect;
441         geo->cylinders = port->dev_geom_cyl;
442         return 0;
443 }
444
445 static const u32 msg_sizes[] = { 32, 64, 128, CARM_MSG_SIZE };
446
447 static inline int carm_lookup_bucket(u32 msg_size)
448 {
449         int i;
450
451         for (i = 0; i < ARRAY_SIZE(msg_sizes); i++)
452                 if (msg_size <= msg_sizes[i])
453                         return i;
454
455         return -ENOENT;
456 }
457
458 static void carm_init_buckets(void __iomem *mmio)
459 {
460         unsigned int i;
461
462         for (i = 0; i < ARRAY_SIZE(msg_sizes); i++)
463                 writel(msg_sizes[i], mmio + CARM_CMS0 + (4 * i));
464 }
465
466 static inline void *carm_ref_msg(struct carm_host *host,
467                                  unsigned int msg_idx)
468 {
469         return host->msg_base + (msg_idx * CARM_MSG_SIZE);
470 }
471
472 static inline dma_addr_t carm_ref_msg_dma(struct carm_host *host,
473                                           unsigned int msg_idx)
474 {
475         return host->msg_dma + (msg_idx * CARM_MSG_SIZE);
476 }
477
478 static int carm_send_msg(struct carm_host *host,
479                          struct carm_request *crq)
480 {
481         void __iomem *mmio = host->mmio;
482         u32 msg = (u32) carm_ref_msg_dma(host, crq->tag);
483         u32 cm_bucket = crq->msg_bucket;
484         u32 tmp;
485         int rc = 0;
486
487         VPRINTK("ENTER\n");
488
489         tmp = readl(mmio + CARM_HMUC);
490         if (tmp & CARM_Q_FULL) {
491 #if 0
492                 tmp = readl(mmio + CARM_INT_MASK);
493                 tmp |= INT_Q_AVAILABLE;
494                 writel(tmp, mmio + CARM_INT_MASK);
495                 readl(mmio + CARM_INT_MASK);    /* flush */
496 #endif
497                 DPRINTK("host msg queue full\n");
498                 rc = -EBUSY;
499         } else {
500                 writel(msg | (cm_bucket << 1), mmio + CARM_IHQP);
501                 readl(mmio + CARM_IHQP);        /* flush */
502         }
503
504         return rc;
505 }
506
507 static struct carm_request *carm_get_request(struct carm_host *host)
508 {
509         unsigned int i;
510
511         /* obey global hardware limit on S/G entries */
512         if (host->hw_sg_used >= (CARM_MAX_HOST_SG - CARM_MAX_REQ_SG))
513                 return NULL;
514
515         for (i = 0; i < max_queue; i++)
516                 if ((host->msg_alloc & (1ULL << i)) == 0) {
517                         struct carm_request *crq = &host->req[i];
518                         crq->port = NULL;
519                         crq->n_elem = 0;
520
521                         host->msg_alloc |= (1ULL << i);
522                         host->n_msgs++;
523
524                         assert(host->n_msgs <= CARM_MAX_REQ);
525                         sg_init_table(crq->sg, CARM_MAX_REQ_SG);
526                         return crq;
527                 }
528
529         DPRINTK("no request available, returning NULL\n");
530         return NULL;
531 }
532
533 static int carm_put_request(struct carm_host *host, struct carm_request *crq)
534 {
535         assert(crq->tag < max_queue);
536
537         if (unlikely((host->msg_alloc & (1ULL << crq->tag)) == 0))
538                 return -EINVAL; /* tried to clear a tag that was not active */
539
540         assert(host->hw_sg_used >= crq->n_elem);
541
542         host->msg_alloc &= ~(1ULL << crq->tag);
543         host->hw_sg_used -= crq->n_elem;
544         host->n_msgs--;
545
546         return 0;
547 }
548
549 static struct carm_request *carm_get_special(struct carm_host *host)
550 {
551         unsigned long flags;
552         struct carm_request *crq = NULL;
553         struct request *rq;
554         int tries = 5000;
555
556         while (tries-- > 0) {
557                 spin_lock_irqsave(&host->lock, flags);
558                 crq = carm_get_request(host);
559                 spin_unlock_irqrestore(&host->lock, flags);
560
561                 if (crq)
562                         break;
563                 msleep(10);
564         }
565
566         if (!crq)
567                 return NULL;
568
569         rq = blk_get_request(host->oob_q, WRITE /* bogus */, GFP_KERNEL);
570         if (!rq) {
571                 spin_lock_irqsave(&host->lock, flags);
572                 carm_put_request(host, crq);
573                 spin_unlock_irqrestore(&host->lock, flags);
574                 return NULL;
575         }
576
577         crq->rq = rq;
578         return crq;
579 }
580
581 static int carm_array_info (struct carm_host *host, unsigned int array_idx)
582 {
583         struct carm_msg_ioctl *ioc;
584         unsigned int idx;
585         u32 msg_data;
586         dma_addr_t msg_dma;
587         struct carm_request *crq;
588         int rc;
589
590         crq = carm_get_special(host);
591         if (!crq) {
592                 rc = -ENOMEM;
593                 goto err_out;
594         }
595
596         idx = crq->tag;
597
598         ioc = carm_ref_msg(host, idx);
599         msg_dma = carm_ref_msg_dma(host, idx);
600         msg_data = (u32) (msg_dma + sizeof(struct carm_array_info));
601
602         crq->msg_type = CARM_MSG_ARRAY;
603         crq->msg_subtype = CARM_ARRAY_INFO;
604         rc = carm_lookup_bucket(sizeof(struct carm_msg_ioctl) +
605                                 sizeof(struct carm_array_info));
606         BUG_ON(rc < 0);
607         crq->msg_bucket = (u32) rc;
608
609         memset(ioc, 0, sizeof(*ioc));
610         ioc->type       = CARM_MSG_ARRAY;
611         ioc->subtype    = CARM_ARRAY_INFO;
612         ioc->array_id   = (u8) array_idx;
613         ioc->handle     = cpu_to_le32(TAG_ENCODE(idx));
614         ioc->data_addr  = cpu_to_le32(msg_data);
615
616         spin_lock_irq(&host->lock);
617         assert(host->state == HST_DEV_SCAN_START ||
618                host->state == HST_DEV_SCAN);
619         spin_unlock_irq(&host->lock);
620
621         DPRINTK("blk_insert_request, tag == %u\n", idx);
622         blk_insert_request(host->oob_q, crq->rq, 1, crq);
623
624         return 0;
625
626 err_out:
627         spin_lock_irq(&host->lock);
628         host->state = HST_ERROR;
629         spin_unlock_irq(&host->lock);
630         return rc;
631 }
632
633 typedef unsigned int (*carm_sspc_t)(struct carm_host *, unsigned int, void *);
634
635 static int carm_send_special (struct carm_host *host, carm_sspc_t func)
636 {
637         struct carm_request *crq;
638         struct carm_msg_ioctl *ioc;
639         void *mem;
640         unsigned int idx, msg_size;
641         int rc;
642
643         crq = carm_get_special(host);
644         if (!crq)
645                 return -ENOMEM;
646
647         idx = crq->tag;
648
649         mem = carm_ref_msg(host, idx);
650
651         msg_size = func(host, idx, mem);
652
653         ioc = mem;
654         crq->msg_type = ioc->type;
655         crq->msg_subtype = ioc->subtype;
656         rc = carm_lookup_bucket(msg_size);
657         BUG_ON(rc < 0);
658         crq->msg_bucket = (u32) rc;
659
660         DPRINTK("blk_insert_request, tag == %u\n", idx);
661         blk_insert_request(host->oob_q, crq->rq, 1, crq);
662
663         return 0;
664 }
665
666 static unsigned int carm_fill_sync_time(struct carm_host *host,
667                                         unsigned int idx, void *mem)
668 {
669         struct timeval tv;
670         struct carm_msg_sync_time *st = mem;
671
672         do_gettimeofday(&tv);
673
674         memset(st, 0, sizeof(*st));
675         st->type        = CARM_MSG_MISC;
676         st->subtype     = MISC_SET_TIME;
677         st->handle      = cpu_to_le32(TAG_ENCODE(idx));
678         st->timestamp   = cpu_to_le32(tv.tv_sec);
679
680         return sizeof(struct carm_msg_sync_time);
681 }
682
683 static unsigned int carm_fill_alloc_buf(struct carm_host *host,
684                                         unsigned int idx, void *mem)
685 {
686         struct carm_msg_allocbuf *ab = mem;
687
688         memset(ab, 0, sizeof(*ab));
689         ab->type        = CARM_MSG_MISC;
690         ab->subtype     = MISC_ALLOC_MEM;
691         ab->handle      = cpu_to_le32(TAG_ENCODE(idx));
692         ab->n_sg        = 1;
693         ab->sg_type     = SGT_32BIT;
694         ab->addr        = cpu_to_le32(host->shm_dma + (PDC_SHM_SIZE >> 1));
695         ab->len         = cpu_to_le32(PDC_SHM_SIZE >> 1);
696         ab->evt_pool    = cpu_to_le32(host->shm_dma + (16 * 1024));
697         ab->n_evt       = cpu_to_le32(1024);
698         ab->rbuf_pool   = cpu_to_le32(host->shm_dma);
699         ab->n_rbuf      = cpu_to_le32(RMSG_Q_LEN);
700         ab->msg_pool    = cpu_to_le32(host->shm_dma + RBUF_LEN);
701         ab->n_msg       = cpu_to_le32(CARM_Q_LEN);
702         ab->sg[0].start = cpu_to_le32(host->shm_dma + (PDC_SHM_SIZE >> 1));
703         ab->sg[0].len   = cpu_to_le32(65536);
704
705         return sizeof(struct carm_msg_allocbuf);
706 }
707
708 static unsigned int carm_fill_scan_channels(struct carm_host *host,
709                                             unsigned int idx, void *mem)
710 {
711         struct carm_msg_ioctl *ioc = mem;
712         u32 msg_data = (u32) (carm_ref_msg_dma(host, idx) +
713                               IOC_SCAN_CHAN_OFFSET);
714
715         memset(ioc, 0, sizeof(*ioc));
716         ioc->type       = CARM_MSG_IOCTL;
717         ioc->subtype    = CARM_IOC_SCAN_CHAN;
718         ioc->handle     = cpu_to_le32(TAG_ENCODE(idx));
719         ioc->data_addr  = cpu_to_le32(msg_data);
720
721         /* fill output data area with "no device" default values */
722         mem += IOC_SCAN_CHAN_OFFSET;
723         memset(mem, IOC_SCAN_CHAN_NODEV, CARM_MAX_PORTS);
724
725         return IOC_SCAN_CHAN_OFFSET + CARM_MAX_PORTS;
726 }
727
728 static unsigned int carm_fill_get_fw_ver(struct carm_host *host,
729                                          unsigned int idx, void *mem)
730 {
731         struct carm_msg_get_fw_ver *ioc = mem;
732         u32 msg_data = (u32) (carm_ref_msg_dma(host, idx) + sizeof(*ioc));
733
734         memset(ioc, 0, sizeof(*ioc));
735         ioc->type       = CARM_MSG_MISC;
736         ioc->subtype    = MISC_GET_FW_VER;
737         ioc->handle     = cpu_to_le32(TAG_ENCODE(idx));
738         ioc->data_addr  = cpu_to_le32(msg_data);
739
740         return sizeof(struct carm_msg_get_fw_ver) +
741                sizeof(struct carm_fw_ver);
742 }
743
744 static inline void carm_end_request_queued(struct carm_host *host,
745                                            struct carm_request *crq,
746                                            int uptodate)
747 {
748         struct request *req = crq->rq;
749         int rc;
750
751         rc = end_that_request_first(req, uptodate, req->hard_nr_sectors);
752         assert(rc == 0);
753
754         end_that_request_last(req, uptodate);
755
756         rc = carm_put_request(host, crq);
757         assert(rc == 0);
758 }
759
760 static inline void carm_push_q (struct carm_host *host, struct request_queue *q)
761 {
762         unsigned int idx = host->wait_q_prod % CARM_MAX_WAIT_Q;
763
764         blk_stop_queue(q);
765         VPRINTK("STOPPED QUEUE %p\n", q);
766
767         host->wait_q[idx] = q;
768         host->wait_q_prod++;
769         BUG_ON(host->wait_q_prod == host->wait_q_cons); /* overrun */
770 }
771
772 static inline struct request_queue *carm_pop_q(struct carm_host *host)
773 {
774         unsigned int idx;
775
776         if (host->wait_q_prod == host->wait_q_cons)
777                 return NULL;
778
779         idx = host->wait_q_cons % CARM_MAX_WAIT_Q;
780         host->wait_q_cons++;
781
782         return host->wait_q[idx];
783 }
784
785 static inline void carm_round_robin(struct carm_host *host)
786 {
787         struct request_queue *q = carm_pop_q(host);
788         if (q) {
789                 blk_start_queue(q);
790                 VPRINTK("STARTED QUEUE %p\n", q);
791         }
792 }
793
794 static inline void carm_end_rq(struct carm_host *host, struct carm_request *crq,
795                         int is_ok)
796 {
797         carm_end_request_queued(host, crq, is_ok);
798         if (max_queue == 1)
799                 carm_round_robin(host);
800         else if ((host->n_msgs <= CARM_MSG_LOW_WATER) &&
801                  (host->hw_sg_used <= CARM_SG_LOW_WATER)) {
802                 carm_round_robin(host);
803         }
804 }
805
806 static void carm_oob_rq_fn(struct request_queue *q)
807 {
808         struct carm_host *host = q->queuedata;
809         struct carm_request *crq;
810         struct request *rq;
811         int rc;
812
813         while (1) {
814                 DPRINTK("get req\n");
815                 rq = elv_next_request(q);
816                 if (!rq)
817                         break;
818
819                 blkdev_dequeue_request(rq);
820
821                 crq = rq->special;
822                 assert(crq != NULL);
823                 assert(crq->rq == rq);
824
825                 crq->n_elem = 0;
826
827                 DPRINTK("send req\n");
828                 rc = carm_send_msg(host, crq);
829                 if (rc) {
830                         blk_requeue_request(q, rq);
831                         carm_push_q(host, q);
832                         return;         /* call us again later, eventually */
833                 }
834         }
835 }
836
837 static void carm_rq_fn(struct request_queue *q)
838 {
839         struct carm_port *port = q->queuedata;
840         struct carm_host *host = port->host;
841         struct carm_msg_rw *msg;
842         struct carm_request *crq;
843         struct request *rq;
844         struct scatterlist *sg;
845         int writing = 0, pci_dir, i, n_elem, rc;
846         u32 tmp;
847         unsigned int msg_size;
848
849 queue_one_request:
850         VPRINTK("get req\n");
851         rq = elv_next_request(q);
852         if (!rq)
853                 return;
854
855         crq = carm_get_request(host);
856         if (!crq) {
857                 carm_push_q(host, q);
858                 return;         /* call us again later, eventually */
859         }
860         crq->rq = rq;
861
862         blkdev_dequeue_request(rq);
863
864         if (rq_data_dir(rq) == WRITE) {
865                 writing = 1;
866                 pci_dir = PCI_DMA_TODEVICE;
867         } else {
868                 pci_dir = PCI_DMA_FROMDEVICE;
869         }
870
871         /* get scatterlist from block layer */
872         sg = &crq->sg[0];
873         n_elem = blk_rq_map_sg(q, rq, sg);
874         if (n_elem <= 0) {
875                 carm_end_rq(host, crq, 0);
876                 return;         /* request with no s/g entries? */
877         }
878
879         /* map scatterlist to PCI bus addresses */
880         n_elem = pci_map_sg(host->pdev, sg, n_elem, pci_dir);
881         if (n_elem <= 0) {
882                 carm_end_rq(host, crq, 0);
883                 return;         /* request with no s/g entries? */
884         }
885         crq->n_elem = n_elem;
886         crq->port = port;
887         host->hw_sg_used += n_elem;
888
889         /*
890          * build read/write message
891          */
892
893         VPRINTK("build msg\n");
894         msg = (struct carm_msg_rw *) carm_ref_msg(host, crq->tag);
895
896         if (writing) {
897                 msg->type = CARM_MSG_WRITE;
898                 crq->msg_type = CARM_MSG_WRITE;
899         } else {
900                 msg->type = CARM_MSG_READ;
901                 crq->msg_type = CARM_MSG_READ;
902         }
903
904         msg->id         = port->port_no;
905         msg->sg_count   = n_elem;
906         msg->sg_type    = SGT_32BIT;
907         msg->handle     = cpu_to_le32(TAG_ENCODE(crq->tag));
908         msg->lba        = cpu_to_le32(rq->sector & 0xffffffff);
909         tmp             = (rq->sector >> 16) >> 16;
910         msg->lba_high   = cpu_to_le16( (u16) tmp );
911         msg->lba_count  = cpu_to_le16(rq->nr_sectors);
912
913         msg_size = sizeof(struct carm_msg_rw) - sizeof(msg->sg);
914         for (i = 0; i < n_elem; i++) {
915                 struct carm_msg_sg *carm_sg = &msg->sg[i];
916                 carm_sg->start = cpu_to_le32(sg_dma_address(&crq->sg[i]));
917                 carm_sg->len = cpu_to_le32(sg_dma_len(&crq->sg[i]));
918                 msg_size += sizeof(struct carm_msg_sg);
919         }
920
921         rc = carm_lookup_bucket(msg_size);
922         BUG_ON(rc < 0);
923         crq->msg_bucket = (u32) rc;
924
925         /*
926          * queue read/write message to hardware
927          */
928
929         VPRINTK("send msg, tag == %u\n", crq->tag);
930         rc = carm_send_msg(host, crq);
931         if (rc) {
932                 carm_put_request(host, crq);
933                 blk_requeue_request(q, rq);
934                 carm_push_q(host, q);
935                 return;         /* call us again later, eventually */
936         }
937
938         goto queue_one_request;
939 }
940
941 static void carm_handle_array_info(struct carm_host *host,
942                                    struct carm_request *crq, u8 *mem,
943                                    int is_ok)
944 {
945         struct carm_port *port;
946         u8 *msg_data = mem + sizeof(struct carm_array_info);
947         struct carm_array_info *desc = (struct carm_array_info *) msg_data;
948         u64 lo, hi;
949         int cur_port;
950         size_t slen;
951
952         DPRINTK("ENTER\n");
953
954         carm_end_rq(host, crq, is_ok);
955
956         if (!is_ok)
957                 goto out;
958         if (le32_to_cpu(desc->array_status) & ARRAY_NO_EXIST)
959                 goto out;
960
961         cur_port = host->cur_scan_dev;
962
963         /* should never occur */
964         if ((cur_port < 0) || (cur_port >= CARM_MAX_PORTS)) {
965                 printk(KERN_ERR PFX "BUG: cur_scan_dev==%d, array_id==%d\n",
966                        cur_port, (int) desc->array_id);
967                 goto out;
968         }
969
970         port = &host->port[cur_port];
971
972         lo = (u64) le32_to_cpu(desc->size);
973         hi = (u64) le16_to_cpu(desc->size_hi);
974
975         port->capacity = lo | (hi << 32);
976         port->dev_geom_head = le16_to_cpu(desc->head);
977         port->dev_geom_sect = le16_to_cpu(desc->sect);
978         port->dev_geom_cyl = le16_to_cpu(desc->cyl);
979
980         host->dev_active |= (1 << cur_port);
981
982         strncpy(port->name, desc->name, sizeof(port->name));
983         port->name[sizeof(port->name) - 1] = 0;
984         slen = strlen(port->name);
985         while (slen && (port->name[slen - 1] == ' ')) {
986                 port->name[slen - 1] = 0;
987                 slen--;
988         }
989
990         printk(KERN_INFO DRV_NAME "(%s): port %u device %Lu sectors\n",
991                pci_name(host->pdev), port->port_no,
992                (unsigned long long) port->capacity);
993         printk(KERN_INFO DRV_NAME "(%s): port %u device \"%s\"\n",
994                pci_name(host->pdev), port->port_no, port->name);
995
996 out:
997         assert(host->state == HST_DEV_SCAN);
998         schedule_work(&host->fsm_task);
999 }
1000
1001 static void carm_handle_scan_chan(struct carm_host *host,
1002                                   struct carm_request *crq, u8 *mem,
1003                                   int is_ok)
1004 {
1005         u8 *msg_data = mem + IOC_SCAN_CHAN_OFFSET;
1006         unsigned int i, dev_count = 0;
1007         int new_state = HST_DEV_SCAN_START;
1008
1009         DPRINTK("ENTER\n");
1010
1011         carm_end_rq(host, crq, is_ok);
1012
1013         if (!is_ok) {
1014                 new_state = HST_ERROR;
1015                 goto out;
1016         }
1017
1018         /* TODO: scan and support non-disk devices */
1019         for (i = 0; i < 8; i++)
1020                 if (msg_data[i] == 0) { /* direct-access device (disk) */
1021                         host->dev_present |= (1 << i);
1022                         dev_count++;
1023                 }
1024
1025         printk(KERN_INFO DRV_NAME "(%s): found %u interesting devices\n",
1026                pci_name(host->pdev), dev_count);
1027
1028 out:
1029         assert(host->state == HST_PORT_SCAN);
1030         host->state = new_state;
1031         schedule_work(&host->fsm_task);
1032 }
1033
1034 static void carm_handle_generic(struct carm_host *host,
1035                                 struct carm_request *crq, int is_ok,
1036                                 int cur_state, int next_state)
1037 {
1038         DPRINTK("ENTER\n");
1039
1040         carm_end_rq(host, crq, is_ok);
1041
1042         assert(host->state == cur_state);
1043         if (is_ok)
1044                 host->state = next_state;
1045         else
1046                 host->state = HST_ERROR;
1047         schedule_work(&host->fsm_task);
1048 }
1049
1050 static inline void carm_handle_rw(struct carm_host *host,
1051                                   struct carm_request *crq, int is_ok)
1052 {
1053         int pci_dir;
1054
1055         VPRINTK("ENTER\n");
1056
1057         if (rq_data_dir(crq->rq) == WRITE)
1058                 pci_dir = PCI_DMA_TODEVICE;
1059         else
1060                 pci_dir = PCI_DMA_FROMDEVICE;
1061
1062         pci_unmap_sg(host->pdev, &crq->sg[0], crq->n_elem, pci_dir);
1063
1064         carm_end_rq(host, crq, is_ok);
1065 }
1066
1067 static inline void carm_handle_resp(struct carm_host *host,
1068                                     __le32 ret_handle_le, u32 status)
1069 {
1070         u32 handle = le32_to_cpu(ret_handle_le);
1071         unsigned int msg_idx;
1072         struct carm_request *crq;
1073         int is_ok = (status == RMSG_OK);
1074         u8 *mem;
1075
1076         VPRINTK("ENTER, handle == 0x%x\n", handle);
1077
1078         if (unlikely(!TAG_VALID(handle))) {
1079                 printk(KERN_ERR DRV_NAME "(%s): BUG: invalid tag 0x%x\n",
1080                        pci_name(host->pdev), handle);
1081                 return;
1082         }
1083
1084         msg_idx = TAG_DECODE(handle);
1085         VPRINTK("tag == %u\n", msg_idx);
1086
1087         crq = &host->req[msg_idx];
1088
1089         /* fast path */
1090         if (likely(crq->msg_type == CARM_MSG_READ ||
1091                    crq->msg_type == CARM_MSG_WRITE)) {
1092                 carm_handle_rw(host, crq, is_ok);
1093                 return;
1094         }
1095
1096         mem = carm_ref_msg(host, msg_idx);
1097
1098         switch (crq->msg_type) {
1099         case CARM_MSG_IOCTL: {
1100                 switch (crq->msg_subtype) {
1101                 case CARM_IOC_SCAN_CHAN:
1102                         carm_handle_scan_chan(host, crq, mem, is_ok);
1103                         break;
1104                 default:
1105                         /* unknown / invalid response */
1106                         goto err_out;
1107                 }
1108                 break;
1109         }
1110
1111         case CARM_MSG_MISC: {
1112                 switch (crq->msg_subtype) {
1113                 case MISC_ALLOC_MEM:
1114                         carm_handle_generic(host, crq, is_ok,
1115                                             HST_ALLOC_BUF, HST_SYNC_TIME);
1116                         break;
1117                 case MISC_SET_TIME:
1118                         carm_handle_generic(host, crq, is_ok,
1119                                             HST_SYNC_TIME, HST_GET_FW_VER);
1120                         break;
1121                 case MISC_GET_FW_VER: {
1122                         struct carm_fw_ver *ver = (struct carm_fw_ver *)
1123                                 mem + sizeof(struct carm_msg_get_fw_ver);
1124                         if (is_ok) {
1125                                 host->fw_ver = le32_to_cpu(ver->version);
1126                                 host->flags |= (ver->features & FL_FW_VER_MASK);
1127                         }
1128                         carm_handle_generic(host, crq, is_ok,
1129                                             HST_GET_FW_VER, HST_PORT_SCAN);
1130                         break;
1131                 }
1132                 default:
1133                         /* unknown / invalid response */
1134                         goto err_out;
1135                 }
1136                 break;
1137         }
1138
1139         case CARM_MSG_ARRAY: {
1140                 switch (crq->msg_subtype) {
1141                 case CARM_ARRAY_INFO:
1142                         carm_handle_array_info(host, crq, mem, is_ok);
1143                         break;
1144                 default:
1145                         /* unknown / invalid response */
1146                         goto err_out;
1147                 }
1148                 break;
1149         }
1150
1151         default:
1152                 /* unknown / invalid response */
1153                 goto err_out;
1154         }
1155
1156         return;
1157
1158 err_out:
1159         printk(KERN_WARNING DRV_NAME "(%s): BUG: unhandled message type %d/%d\n",
1160                pci_name(host->pdev), crq->msg_type, crq->msg_subtype);
1161         carm_end_rq(host, crq, 0);
1162 }
1163
1164 static inline void carm_handle_responses(struct carm_host *host)
1165 {
1166         void __iomem *mmio = host->mmio;
1167         struct carm_response *resp = (struct carm_response *) host->shm;
1168         unsigned int work = 0;
1169         unsigned int idx = host->resp_idx % RMSG_Q_LEN;
1170
1171         while (1) {
1172                 u32 status = le32_to_cpu(resp[idx].status);
1173
1174                 if (status == 0xffffffff) {
1175                         VPRINTK("ending response on index %u\n", idx);
1176                         writel(idx << 3, mmio + CARM_RESP_IDX);
1177                         break;
1178                 }
1179
1180                 /* response to a message we sent */
1181                 else if ((status & (1 << 31)) == 0) {
1182                         VPRINTK("handling msg response on index %u\n", idx);
1183                         carm_handle_resp(host, resp[idx].ret_handle, status);
1184                         resp[idx].status = cpu_to_le32(0xffffffff);
1185                 }
1186
1187                 /* asynchronous events the hardware throws our way */
1188                 else if ((status & 0xff000000) == (1 << 31)) {
1189                         u8 *evt_type_ptr = (u8 *) &resp[idx];
1190                         u8 evt_type = *evt_type_ptr;
1191                         printk(KERN_WARNING DRV_NAME "(%s): unhandled event type %d\n",
1192                                pci_name(host->pdev), (int) evt_type);
1193                         resp[idx].status = cpu_to_le32(0xffffffff);
1194                 }
1195
1196                 idx = NEXT_RESP(idx);
1197                 work++;
1198         }
1199
1200         VPRINTK("EXIT, work==%u\n", work);
1201         host->resp_idx += work;
1202 }
1203
1204 static irqreturn_t carm_interrupt(int irq, void *__host)
1205 {
1206         struct carm_host *host = __host;
1207         void __iomem *mmio;
1208         u32 mask;
1209         int handled = 0;
1210         unsigned long flags;
1211
1212         if (!host) {
1213                 VPRINTK("no host\n");
1214                 return IRQ_NONE;
1215         }
1216
1217         spin_lock_irqsave(&host->lock, flags);
1218
1219         mmio = host->mmio;
1220
1221         /* reading should also clear interrupts */
1222         mask = readl(mmio + CARM_INT_STAT);
1223
1224         if (mask == 0 || mask == 0xffffffff) {
1225                 VPRINTK("no work, mask == 0x%x\n", mask);
1226                 goto out;
1227         }
1228
1229         if (mask & INT_ACK_MASK)
1230                 writel(mask, mmio + CARM_INT_STAT);
1231
1232         if (unlikely(host->state == HST_INVALID)) {
1233                 VPRINTK("not initialized yet, mask = 0x%x\n", mask);
1234                 goto out;
1235         }
1236
1237         if (mask & CARM_HAVE_RESP) {
1238                 handled = 1;
1239                 carm_handle_responses(host);
1240         }
1241
1242 out:
1243         spin_unlock_irqrestore(&host->lock, flags);
1244         VPRINTK("EXIT\n");
1245         return IRQ_RETVAL(handled);
1246 }
1247
1248 static void carm_fsm_task (struct work_struct *work)
1249 {
1250         struct carm_host *host =
1251                 container_of(work, struct carm_host, fsm_task);
1252         unsigned long flags;
1253         unsigned int state;
1254         int rc, i, next_dev;
1255         int reschedule = 0;
1256         int new_state = HST_INVALID;
1257
1258         spin_lock_irqsave(&host->lock, flags);
1259         state = host->state;
1260         spin_unlock_irqrestore(&host->lock, flags);
1261
1262         DPRINTK("ENTER, state == %s\n", state_name[state]);
1263
1264         switch (state) {
1265         case HST_PROBE_START:
1266                 new_state = HST_ALLOC_BUF;
1267                 reschedule = 1;
1268                 break;
1269
1270         case HST_ALLOC_BUF:
1271                 rc = carm_send_special(host, carm_fill_alloc_buf);
1272                 if (rc) {
1273                         new_state = HST_ERROR;
1274                         reschedule = 1;
1275                 }
1276                 break;
1277
1278         case HST_SYNC_TIME:
1279                 rc = carm_send_special(host, carm_fill_sync_time);
1280                 if (rc) {
1281                         new_state = HST_ERROR;
1282                         reschedule = 1;
1283                 }
1284                 break;
1285
1286         case HST_GET_FW_VER:
1287                 rc = carm_send_special(host, carm_fill_get_fw_ver);
1288                 if (rc) {
1289                         new_state = HST_ERROR;
1290                         reschedule = 1;
1291                 }
1292                 break;
1293
1294         case HST_PORT_SCAN:
1295                 rc = carm_send_special(host, carm_fill_scan_channels);
1296                 if (rc) {
1297                         new_state = HST_ERROR;
1298                         reschedule = 1;
1299                 }
1300                 break;
1301
1302         case HST_DEV_SCAN_START:
1303                 host->cur_scan_dev = -1;
1304                 new_state = HST_DEV_SCAN;
1305                 reschedule = 1;
1306                 break;
1307
1308         case HST_DEV_SCAN:
1309                 next_dev = -1;
1310                 for (i = host->cur_scan_dev + 1; i < CARM_MAX_PORTS; i++)
1311                         if (host->dev_present & (1 << i)) {
1312                                 next_dev = i;
1313                                 break;
1314                         }
1315
1316                 if (next_dev >= 0) {
1317                         host->cur_scan_dev = next_dev;
1318                         rc = carm_array_info(host, next_dev);
1319                         if (rc) {
1320                                 new_state = HST_ERROR;
1321                                 reschedule = 1;
1322                         }
1323                 } else {
1324                         new_state = HST_DEV_ACTIVATE;
1325                         reschedule = 1;
1326                 }
1327                 break;
1328
1329         case HST_DEV_ACTIVATE: {
1330                 int activated = 0;
1331                 for (i = 0; i < CARM_MAX_PORTS; i++)
1332                         if (host->dev_active & (1 << i)) {
1333                                 struct carm_port *port = &host->port[i];
1334                                 struct gendisk *disk = port->disk;
1335
1336                                 set_capacity(disk, port->capacity);
1337                                 add_disk(disk);
1338                                 activated++;
1339                         }
1340
1341                 printk(KERN_INFO DRV_NAME "(%s): %d ports activated\n",
1342                        pci_name(host->pdev), activated);
1343
1344                 new_state = HST_PROBE_FINISHED;
1345                 reschedule = 1;
1346                 break;
1347         }
1348
1349         case HST_PROBE_FINISHED:
1350                 complete(&host->probe_comp);
1351                 break;
1352
1353         case HST_ERROR:
1354                 /* FIXME: TODO */
1355                 break;
1356
1357         default:
1358                 /* should never occur */
1359                 printk(KERN_ERR PFX "BUG: unknown state %d\n", state);
1360                 assert(0);
1361                 break;
1362         }
1363
1364         if (new_state != HST_INVALID) {
1365                 spin_lock_irqsave(&host->lock, flags);
1366                 host->state = new_state;
1367                 spin_unlock_irqrestore(&host->lock, flags);
1368         }
1369         if (reschedule)
1370                 schedule_work(&host->fsm_task);
1371 }
1372
1373 static int carm_init_wait(void __iomem *mmio, u32 bits, unsigned int test_bit)
1374 {
1375         unsigned int i;
1376
1377         for (i = 0; i < 50000; i++) {
1378                 u32 tmp = readl(mmio + CARM_LMUC);
1379                 udelay(100);
1380
1381                 if (test_bit) {
1382                         if ((tmp & bits) == bits)
1383                                 return 0;
1384                 } else {
1385                         if ((tmp & bits) == 0)
1386                                 return 0;
1387                 }
1388
1389                 cond_resched();
1390         }
1391
1392         printk(KERN_ERR PFX "carm_init_wait timeout, bits == 0x%x, test_bit == %s\n",
1393                bits, test_bit ? "yes" : "no");
1394         return -EBUSY;
1395 }
1396
1397 static void carm_init_responses(struct carm_host *host)
1398 {
1399         void __iomem *mmio = host->mmio;
1400         unsigned int i;
1401         struct carm_response *resp = (struct carm_response *) host->shm;
1402
1403         for (i = 0; i < RMSG_Q_LEN; i++)
1404                 resp[i].status = cpu_to_le32(0xffffffff);
1405
1406         writel(0, mmio + CARM_RESP_IDX);
1407 }
1408
1409 static int carm_init_host(struct carm_host *host)
1410 {
1411         void __iomem *mmio = host->mmio;
1412         u32 tmp;
1413         u8 tmp8;
1414         int rc;
1415
1416         DPRINTK("ENTER\n");
1417
1418         writel(0, mmio + CARM_INT_MASK);
1419
1420         tmp8 = readb(mmio + CARM_INITC);
1421         if (tmp8 & 0x01) {
1422                 tmp8 &= ~0x01;
1423                 writeb(tmp8, mmio + CARM_INITC);
1424                 readb(mmio + CARM_INITC);       /* flush */
1425
1426                 DPRINTK("snooze...\n");
1427                 msleep(5000);
1428         }
1429
1430         tmp = readl(mmio + CARM_HMUC);
1431         if (tmp & CARM_CME) {
1432                 DPRINTK("CME bit present, waiting\n");
1433                 rc = carm_init_wait(mmio, CARM_CME, 1);
1434                 if (rc) {
1435                         DPRINTK("EXIT, carm_init_wait 1 failed\n");
1436                         return rc;
1437                 }
1438         }
1439         if (tmp & CARM_RME) {
1440                 DPRINTK("RME bit present, waiting\n");
1441                 rc = carm_init_wait(mmio, CARM_RME, 1);
1442                 if (rc) {
1443                         DPRINTK("EXIT, carm_init_wait 2 failed\n");
1444                         return rc;
1445                 }
1446         }
1447
1448         tmp &= ~(CARM_RME | CARM_CME);
1449         writel(tmp, mmio + CARM_HMUC);
1450         readl(mmio + CARM_HMUC);        /* flush */
1451
1452         rc = carm_init_wait(mmio, CARM_RME | CARM_CME, 0);
1453         if (rc) {
1454                 DPRINTK("EXIT, carm_init_wait 3 failed\n");
1455                 return rc;
1456         }
1457
1458         carm_init_buckets(mmio);
1459
1460         writel(host->shm_dma & 0xffffffff, mmio + RBUF_ADDR_LO);
1461         writel((host->shm_dma >> 16) >> 16, mmio + RBUF_ADDR_HI);
1462         writel(RBUF_LEN, mmio + RBUF_BYTE_SZ);
1463
1464         tmp = readl(mmio + CARM_HMUC);
1465         tmp |= (CARM_RME | CARM_CME | CARM_WZBC);
1466         writel(tmp, mmio + CARM_HMUC);
1467         readl(mmio + CARM_HMUC);        /* flush */
1468
1469         rc = carm_init_wait(mmio, CARM_RME | CARM_CME, 1);
1470         if (rc) {
1471                 DPRINTK("EXIT, carm_init_wait 4 failed\n");
1472                 return rc;
1473         }
1474
1475         writel(0, mmio + CARM_HMPHA);
1476         writel(INT_DEF_MASK, mmio + CARM_INT_MASK);
1477
1478         carm_init_responses(host);
1479
1480         /* start initialization, probing state machine */
1481         spin_lock_irq(&host->lock);
1482         assert(host->state == HST_INVALID);
1483         host->state = HST_PROBE_START;
1484         spin_unlock_irq(&host->lock);
1485         schedule_work(&host->fsm_task);
1486
1487         DPRINTK("EXIT\n");
1488         return 0;
1489 }
1490
1491 static int carm_init_disks(struct carm_host *host)
1492 {
1493         unsigned int i;
1494         int rc = 0;
1495
1496         for (i = 0; i < CARM_MAX_PORTS; i++) {
1497                 struct gendisk *disk;
1498                 struct request_queue *q;
1499                 struct carm_port *port;
1500
1501                 port = &host->port[i];
1502                 port->host = host;
1503                 port->port_no = i;
1504
1505                 disk = alloc_disk(CARM_MINORS_PER_MAJOR);
1506                 if (!disk) {
1507                         rc = -ENOMEM;
1508                         break;
1509                 }
1510
1511                 port->disk = disk;
1512                 sprintf(disk->disk_name, DRV_NAME "/%u",
1513                         (unsigned int) (host->id * CARM_MAX_PORTS) + i);
1514                 disk->major = host->major;
1515                 disk->first_minor = i * CARM_MINORS_PER_MAJOR;
1516                 disk->fops = &carm_bd_ops;
1517                 disk->private_data = port;
1518
1519                 q = blk_init_queue(carm_rq_fn, &host->lock);
1520                 if (!q) {
1521                         rc = -ENOMEM;
1522                         break;
1523                 }
1524                 disk->queue = q;
1525                 blk_queue_max_hw_segments(q, CARM_MAX_REQ_SG);
1526                 blk_queue_max_phys_segments(q, CARM_MAX_REQ_SG);
1527                 blk_queue_segment_boundary(q, CARM_SG_BOUNDARY);
1528
1529                 q->queuedata = port;
1530         }
1531
1532         return rc;
1533 }
1534
1535 static void carm_free_disks(struct carm_host *host)
1536 {
1537         unsigned int i;
1538
1539         for (i = 0; i < CARM_MAX_PORTS; i++) {
1540                 struct gendisk *disk = host->port[i].disk;
1541                 if (disk) {
1542                         struct request_queue *q = disk->queue;
1543
1544                         if (disk->flags & GENHD_FL_UP)
1545                                 del_gendisk(disk);
1546                         if (q)
1547                                 blk_cleanup_queue(q);
1548                         put_disk(disk);
1549                 }
1550         }
1551 }
1552
1553 static int carm_init_shm(struct carm_host *host)
1554 {
1555         host->shm = pci_alloc_consistent(host->pdev, CARM_SHM_SIZE,
1556                                          &host->shm_dma);
1557         if (!host->shm)
1558                 return -ENOMEM;
1559
1560         host->msg_base = host->shm + RBUF_LEN;
1561         host->msg_dma = host->shm_dma + RBUF_LEN;
1562
1563         memset(host->shm, 0xff, RBUF_LEN);
1564         memset(host->msg_base, 0, PDC_SHM_SIZE - RBUF_LEN);
1565
1566         return 0;
1567 }
1568
1569 static int carm_init_one (struct pci_dev *pdev, const struct pci_device_id *ent)
1570 {
1571         static unsigned int printed_version;
1572         struct carm_host *host;
1573         unsigned int pci_dac;
1574         int rc;
1575         struct request_queue *q;
1576         unsigned int i;
1577
1578         if (!printed_version++)
1579                 printk(KERN_DEBUG DRV_NAME " version " DRV_VERSION "\n");
1580
1581         rc = pci_enable_device(pdev);
1582         if (rc)
1583                 return rc;
1584
1585         rc = pci_request_regions(pdev, DRV_NAME);
1586         if (rc)
1587                 goto err_out;
1588
1589 #ifdef IF_64BIT_DMA_IS_POSSIBLE /* grrrr... */
1590         rc = pci_set_dma_mask(pdev, DMA_64BIT_MASK);
1591         if (!rc) {
1592                 rc = pci_set_consistent_dma_mask(pdev, DMA_64BIT_MASK);
1593                 if (rc) {
1594                         printk(KERN_ERR DRV_NAME "(%s): consistent DMA mask failure\n",
1595                                 pci_name(pdev));
1596                         goto err_out_regions;
1597                 }
1598                 pci_dac = 1;
1599         } else {
1600 #endif
1601                 rc = pci_set_dma_mask(pdev, DMA_32BIT_MASK);
1602                 if (rc) {
1603                         printk(KERN_ERR DRV_NAME "(%s): DMA mask failure\n",
1604                                 pci_name(pdev));
1605                         goto err_out_regions;
1606                 }
1607                 pci_dac = 0;
1608 #ifdef IF_64BIT_DMA_IS_POSSIBLE /* grrrr... */
1609         }
1610 #endif
1611
1612         host = kzalloc(sizeof(*host), GFP_KERNEL);
1613         if (!host) {
1614                 printk(KERN_ERR DRV_NAME "(%s): memory alloc failure\n",
1615                        pci_name(pdev));
1616                 rc = -ENOMEM;
1617                 goto err_out_regions;
1618         }
1619
1620         host->pdev = pdev;
1621         host->flags = pci_dac ? FL_DAC : 0;
1622         spin_lock_init(&host->lock);
1623         INIT_WORK(&host->fsm_task, carm_fsm_task);
1624         init_completion(&host->probe_comp);
1625
1626         for (i = 0; i < ARRAY_SIZE(host->req); i++)
1627                 host->req[i].tag = i;
1628
1629         host->mmio = ioremap(pci_resource_start(pdev, 0),
1630                              pci_resource_len(pdev, 0));
1631         if (!host->mmio) {
1632                 printk(KERN_ERR DRV_NAME "(%s): MMIO alloc failure\n",
1633                        pci_name(pdev));
1634                 rc = -ENOMEM;
1635                 goto err_out_kfree;
1636         }
1637
1638         rc = carm_init_shm(host);
1639         if (rc) {
1640                 printk(KERN_ERR DRV_NAME "(%s): DMA SHM alloc failure\n",
1641                        pci_name(pdev));
1642                 goto err_out_iounmap;
1643         }
1644
1645         q = blk_init_queue(carm_oob_rq_fn, &host->lock);
1646         if (!q) {
1647                 printk(KERN_ERR DRV_NAME "(%s): OOB queue alloc failure\n",
1648                        pci_name(pdev));
1649                 rc = -ENOMEM;
1650                 goto err_out_pci_free;
1651         }
1652         host->oob_q = q;
1653         q->queuedata = host;
1654
1655         /*
1656          * Figure out which major to use: 160, 161, or dynamic
1657          */
1658         if (!test_and_set_bit(0, &carm_major_alloc))
1659                 host->major = 160;
1660         else if (!test_and_set_bit(1, &carm_major_alloc))
1661                 host->major = 161;
1662         else
1663                 host->flags |= FL_DYN_MAJOR;
1664
1665         host->id = carm_host_id;
1666         sprintf(host->name, DRV_NAME "%d", carm_host_id);
1667
1668         rc = register_blkdev(host->major, host->name);
1669         if (rc < 0)
1670                 goto err_out_free_majors;
1671         if (host->flags & FL_DYN_MAJOR)
1672                 host->major = rc;
1673
1674         rc = carm_init_disks(host);
1675         if (rc)
1676                 goto err_out_blkdev_disks;
1677
1678         pci_set_master(pdev);
1679
1680         rc = request_irq(pdev->irq, carm_interrupt, IRQF_SHARED, DRV_NAME, host);
1681         if (rc) {
1682                 printk(KERN_ERR DRV_NAME "(%s): irq alloc failure\n",
1683                        pci_name(pdev));
1684                 goto err_out_blkdev_disks;
1685         }
1686
1687         rc = carm_init_host(host);
1688         if (rc)
1689                 goto err_out_free_irq;
1690
1691         DPRINTK("waiting for probe_comp\n");
1692         wait_for_completion(&host->probe_comp);
1693
1694         printk(KERN_INFO "%s: pci %s, ports %d, io %llx, irq %u, major %d\n",
1695                host->name, pci_name(pdev), (int) CARM_MAX_PORTS,
1696                (unsigned long long)pci_resource_start(pdev, 0),
1697                    pdev->irq, host->major);
1698
1699         carm_host_id++;
1700         pci_set_drvdata(pdev, host);
1701         return 0;
1702
1703 err_out_free_irq:
1704         free_irq(pdev->irq, host);
1705 err_out_blkdev_disks:
1706         carm_free_disks(host);
1707         unregister_blkdev(host->major, host->name);
1708 err_out_free_majors:
1709         if (host->major == 160)
1710                 clear_bit(0, &carm_major_alloc);
1711         else if (host->major == 161)
1712                 clear_bit(1, &carm_major_alloc);
1713         blk_cleanup_queue(host->oob_q);
1714 err_out_pci_free:
1715         pci_free_consistent(pdev, CARM_SHM_SIZE, host->shm, host->shm_dma);
1716 err_out_iounmap:
1717         iounmap(host->mmio);
1718 err_out_kfree:
1719         kfree(host);
1720 err_out_regions:
1721         pci_release_regions(pdev);
1722 err_out:
1723         pci_disable_device(pdev);
1724         return rc;
1725 }
1726
1727 static void carm_remove_one (struct pci_dev *pdev)
1728 {
1729         struct carm_host *host = pci_get_drvdata(pdev);
1730
1731         if (!host) {
1732                 printk(KERN_ERR PFX "BUG: no host data for PCI(%s)\n",
1733                        pci_name(pdev));
1734                 return;
1735         }
1736
1737         free_irq(pdev->irq, host);
1738         carm_free_disks(host);
1739         unregister_blkdev(host->major, host->name);
1740         if (host->major == 160)
1741                 clear_bit(0, &carm_major_alloc);
1742         else if (host->major == 161)
1743                 clear_bit(1, &carm_major_alloc);
1744         blk_cleanup_queue(host->oob_q);
1745         pci_free_consistent(pdev, CARM_SHM_SIZE, host->shm, host->shm_dma);
1746         iounmap(host->mmio);
1747         kfree(host);
1748         pci_release_regions(pdev);
1749         pci_disable_device(pdev);
1750         pci_set_drvdata(pdev, NULL);
1751 }
1752
1753 static int __init carm_init(void)
1754 {
1755         return pci_register_driver(&carm_driver);
1756 }
1757
1758 static void __exit carm_exit(void)
1759 {
1760         pci_unregister_driver(&carm_driver);
1761 }
1762
1763 module_init(carm_init);
1764 module_exit(carm_exit);
1765
1766