ahci: Support non-PCI controllers
[oweals/u-boot.git] / drivers / ata / ahci.c
1 /*
2  * Copyright (C) Freescale Semiconductor, Inc. 2006.
3  * Author: Jason Jin<Jason.jin@freescale.com>
4  *         Zhang Wei<wei.zhang@freescale.com>
5  *
6  * SPDX-License-Identifier:     GPL-2.0+
7  *
8  * with the reference on libata and ahci drvier in kernel
9  *
10  * This driver provides a SCSI interface to SATA.
11  */
12 #include <common.h>
13
14 #include <command.h>
15 #include <dm.h>
16 #include <pci.h>
17 #include <asm/processor.h>
18 #include <linux/errno.h>
19 #include <asm/io.h>
20 #include <malloc.h>
21 #include <memalign.h>
22 #include <pci.h>
23 #include <scsi.h>
24 #include <libata.h>
25 #include <linux/ctype.h>
26 #include <ahci.h>
27 #include <dm/device-internal.h>
28 #include <dm/lists.h>
29
30 static int ata_io_flush(struct ahci_uc_priv *uc_priv, u8 port);
31
32 #ifndef CONFIG_DM_SCSI
33 struct ahci_uc_priv *probe_ent = NULL;
34 #endif
35
36 #define writel_with_flush(a,b)  do { writel(a,b); readl(b); } while (0)
37
38 /*
39  * Some controllers limit number of blocks they can read/write at once.
40  * Contemporary SSD devices work much faster if the read/write size is aligned
41  * to a power of 2.  Let's set default to 128 and allowing to be overwritten if
42  * needed.
43  */
44 #ifndef MAX_SATA_BLOCKS_READ_WRITE
45 #define MAX_SATA_BLOCKS_READ_WRITE      0x80
46 #endif
47
48 /* Maximum timeouts for each event */
49 #define WAIT_MS_SPINUP  20000
50 #define WAIT_MS_DATAIO  10000
51 #define WAIT_MS_FLUSH   5000
52 #define WAIT_MS_LINKUP  200
53
54 __weak void __iomem *ahci_port_base(void __iomem *base, u32 port)
55 {
56         return base + 0x100 + (port * 0x80);
57 }
58
59
60 static void ahci_setup_port(struct ahci_ioports *port, void __iomem *base,
61                             unsigned int port_idx)
62 {
63         base = ahci_port_base(base, port_idx);
64
65         port->cmd_addr = base;
66         port->scr_addr = base + PORT_SCR;
67 }
68
69
70 #define msleep(a) udelay(a * 1000)
71
72 static void ahci_dcache_flush_range(unsigned long begin, unsigned long len)
73 {
74         const unsigned long start = begin;
75         const unsigned long end = start + len;
76
77         debug("%s: flush dcache: [%#lx, %#lx)\n", __func__, start, end);
78         flush_dcache_range(start, end);
79 }
80
81 /*
82  * SATA controller DMAs to physical RAM.  Ensure data from the
83  * controller is invalidated from dcache; next access comes from
84  * physical RAM.
85  */
86 static void ahci_dcache_invalidate_range(unsigned long begin, unsigned long len)
87 {
88         const unsigned long start = begin;
89         const unsigned long end = start + len;
90
91         debug("%s: invalidate dcache: [%#lx, %#lx)\n", __func__, start, end);
92         invalidate_dcache_range(start, end);
93 }
94
95 /*
96  * Ensure data for SATA controller is flushed out of dcache and
97  * written to physical memory.
98  */
99 static void ahci_dcache_flush_sata_cmd(struct ahci_ioports *pp)
100 {
101         ahci_dcache_flush_range((unsigned long)pp->cmd_slot,
102                                 AHCI_PORT_PRIV_DMA_SZ);
103 }
104
105 static int waiting_for_cmd_completed(void __iomem *offset,
106                                      int timeout_msec,
107                                      u32 sign)
108 {
109         int i;
110         u32 status;
111
112         for (i = 0; ((status = readl(offset)) & sign) && i < timeout_msec; i++)
113                 msleep(1);
114
115         return (i < timeout_msec) ? 0 : -1;
116 }
117
118 int __weak ahci_link_up(struct ahci_uc_priv *uc_priv, u8 port)
119 {
120         u32 tmp;
121         int j = 0;
122         void __iomem *port_mmio = uc_priv->port[port].port_mmio;
123
124         /*
125          * Bring up SATA link.
126          * SATA link bringup time is usually less than 1 ms; only very
127          * rarely has it taken between 1-2 ms. Never seen it above 2 ms.
128          */
129         while (j < WAIT_MS_LINKUP) {
130                 tmp = readl(port_mmio + PORT_SCR_STAT);
131                 tmp &= PORT_SCR_STAT_DET_MASK;
132                 if (tmp == PORT_SCR_STAT_DET_PHYRDY)
133                         return 0;
134                 udelay(1000);
135                 j++;
136         }
137         return 1;
138 }
139
140 #ifdef CONFIG_SUNXI_AHCI
141 /* The sunxi AHCI controller requires this undocumented setup */
142 static void sunxi_dma_init(void __iomem *port_mmio)
143 {
144         clrsetbits_le32(port_mmio + PORT_P0DMACR, 0x0000ff00, 0x00004400);
145 }
146 #endif
147
148 int ahci_reset(void __iomem *base)
149 {
150         int i = 1000;
151         u32 __iomem *host_ctl_reg = base + HOST_CTL;
152         u32 tmp = readl(host_ctl_reg); /* global controller reset */
153
154         if ((tmp & HOST_RESET) == 0)
155                 writel_with_flush(tmp | HOST_RESET, host_ctl_reg);
156
157         /*
158          * reset must complete within 1 second, or
159          * the hardware should be considered fried.
160          */
161         do {
162                 udelay(1000);
163                 tmp = readl(host_ctl_reg);
164                 i--;
165         } while ((i > 0) && (tmp & HOST_RESET));
166
167         if (i == 0) {
168                 printf("controller reset failed (0x%x)\n", tmp);
169                 return -1;
170         }
171
172         return 0;
173 }
174
175 static int ahci_host_init(struct ahci_uc_priv *uc_priv)
176 {
177 #if !defined(CONFIG_SCSI_AHCI_PLAT) && !defined(CONFIG_DM_SCSI)
178 # ifdef CONFIG_DM_PCI
179         struct udevice *dev = uc_priv->dev;
180         struct pci_child_platdata *pplat = dev_get_parent_platdata(dev);
181 # else
182         pci_dev_t pdev = uc_priv->dev;
183         unsigned short vendor;
184 # endif
185         u16 tmp16;
186 #endif
187         void __iomem *mmio = uc_priv->mmio_base;
188         u32 tmp, cap_save, cmd;
189         int i, j, ret;
190         void __iomem *port_mmio;
191         u32 port_map;
192
193         debug("ahci_host_init: start\n");
194
195         cap_save = readl(mmio + HOST_CAP);
196         cap_save &= ((1 << 28) | (1 << 17));
197         cap_save |= (1 << 27);  /* Staggered Spin-up. Not needed. */
198
199         ret = ahci_reset(uc_priv->mmio_base);
200         if (ret)
201                 return ret;
202
203         writel_with_flush(HOST_AHCI_EN, mmio + HOST_CTL);
204         writel(cap_save, mmio + HOST_CAP);
205         writel_with_flush(0xf, mmio + HOST_PORTS_IMPL);
206
207 #if !defined(CONFIG_SCSI_AHCI_PLAT) && !defined(CONFIG_DM_SCSI)
208 # ifdef CONFIG_DM_PCI
209         if (pplat->vendor == PCI_VENDOR_ID_INTEL) {
210                 u16 tmp16;
211
212                 dm_pci_read_config16(dev, 0x92, &tmp16);
213                 dm_pci_write_config16(dev, 0x92, tmp16 | 0xf);
214         }
215 # else
216         pci_read_config_word(pdev, PCI_VENDOR_ID, &vendor);
217
218         if (vendor == PCI_VENDOR_ID_INTEL) {
219                 u16 tmp16;
220                 pci_read_config_word(pdev, 0x92, &tmp16);
221                 tmp16 |= 0xf;
222                 pci_write_config_word(pdev, 0x92, tmp16);
223         }
224 # endif
225 #endif
226         uc_priv->cap = readl(mmio + HOST_CAP);
227         uc_priv->port_map = readl(mmio + HOST_PORTS_IMPL);
228         port_map = uc_priv->port_map;
229         uc_priv->n_ports = (uc_priv->cap & 0x1f) + 1;
230
231         debug("cap 0x%x  port_map 0x%x  n_ports %d\n",
232               uc_priv->cap, uc_priv->port_map, uc_priv->n_ports);
233
234         if (uc_priv->n_ports > CONFIG_SYS_SCSI_MAX_SCSI_ID)
235                 uc_priv->n_ports = CONFIG_SYS_SCSI_MAX_SCSI_ID;
236
237         for (i = 0; i < uc_priv->n_ports; i++) {
238                 if (!(port_map & (1 << i)))
239                         continue;
240                 uc_priv->port[i].port_mmio = ahci_port_base(mmio, i);
241                 port_mmio = (u8 *)uc_priv->port[i].port_mmio;
242                 ahci_setup_port(&uc_priv->port[i], mmio, i);
243
244                 /* make sure port is not active */
245                 tmp = readl(port_mmio + PORT_CMD);
246                 if (tmp & (PORT_CMD_LIST_ON | PORT_CMD_FIS_ON |
247                            PORT_CMD_FIS_RX | PORT_CMD_START)) {
248                         debug("Port %d is active. Deactivating.\n", i);
249                         tmp &= ~(PORT_CMD_LIST_ON | PORT_CMD_FIS_ON |
250                                  PORT_CMD_FIS_RX | PORT_CMD_START);
251                         writel_with_flush(tmp, port_mmio + PORT_CMD);
252
253                         /* spec says 500 msecs for each bit, so
254                          * this is slightly incorrect.
255                          */
256                         msleep(500);
257                 }
258
259 #ifdef CONFIG_SUNXI_AHCI
260                 sunxi_dma_init(port_mmio);
261 #endif
262
263                 /* Add the spinup command to whatever mode bits may
264                  * already be on in the command register.
265                  */
266                 cmd = readl(port_mmio + PORT_CMD);
267                 cmd |= PORT_CMD_SPIN_UP;
268                 writel_with_flush(cmd, port_mmio + PORT_CMD);
269
270                 /* Bring up SATA link. */
271                 ret = ahci_link_up(uc_priv, i);
272                 if (ret) {
273                         printf("SATA link %d timeout.\n", i);
274                         continue;
275                 } else {
276                         debug("SATA link ok.\n");
277                 }
278
279                 /* Clear error status */
280                 tmp = readl(port_mmio + PORT_SCR_ERR);
281                 if (tmp)
282                         writel(tmp, port_mmio + PORT_SCR_ERR);
283
284                 debug("Spinning up device on SATA port %d... ", i);
285
286                 j = 0;
287                 while (j < WAIT_MS_SPINUP) {
288                         tmp = readl(port_mmio + PORT_TFDATA);
289                         if (!(tmp & (ATA_BUSY | ATA_DRQ)))
290                                 break;
291                         udelay(1000);
292                         tmp = readl(port_mmio + PORT_SCR_STAT);
293                         tmp &= PORT_SCR_STAT_DET_MASK;
294                         if (tmp == PORT_SCR_STAT_DET_PHYRDY)
295                                 break;
296                         j++;
297                 }
298
299                 tmp = readl(port_mmio + PORT_SCR_STAT) & PORT_SCR_STAT_DET_MASK;
300                 if (tmp == PORT_SCR_STAT_DET_COMINIT) {
301                         debug("SATA link %d down (COMINIT received), retrying...\n", i);
302                         i--;
303                         continue;
304                 }
305
306                 printf("Target spinup took %d ms.\n", j);
307                 if (j == WAIT_MS_SPINUP)
308                         debug("timeout.\n");
309                 else
310                         debug("ok.\n");
311
312                 tmp = readl(port_mmio + PORT_SCR_ERR);
313                 debug("PORT_SCR_ERR 0x%x\n", tmp);
314                 writel(tmp, port_mmio + PORT_SCR_ERR);
315
316                 /* ack any pending irq events for this port */
317                 tmp = readl(port_mmio + PORT_IRQ_STAT);
318                 debug("PORT_IRQ_STAT 0x%x\n", tmp);
319                 if (tmp)
320                         writel(tmp, port_mmio + PORT_IRQ_STAT);
321
322                 writel(1 << i, mmio + HOST_IRQ_STAT);
323
324                 /* register linkup ports */
325                 tmp = readl(port_mmio + PORT_SCR_STAT);
326                 debug("SATA port %d status: 0x%x\n", i, tmp);
327                 if ((tmp & PORT_SCR_STAT_DET_MASK) == PORT_SCR_STAT_DET_PHYRDY)
328                         uc_priv->link_port_map |= (0x01 << i);
329         }
330
331         tmp = readl(mmio + HOST_CTL);
332         debug("HOST_CTL 0x%x\n", tmp);
333         writel(tmp | HOST_IRQ_EN, mmio + HOST_CTL);
334         tmp = readl(mmio + HOST_CTL);
335         debug("HOST_CTL 0x%x\n", tmp);
336 #if !defined(CONFIG_DM_SCSI)
337 #ifndef CONFIG_SCSI_AHCI_PLAT
338 # ifdef CONFIG_DM_PCI
339         dm_pci_read_config16(dev, PCI_COMMAND, &tmp16);
340         tmp |= PCI_COMMAND_MASTER;
341         dm_pci_write_config16(dev, PCI_COMMAND, tmp16);
342 # else
343         pci_read_config_word(pdev, PCI_COMMAND, &tmp16);
344         tmp |= PCI_COMMAND_MASTER;
345         pci_write_config_word(pdev, PCI_COMMAND, tmp16);
346 # endif
347 #endif
348 #endif
349         return 0;
350 }
351
352
353 static void ahci_print_info(struct ahci_uc_priv *uc_priv)
354 {
355 #if !defined(CONFIG_SCSI_AHCI_PLAT) && !defined(CONFIG_DM_SCSI)
356 # if defined(CONFIG_DM_PCI)
357         struct udevice *dev = uc_priv->dev;
358 # else
359         pci_dev_t pdev = uc_priv->dev;
360 # endif
361         u16 cc;
362 #endif
363         void __iomem *mmio = uc_priv->mmio_base;
364         u32 vers, cap, cap2, impl, speed;
365         const char *speed_s;
366         const char *scc_s;
367
368         vers = readl(mmio + HOST_VERSION);
369         cap = uc_priv->cap;
370         cap2 = readl(mmio + HOST_CAP2);
371         impl = uc_priv->port_map;
372
373         speed = (cap >> 20) & 0xf;
374         if (speed == 1)
375                 speed_s = "1.5";
376         else if (speed == 2)
377                 speed_s = "3";
378         else if (speed == 3)
379                 speed_s = "6";
380         else
381                 speed_s = "?";
382
383 #if defined(CONFIG_SCSI_AHCI_PLAT) || defined(CONFIG_DM_SCSI)
384         scc_s = "SATA";
385 #else
386 # ifdef CONFIG_DM_PCI
387         dm_pci_read_config16(dev, 0x0a, &cc);
388 # else
389         pci_read_config_word(pdev, 0x0a, &cc);
390 # endif
391         if (cc == 0x0101)
392                 scc_s = "IDE";
393         else if (cc == 0x0106)
394                 scc_s = "SATA";
395         else if (cc == 0x0104)
396                 scc_s = "RAID";
397         else
398                 scc_s = "unknown";
399 #endif
400         printf("AHCI %02x%02x.%02x%02x "
401                "%u slots %u ports %s Gbps 0x%x impl %s mode\n",
402                (vers >> 24) & 0xff,
403                (vers >> 16) & 0xff,
404                (vers >> 8) & 0xff,
405                vers & 0xff,
406                ((cap >> 8) & 0x1f) + 1, (cap & 0x1f) + 1, speed_s, impl, scc_s);
407
408         printf("flags: "
409                "%s%s%s%s%s%s%s"
410                "%s%s%s%s%s%s%s"
411                "%s%s%s%s%s%s\n",
412                cap & (1 << 31) ? "64bit " : "",
413                cap & (1 << 30) ? "ncq " : "",
414                cap & (1 << 28) ? "ilck " : "",
415                cap & (1 << 27) ? "stag " : "",
416                cap & (1 << 26) ? "pm " : "",
417                cap & (1 << 25) ? "led " : "",
418                cap & (1 << 24) ? "clo " : "",
419                cap & (1 << 19) ? "nz " : "",
420                cap & (1 << 18) ? "only " : "",
421                cap & (1 << 17) ? "pmp " : "",
422                cap & (1 << 16) ? "fbss " : "",
423                cap & (1 << 15) ? "pio " : "",
424                cap & (1 << 14) ? "slum " : "",
425                cap & (1 << 13) ? "part " : "",
426                cap & (1 << 7) ? "ccc " : "",
427                cap & (1 << 6) ? "ems " : "",
428                cap & (1 << 5) ? "sxs " : "",
429                cap2 & (1 << 2) ? "apst " : "",
430                cap2 & (1 << 1) ? "nvmp " : "",
431                cap2 & (1 << 0) ? "boh " : "");
432 }
433
434 #if defined(CONFIG_DM_SCSI) || !defined(CONFIG_SCSI_AHCI_PLAT)
435 # if defined(CONFIG_DM_PCI) || defined(CONFIG_DM_SCSI)
436 static int ahci_init_one(struct ahci_uc_priv *uc_priv, struct udevice *dev)
437 # else
438 static int ahci_init_one(struct ahci_uc_priv *uc_priv, pci_dev_t dev)
439 # endif
440 {
441 #if !defined(CONFIG_DM_SCSI)
442         u16 vendor;
443 #endif
444         int rc;
445
446         uc_priv->dev = dev;
447
448         uc_priv->host_flags = ATA_FLAG_SATA
449                                 | ATA_FLAG_NO_LEGACY
450                                 | ATA_FLAG_MMIO
451                                 | ATA_FLAG_PIO_DMA
452                                 | ATA_FLAG_NO_ATAPI;
453         uc_priv->pio_mask = 0x1f;
454         uc_priv->udma_mask = 0x7f;      /*Fixme,assume to support UDMA6 */
455
456 #if !defined(CONFIG_DM_SCSI)
457 #ifdef CONFIG_DM_PCI
458         uc_priv->mmio_base = dm_pci_map_bar(dev, PCI_BASE_ADDRESS_5,
459                                               PCI_REGION_MEM);
460
461         /* Take from kernel:
462          * JMicron-specific fixup:
463          * make sure we're in AHCI mode
464          */
465         dm_pci_read_config16(dev, PCI_VENDOR_ID, &vendor);
466         if (vendor == 0x197b)
467                 dm_pci_write_config8(dev, 0x41, 0xa1);
468 #else
469         uc_priv->mmio_base = pci_map_bar(dev, PCI_BASE_ADDRESS_5,
470                                            PCI_REGION_MEM);
471
472         /* Take from kernel:
473          * JMicron-specific fixup:
474          * make sure we're in AHCI mode
475          */
476         pci_read_config_word(dev, PCI_VENDOR_ID, &vendor);
477         if (vendor == 0x197b)
478                 pci_write_config_byte(dev, 0x41, 0xa1);
479 #endif
480 #else
481         struct scsi_platdata *plat = dev_get_uclass_platdata(dev);
482         uc_priv->mmio_base = (void *)plat->base;
483 #endif
484
485         debug("ahci mmio_base=0x%p\n", uc_priv->mmio_base);
486         /* initialize adapter */
487         rc = ahci_host_init(uc_priv);
488         if (rc)
489                 goto err_out;
490
491         ahci_print_info(uc_priv);
492
493         return 0;
494
495       err_out:
496         return rc;
497 }
498 #endif
499
500 #define MAX_DATA_BYTE_COUNT  (4*1024*1024)
501
502 static int ahci_fill_sg(struct ahci_uc_priv *uc_priv, u8 port,
503                         unsigned char *buf, int buf_len)
504 {
505         struct ahci_ioports *pp = &(uc_priv->port[port]);
506         struct ahci_sg *ahci_sg = pp->cmd_tbl_sg;
507         u32 sg_count;
508         int i;
509
510         sg_count = ((buf_len - 1) / MAX_DATA_BYTE_COUNT) + 1;
511         if (sg_count > AHCI_MAX_SG) {
512                 printf("Error:Too much sg!\n");
513                 return -1;
514         }
515
516         for (i = 0; i < sg_count; i++) {
517                 ahci_sg->addr =
518                     cpu_to_le32((unsigned long) buf + i * MAX_DATA_BYTE_COUNT);
519                 ahci_sg->addr_hi = 0;
520                 ahci_sg->flags_size = cpu_to_le32(0x3fffff &
521                                           (buf_len < MAX_DATA_BYTE_COUNT
522                                            ? (buf_len - 1)
523                                            : (MAX_DATA_BYTE_COUNT - 1)));
524                 ahci_sg++;
525                 buf_len -= MAX_DATA_BYTE_COUNT;
526         }
527
528         return sg_count;
529 }
530
531
532 static void ahci_fill_cmd_slot(struct ahci_ioports *pp, u32 opts)
533 {
534         pp->cmd_slot->opts = cpu_to_le32(opts);
535         pp->cmd_slot->status = 0;
536         pp->cmd_slot->tbl_addr = cpu_to_le32((u32)pp->cmd_tbl & 0xffffffff);
537 #ifdef CONFIG_PHYS_64BIT
538         pp->cmd_slot->tbl_addr_hi =
539             cpu_to_le32((u32)(((pp->cmd_tbl) >> 16) >> 16));
540 #endif
541 }
542
543 static int wait_spinup(void __iomem *port_mmio)
544 {
545         ulong start;
546         u32 tf_data;
547
548         start = get_timer(0);
549         do {
550                 tf_data = readl(port_mmio + PORT_TFDATA);
551                 if (!(tf_data & ATA_BUSY))
552                         return 0;
553         } while (get_timer(start) < WAIT_MS_SPINUP);
554
555         return -ETIMEDOUT;
556 }
557
558 static int ahci_port_start(struct ahci_uc_priv *uc_priv, u8 port)
559 {
560         struct ahci_ioports *pp = &(uc_priv->port[port]);
561         void __iomem *port_mmio = pp->port_mmio;
562         u32 port_status;
563         void __iomem *mem;
564
565         debug("Enter start port: %d\n", port);
566         port_status = readl(port_mmio + PORT_SCR_STAT);
567         debug("Port %d status: %x\n", port, port_status);
568         if ((port_status & 0xf) != 0x03) {
569                 printf("No Link on this port!\n");
570                 return -1;
571         }
572
573         mem = malloc(AHCI_PORT_PRIV_DMA_SZ + 2048);
574         if (!mem) {
575                 free(pp);
576                 printf("%s: No mem for table!\n", __func__);
577                 return -ENOMEM;
578         }
579
580         /* Aligned to 2048-bytes */
581         mem = memalign(2048, AHCI_PORT_PRIV_DMA_SZ);
582         memset(mem, 0, AHCI_PORT_PRIV_DMA_SZ);
583
584         /*
585          * First item in chunk of DMA memory: 32-slot command table,
586          * 32 bytes each in size
587          */
588         pp->cmd_slot =
589                 (struct ahci_cmd_hdr *)(uintptr_t)virt_to_phys((void *)mem);
590         debug("cmd_slot = %p\n", pp->cmd_slot);
591         mem += (AHCI_CMD_SLOT_SZ + 224);
592
593         /*
594          * Second item: Received-FIS area
595          */
596         pp->rx_fis = virt_to_phys((void *)mem);
597         mem += AHCI_RX_FIS_SZ;
598
599         /*
600          * Third item: data area for storing a single command
601          * and its scatter-gather table
602          */
603         pp->cmd_tbl = virt_to_phys((void *)mem);
604         debug("cmd_tbl_dma = %lx\n", pp->cmd_tbl);
605
606         mem += AHCI_CMD_TBL_HDR;
607         pp->cmd_tbl_sg =
608                         (struct ahci_sg *)(uintptr_t)virt_to_phys((void *)mem);
609
610         writel_with_flush((unsigned long)pp->cmd_slot,
611                           port_mmio + PORT_LST_ADDR);
612
613         writel_with_flush(pp->rx_fis, port_mmio + PORT_FIS_ADDR);
614
615 #ifdef CONFIG_SUNXI_AHCI
616         sunxi_dma_init(port_mmio);
617 #endif
618
619         writel_with_flush(PORT_CMD_ICC_ACTIVE | PORT_CMD_FIS_RX |
620                           PORT_CMD_POWER_ON | PORT_CMD_SPIN_UP |
621                           PORT_CMD_START, port_mmio + PORT_CMD);
622
623         debug("Exit start port %d\n", port);
624
625         /*
626          * Make sure interface is not busy based on error and status
627          * information from task file data register before proceeding
628          */
629         return wait_spinup(port_mmio);
630 }
631
632
633 static int ahci_device_data_io(struct ahci_uc_priv *uc_priv, u8 port, u8 *fis,
634                                int fis_len, u8 *buf, int buf_len, u8 is_write)
635 {
636
637         struct ahci_ioports *pp = &(uc_priv->port[port]);
638         void __iomem *port_mmio = pp->port_mmio;
639         u32 opts;
640         u32 port_status;
641         int sg_count;
642
643         debug("Enter %s: for port %d\n", __func__, port);
644
645         if (port > uc_priv->n_ports) {
646                 printf("Invalid port number %d\n", port);
647                 return -1;
648         }
649
650         port_status = readl(port_mmio + PORT_SCR_STAT);
651         if ((port_status & 0xf) != 0x03) {
652                 debug("No Link on port %d!\n", port);
653                 return -1;
654         }
655
656         memcpy((unsigned char *)pp->cmd_tbl, fis, fis_len);
657
658         sg_count = ahci_fill_sg(uc_priv, port, buf, buf_len);
659         opts = (fis_len >> 2) | (sg_count << 16) | (is_write << 6);
660         ahci_fill_cmd_slot(pp, opts);
661
662         ahci_dcache_flush_sata_cmd(pp);
663         ahci_dcache_flush_range((unsigned long)buf, (unsigned long)buf_len);
664
665         writel_with_flush(1, port_mmio + PORT_CMD_ISSUE);
666
667         if (waiting_for_cmd_completed(port_mmio + PORT_CMD_ISSUE,
668                                 WAIT_MS_DATAIO, 0x1)) {
669                 printf("timeout exit!\n");
670                 return -1;
671         }
672
673         ahci_dcache_invalidate_range((unsigned long)buf,
674                                      (unsigned long)buf_len);
675         debug("%s: %d byte transferred.\n", __func__, pp->cmd_slot->status);
676
677         return 0;
678 }
679
680
681 static char *ata_id_strcpy(u16 *target, u16 *src, int len)
682 {
683         int i;
684         for (i = 0; i < len / 2; i++)
685                 target[i] = swab16(src[i]);
686         return (char *)target;
687 }
688
689 /*
690  * SCSI INQUIRY command operation.
691  */
692 static int ata_scsiop_inquiry(struct ahci_uc_priv *uc_priv,
693                               struct scsi_cmd *pccb)
694 {
695         static const u8 hdr[] = {
696                 0,
697                 0,
698                 0x5,            /* claim SPC-3 version compatibility */
699                 2,
700                 95 - 4,
701         };
702         u8 fis[20];
703         u16 *idbuf;
704         ALLOC_CACHE_ALIGN_BUFFER(u16, tmpid, ATA_ID_WORDS);
705         u8 port;
706
707         /* Clean ccb data buffer */
708         memset(pccb->pdata, 0, pccb->datalen);
709
710         memcpy(pccb->pdata, hdr, sizeof(hdr));
711
712         if (pccb->datalen <= 35)
713                 return 0;
714
715         memset(fis, 0, sizeof(fis));
716         /* Construct the FIS */
717         fis[0] = 0x27;          /* Host to device FIS. */
718         fis[1] = 1 << 7;        /* Command FIS. */
719         fis[2] = ATA_CMD_ID_ATA; /* Command byte. */
720
721         /* Read id from sata */
722         port = pccb->target;
723
724         if (ahci_device_data_io(uc_priv, port, (u8 *)&fis, sizeof(fis),
725                                 (u8 *)tmpid, ATA_ID_WORDS * 2, 0)) {
726                 debug("scsi_ahci: SCSI inquiry command failure.\n");
727                 return -EIO;
728         }
729
730         if (!uc_priv->ataid[port]) {
731                 uc_priv->ataid[port] = malloc(ATA_ID_WORDS * 2);
732                 if (!uc_priv->ataid[port]) {
733                         printf("%s: No memory for ataid[port]\n", __func__);
734                         return -ENOMEM;
735                 }
736         }
737
738         idbuf = uc_priv->ataid[port];
739
740         memcpy(idbuf, tmpid, ATA_ID_WORDS * 2);
741         ata_swap_buf_le16(idbuf, ATA_ID_WORDS);
742
743         memcpy(&pccb->pdata[8], "ATA     ", 8);
744         ata_id_strcpy((u16 *)&pccb->pdata[16], &idbuf[ATA_ID_PROD], 16);
745         ata_id_strcpy((u16 *)&pccb->pdata[32], &idbuf[ATA_ID_FW_REV], 4);
746
747 #ifdef DEBUG
748         ata_dump_id(idbuf);
749 #endif
750         return 0;
751 }
752
753
754 /*
755  * SCSI READ10/WRITE10 command operation.
756  */
757 static int ata_scsiop_read_write(struct ahci_uc_priv *uc_priv,
758                                  struct scsi_cmd *pccb, u8 is_write)
759 {
760         lbaint_t lba = 0;
761         u16 blocks = 0;
762         u8 fis[20];
763         u8 *user_buffer = pccb->pdata;
764         u32 user_buffer_size = pccb->datalen;
765
766         /* Retrieve the base LBA number from the ccb structure. */
767         if (pccb->cmd[0] == SCSI_READ16) {
768                 memcpy(&lba, pccb->cmd + 2, 8);
769                 lba = be64_to_cpu(lba);
770         } else {
771                 u32 temp;
772                 memcpy(&temp, pccb->cmd + 2, 4);
773                 lba = be32_to_cpu(temp);
774         }
775
776         /*
777          * Retrieve the base LBA number and the block count from
778          * the ccb structure.
779          *
780          * For 10-byte and 16-byte SCSI R/W commands, transfer
781          * length 0 means transfer 0 block of data.
782          * However, for ATA R/W commands, sector count 0 means
783          * 256 or 65536 sectors, not 0 sectors as in SCSI.
784          *
785          * WARNING: one or two older ATA drives treat 0 as 0...
786          */
787         if (pccb->cmd[0] == SCSI_READ16)
788                 blocks = (((u16)pccb->cmd[13]) << 8) | ((u16) pccb->cmd[14]);
789         else
790                 blocks = (((u16)pccb->cmd[7]) << 8) | ((u16) pccb->cmd[8]);
791
792         debug("scsi_ahci: %s %u blocks starting from lba 0x" LBAFU "\n",
793               is_write ?  "write" : "read", blocks, lba);
794
795         /* Preset the FIS */
796         memset(fis, 0, sizeof(fis));
797         fis[0] = 0x27;           /* Host to device FIS. */
798         fis[1] = 1 << 7;         /* Command FIS. */
799         /* Command byte (read/write). */
800         fis[2] = is_write ? ATA_CMD_WRITE_EXT : ATA_CMD_READ_EXT;
801
802         while (blocks) {
803                 u16 now_blocks; /* number of blocks per iteration */
804                 u32 transfer_size; /* number of bytes per iteration */
805
806                 now_blocks = min((u16)MAX_SATA_BLOCKS_READ_WRITE, blocks);
807
808                 transfer_size = ATA_SECT_SIZE * now_blocks;
809                 if (transfer_size > user_buffer_size) {
810                         printf("scsi_ahci: Error: buffer too small.\n");
811                         return -EIO;
812                 }
813
814                 /*
815                  * LBA48 SATA command but only use 32bit address range within
816                  * that (unless we've enabled 64bit LBA support). The next
817                  * smaller command range (28bit) is too small.
818                  */
819                 fis[4] = (lba >> 0) & 0xff;
820                 fis[5] = (lba >> 8) & 0xff;
821                 fis[6] = (lba >> 16) & 0xff;
822                 fis[7] = 1 << 6; /* device reg: set LBA mode */
823                 fis[8] = ((lba >> 24) & 0xff);
824 #ifdef CONFIG_SYS_64BIT_LBA
825                 if (pccb->cmd[0] == SCSI_READ16) {
826                         fis[9] = ((lba >> 32) & 0xff);
827                         fis[10] = ((lba >> 40) & 0xff);
828                 }
829 #endif
830
831                 fis[3] = 0xe0; /* features */
832
833                 /* Block (sector) count */
834                 fis[12] = (now_blocks >> 0) & 0xff;
835                 fis[13] = (now_blocks >> 8) & 0xff;
836
837                 /* Read/Write from ahci */
838                 if (ahci_device_data_io(uc_priv, pccb->target, (u8 *)&fis,
839                                         sizeof(fis), user_buffer, transfer_size,
840                                         is_write)) {
841                         debug("scsi_ahci: SCSI %s10 command failure.\n",
842                               is_write ? "WRITE" : "READ");
843                         return -EIO;
844                 }
845
846                 /* If this transaction is a write, do a following flush.
847                  * Writes in u-boot are so rare, and the logic to know when is
848                  * the last write and do a flush only there is sufficiently
849                  * difficult. Just do a flush after every write. This incurs,
850                  * usually, one extra flush when the rare writes do happen.
851                  */
852                 if (is_write) {
853                         if (-EIO == ata_io_flush(uc_priv, pccb->target))
854                                 return -EIO;
855                 }
856                 user_buffer += transfer_size;
857                 user_buffer_size -= transfer_size;
858                 blocks -= now_blocks;
859                 lba += now_blocks;
860         }
861
862         return 0;
863 }
864
865
866 /*
867  * SCSI READ CAPACITY10 command operation.
868  */
869 static int ata_scsiop_read_capacity10(struct ahci_uc_priv *uc_priv,
870                                       struct scsi_cmd *pccb)
871 {
872         u32 cap;
873         u64 cap64;
874         u32 block_size;
875
876         if (!uc_priv->ataid[pccb->target]) {
877                 printf("scsi_ahci: SCSI READ CAPACITY10 command failure. "
878                        "\tNo ATA info!\n"
879                        "\tPlease run SCSI command INQUIRY first!\n");
880                 return -EPERM;
881         }
882
883         cap64 = ata_id_n_sectors(uc_priv->ataid[pccb->target]);
884         if (cap64 > 0x100000000ULL)
885                 cap64 = 0xffffffff;
886
887         cap = cpu_to_be32(cap64);
888         memcpy(pccb->pdata, &cap, sizeof(cap));
889
890         block_size = cpu_to_be32((u32)512);
891         memcpy(&pccb->pdata[4], &block_size, 4);
892
893         return 0;
894 }
895
896
897 /*
898  * SCSI READ CAPACITY16 command operation.
899  */
900 static int ata_scsiop_read_capacity16(struct ahci_uc_priv *uc_priv,
901                                       struct scsi_cmd *pccb)
902 {
903         u64 cap;
904         u64 block_size;
905
906         if (!uc_priv->ataid[pccb->target]) {
907                 printf("scsi_ahci: SCSI READ CAPACITY16 command failure. "
908                        "\tNo ATA info!\n"
909                        "\tPlease run SCSI command INQUIRY first!\n");
910                 return -EPERM;
911         }
912
913         cap = ata_id_n_sectors(uc_priv->ataid[pccb->target]);
914         cap = cpu_to_be64(cap);
915         memcpy(pccb->pdata, &cap, sizeof(cap));
916
917         block_size = cpu_to_be64((u64)512);
918         memcpy(&pccb->pdata[8], &block_size, 8);
919
920         return 0;
921 }
922
923
924 /*
925  * SCSI TEST UNIT READY command operation.
926  */
927 static int ata_scsiop_test_unit_ready(struct ahci_uc_priv *uc_priv,
928                                       struct scsi_cmd *pccb)
929 {
930         return (uc_priv->ataid[pccb->target]) ? 0 : -EPERM;
931 }
932
933
934 static int ahci_scsi_exec(struct udevice *dev, struct scsi_cmd *pccb)
935 {
936         struct ahci_uc_priv *uc_priv;
937 #ifdef CONFIG_DM_SCSI
938         uc_priv = dev_get_uclass_priv(dev);
939 #else
940         uc_priv = probe_ent;
941 #endif
942         int ret;
943
944         switch (pccb->cmd[0]) {
945         case SCSI_READ16:
946         case SCSI_READ10:
947                 ret = ata_scsiop_read_write(uc_priv, pccb, 0);
948                 break;
949         case SCSI_WRITE10:
950                 ret = ata_scsiop_read_write(uc_priv, pccb, 1);
951                 break;
952         case SCSI_RD_CAPAC10:
953                 ret = ata_scsiop_read_capacity10(uc_priv, pccb);
954                 break;
955         case SCSI_RD_CAPAC16:
956                 ret = ata_scsiop_read_capacity16(uc_priv, pccb);
957                 break;
958         case SCSI_TST_U_RDY:
959                 ret = ata_scsiop_test_unit_ready(uc_priv, pccb);
960                 break;
961         case SCSI_INQUIRY:
962                 ret = ata_scsiop_inquiry(uc_priv, pccb);
963                 break;
964         default:
965                 printf("Unsupport SCSI command 0x%02x\n", pccb->cmd[0]);
966                 return -ENOTSUPP;
967         }
968
969         if (ret) {
970                 debug("SCSI command 0x%02x ret errno %d\n", pccb->cmd[0], ret);
971                 return ret;
972         }
973         return 0;
974
975 }
976
977 static int ahci_start_ports(struct ahci_uc_priv *uc_priv)
978 {
979         u32 linkmap;
980         int i;
981
982         linkmap = uc_priv->link_port_map;
983
984         for (i = 0; i < CONFIG_SYS_SCSI_MAX_SCSI_ID; i++) {
985                 if (((linkmap >> i) & 0x01)) {
986                         if (ahci_port_start(uc_priv, (u8) i)) {
987                                 printf("Can not start port %d\n", i);
988                                 continue;
989                         }
990                 }
991         }
992
993         return 0;
994 }
995
996 #ifndef CONFIG_DM_SCSI
997 void scsi_low_level_init(int busdevfunc)
998 {
999         struct ahci_uc_priv *uc_priv;
1000
1001 #ifndef CONFIG_SCSI_AHCI_PLAT
1002         probe_ent = calloc(1, sizeof(struct ahci_uc_priv));
1003         if (!probe_ent) {
1004                 printf("%s: No memory for uc_priv\n", __func__);
1005                 return;
1006         }
1007         uc_priv = probe_ent;
1008 # if defined(CONFIG_DM_PCI)
1009         struct udevice *dev;
1010         int ret;
1011
1012         ret = dm_pci_bus_find_bdf(busdevfunc, &dev);
1013         if (ret)
1014                 return;
1015         ahci_init_one(uc_priv, dev);
1016 # else
1017         ahci_init_one(uc_priv, busdevfunc);
1018 # endif
1019 #else
1020         uc_priv = probe_ent;
1021 #endif
1022
1023         ahci_start_ports(uc_priv);
1024 }
1025 #endif
1026
1027 #ifndef CONFIG_SCSI_AHCI_PLAT
1028 # if defined(CONFIG_DM_PCI) || defined(CONFIG_DM_SCSI)
1029 int achi_init_one_dm(struct udevice *dev)
1030 {
1031         struct ahci_uc_priv *uc_priv = dev_get_uclass_priv(dev);
1032
1033         return ahci_init_one(uc_priv, dev);
1034 }
1035 #endif
1036 #endif
1037
1038 int achi_start_ports_dm(struct udevice *dev)
1039 {
1040         struct ahci_uc_priv *uc_priv = dev_get_uclass_priv(dev);
1041
1042         return ahci_start_ports(uc_priv);
1043 }
1044
1045 #ifdef CONFIG_SCSI_AHCI_PLAT
1046 static int ahci_init_common(struct ahci_uc_priv *uc_priv, void __iomem *base)
1047 {
1048         int rc;
1049
1050         uc_priv->host_flags = ATA_FLAG_SATA
1051                                 | ATA_FLAG_NO_LEGACY
1052                                 | ATA_FLAG_MMIO
1053                                 | ATA_FLAG_PIO_DMA
1054                                 | ATA_FLAG_NO_ATAPI;
1055         uc_priv->pio_mask = 0x1f;
1056         uc_priv->udma_mask = 0x7f;      /*Fixme,assume to support UDMA6 */
1057
1058         uc_priv->mmio_base = base;
1059
1060         /* initialize adapter */
1061         rc = ahci_host_init(uc_priv);
1062         if (rc)
1063                 goto err_out;
1064
1065         ahci_print_info(uc_priv);
1066
1067         rc = ahci_start_ports(uc_priv);
1068
1069 err_out:
1070         return rc;
1071 }
1072
1073 #ifndef CONFIG_DM_SCSI
1074 int ahci_init(void __iomem *base)
1075 {
1076         struct ahci_uc_priv *uc_priv;
1077
1078         probe_ent = malloc(sizeof(struct ahci_uc_priv));
1079         if (!probe_ent) {
1080                 printf("%s: No memory for uc_priv\n", __func__);
1081                 return -ENOMEM;
1082         }
1083
1084         uc_priv = probe_ent;
1085         memset(uc_priv, 0, sizeof(struct ahci_uc_priv));
1086
1087         return ahci_init_common(uc_priv, base);
1088 }
1089 #endif
1090
1091 int ahci_init_dm(struct udevice *dev, void __iomem *base)
1092 {
1093         struct ahci_uc_priv *uc_priv = dev_get_uclass_priv(dev);
1094
1095         return ahci_init_common(uc_priv, base);
1096 }
1097
1098 void __weak scsi_init(void)
1099 {
1100 }
1101
1102 #endif /* CONFIG_SCSI_AHCI_PLAT */
1103
1104 /*
1105  * In the general case of generic rotating media it makes sense to have a
1106  * flush capability. It probably even makes sense in the case of SSDs because
1107  * one cannot always know for sure what kind of internal cache/flush mechanism
1108  * is embodied therein. At first it was planned to invoke this after the last
1109  * write to disk and before rebooting. In practice, knowing, a priori, which
1110  * is the last write is difficult. Because writing to the disk in u-boot is
1111  * very rare, this flush command will be invoked after every block write.
1112  */
1113 static int ata_io_flush(struct ahci_uc_priv *uc_priv, u8 port)
1114 {
1115         u8 fis[20];
1116         struct ahci_ioports *pp = &(uc_priv->port[port]);
1117         void __iomem *port_mmio = pp->port_mmio;
1118         u32 cmd_fis_len = 5;    /* five dwords */
1119
1120         /* Preset the FIS */
1121         memset(fis, 0, 20);
1122         fis[0] = 0x27;           /* Host to device FIS. */
1123         fis[1] = 1 << 7;         /* Command FIS. */
1124         fis[2] = ATA_CMD_FLUSH_EXT;
1125
1126         memcpy((unsigned char *)pp->cmd_tbl, fis, 20);
1127         ahci_fill_cmd_slot(pp, cmd_fis_len);
1128         ahci_dcache_flush_sata_cmd(pp);
1129         writel_with_flush(1, port_mmio + PORT_CMD_ISSUE);
1130
1131         if (waiting_for_cmd_completed(port_mmio + PORT_CMD_ISSUE,
1132                         WAIT_MS_FLUSH, 0x1)) {
1133                 debug("scsi_ahci: flush command timeout on port %d.\n", port);
1134                 return -EIO;
1135         }
1136
1137         return 0;
1138 }
1139
1140 static int ahci_scsi_bus_reset(struct udevice *dev)
1141 {
1142         /* Not implemented */
1143
1144         return 0;
1145 }
1146
1147 #ifdef CONFIG_DM_SCSI
1148 int ahci_bind_scsi(struct udevice *ahci_dev, struct udevice **devp)
1149 {
1150         struct udevice *dev;
1151         int ret;
1152
1153         ret = device_bind_driver(ahci_dev, "ahci_scsi", "ahci_scsi", &dev);
1154         if (ret)
1155                 return ret;
1156         *devp = dev;
1157
1158         return 0;
1159 }
1160
1161 int ahci_probe_scsi(struct udevice *ahci_dev, ulong base)
1162 {
1163         struct ahci_uc_priv *uc_priv;
1164         struct scsi_platdata *uc_plat;
1165         struct udevice *dev;
1166         int ret;
1167
1168         device_find_first_child(ahci_dev, &dev);
1169         if (!dev)
1170                 return -ENODEV;
1171         uc_plat = dev_get_uclass_platdata(dev);
1172         uc_plat->base = base;
1173         uc_plat->max_lun = 1;
1174         uc_plat->max_id = 2;
1175
1176         uc_priv = dev_get_uclass_priv(ahci_dev);
1177         ret = ahci_init_one(uc_priv, dev);
1178         if (ret)
1179                 return ret;
1180         ret = ahci_start_ports(uc_priv);
1181         if (ret)
1182                 return ret;
1183
1184         return 0;
1185 }
1186
1187 #ifdef CONFIG_DM_PCI
1188 int ahci_probe_scsi_pci(struct udevice *ahci_dev)
1189 {
1190         ulong base;
1191
1192         base = (ulong)dm_pci_map_bar(ahci_dev, PCI_BASE_ADDRESS_5,
1193                                      PCI_REGION_MEM);
1194
1195         return ahci_probe_scsi(ahci_dev, base);
1196 }
1197 #endif
1198
1199 struct scsi_ops scsi_ops = {
1200         .exec           = ahci_scsi_exec,
1201         .bus_reset      = ahci_scsi_bus_reset,
1202 };
1203
1204 U_BOOT_DRIVER(ahci_scsi) = {
1205         .name           = "ahci_scsi",
1206         .id             = UCLASS_SCSI,
1207         .ops            = &scsi_ops,
1208 };
1209 #else
1210 int scsi_exec(struct udevice *dev, struct scsi_cmd *pccb)
1211 {
1212         return ahci_scsi_exec(dev, pccb);
1213 }
1214
1215 __weak int scsi_bus_reset(struct udevice *dev)
1216 {
1217         return ahci_scsi_bus_reset(dev);
1218
1219         return 0;
1220 }
1221 #endif