//==========================================================================
//
//      mips_stb220_disk_ide_drivers.inl
//
//      STB220 target IDE disk driver configuration
//
//==========================================================================
// ####ECOSGPLCOPYRIGHTBEGIN####                                            
// -------------------------------------------                              
// This file is part of eCos, the Embedded Configurable Operating System.   
// Copyright (C) 2005, 2006 Free Software Foundation, Inc.                  
// Copyright (C) 2005, 2006 eCosCentric Limited                             
//
// eCos is free software; you can redistribute it and/or modify it under    
// the terms of the GNU General Public License as published by the Free     
// Software Foundation; either version 2 or (at your option) any later      
// version.                                                                 
//
// eCos is distributed in the hope that it will be useful, but WITHOUT      
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or    
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License    
// for more details.                                                        
//
// You should have received a copy of the GNU General Public License        
// along with eCos; if not, write to the Free Software Foundation, Inc.,    
// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.            
//
// As a special exception, if other files instantiate templates or use      
// macros or inline functions from this file, or you compile this file      
// and link it with other works to produce a work based on this file,       
// this file does not by itself cause the resulting work to be covered by   
// the GNU General Public License. However the source code for this file    
// must still be made available in accordance with section (3) of the GNU   
// General Public License v2.                                               
//
// This exception does not invalidate any other reasons why a work based    
// on this file might be covered by the GNU General Public License.         
// -------------------------------------------                              
// ####ECOSGPLCOPYRIGHTEND####                                              
//==========================================================================
//#####DESCRIPTIONBEGIN####
//
// Author(s):    nickg
// Contributors: 
// Date:         2005-12-01
//
//####DESCRIPTIONEND####
//
//==========================================================================

#include <pkgconf/devs_disk_mips_stb220.h>

#include <cyg/hal/hal_cache.h>

#include <cyg/hal/hal_endian.h>

#ifdef CYGPKG_DEVS_DISK_MIPS_STB220_IDE

// ----------------------------------------------------------------------------
// IDE Register Indices

#define IDE_REG_DATA            0x100
#define IDE_REG_ERROR           0x104
#define IDE_REG_FEATURES        0x104
#define IDE_REG_COUNT           0x108
#define IDE_REG_REASON          0x108  // ATAPI
#define IDE_REG_LBALOW          0x10C
#define IDE_REG_LBAMID          0x110
#define IDE_REG_LBAHI           0x114
#define IDE_REG_DEVICE          0x118
#define IDE_REG_STATUS          0x11C
#define IDE_REG_COMMAND         0x11C


#define SECTOR_SIZE      512

#define CDROM_SECTOR_SIZE 2048
#define SECTORS_PER_CDROM_SECTOR (CDROM_SECTOR_SIZE/SECTOR_SIZE)

// ----------------------------------------------------------------------------

#if CYGNUM_HAL_MIPS_STB220_IDE_ISR_PIO == 5
#define HAL_IDE_INTERRUPT_PRI   CYGNUM_HAL_ISR_PIO_5
#elif CYGNUM_HAL_MIPS_STB220_IDE_ISR_PIO == 13
#define HAL_IDE_INTERRUPT_PRI   CYGNUM_HAL_ISR_PIO_13
#else
#error Undefined IDE interrupt vector
#endif

#define __IDE_CMD_ADDR  0xB7E1A000
#define __IDE_CTL_ADDR  0xB7E1A200

// ----------------------------------------------------------------------------

#define HAL_IDE_NUM_CONTROLLERS 1

// Initialize the IDE controller. PIO pins 16, 17 and 19 must be
// controlled by the IDE device. PIO5 is connected to the IDE
// interrupt line and must be configured as an input. The interrupt
// itself is configured for a high level trigger.

static __inline__ int hal_ide_init( void )
{
    cyg_uint32 sel, dir;
    HAL_READ_UINT32(HAL_PNX8330_PIO_SEL, sel );
    sel |= (1 << 16) | (1 << 17) | (1 << 19);
    sel &= ~(1 << 5);
    HAL_WRITE_UINT32(HAL_PNX8330_PIO_SEL, sel );

    HAL_READ_UINT32(HAL_PNX8330_PIO_DIR, dir );
    dir &= ~(0x01 << 5);
    HAL_WRITE_UINT32(HAL_PNX8330_PIO_DIR, dir );

    HAL_INTERRUPT_CONFIGURE( HAL_IDE_INTERRUPT_PRI, 1, 1 );

    // set PIO timing controls
//    HAL_WRITE_UINT32( __IDE_CMD_ADDR + 4, 0x00018888 );
//    HAL_WRITE_UINT32( __IDE_CMD_ADDR + 4, 0x00014444 );
//    HAL_WRITE_UINT32( __IDE_CMD_ADDR + 4, 0x00002222 );
    HAL_WRITE_UINT32( __IDE_CMD_ADDR + 4, 0x00001111 );
//    HAL_WRITE_UINT32( __IDE_CMD_ADDR + 4, 0x00000000 );            

    // set DMA timing controls
    HAL_WRITE_UINT32( __IDE_CMD_ADDR + 8, 0x00000000 );
    
    return HAL_IDE_NUM_CONTROLLERS;
}

#define HAL_IDE_INIT() hal_ide_init()


#define HAL_IDE_READ_UINT8( __ctlr, __regno, __val )            \
{                                                               \
    cyg_uint32 __regval;                                        \
    HAL_READ_UINT32(__IDE_CMD_ADDR + (__regno), __regval);      \
    (__val) = __regval & 0xFF;                                  \
}

#define HAL_IDE_READ_UINT16( __ctlr, __regno, __val )           \
{                                                               \
    cyg_uint32 __regval;                                        \
    HAL_READ_UINT32(__IDE_CMD_ADDR + (__regno), __regval);      \
    (__val)  = CYG_SWAP16(__regval&0xFFFF);                     \
}

#undef HAL_IDE_READ_ALTSTATUS
#define HAL_IDE_READ_ALTSTATUS( __ctlr, __val ) \
{                                               \
    cyg_uint32 __regval;                        \
    HAL_READ_UINT32(__IDE_CTL_ADDR, __regval);  \
    (__val) = __regval & 0xFF;                  \
}

#define HAL_IDE_WRITE_UINT8( __ctlr, __regno, __val )           \
{                                                               \
    cyg_uint32 __regval = (__val);                              \
    HAL_WRITE_UINT32(__IDE_CMD_ADDR + (__regno), __regval);     \
}

#define HAL_IDE_WRITE_UINT16( __ctlr, __regno, __val )          \
{                                                               \
    cyg_uint32 __regval = CYG_SWAP16(__val);                    \
    HAL_WRITE_UINT32(__IDE_CMD_ADDR + (__regno), __regval);     \
}

#undef HAL_IDE_WRITE_CONTROL
#define HAL_IDE_WRITE_CONTROL( __ctlr, __val )  \
{                                               \
    cyg_uint32 __regval = (__val);              \
    HAL_WRITE_UINT32(__IDE_CTL_ADDR, __regval); \
}

//==========================================================================
// DMA support

#if CYGINT_DEVS_DISK_IDE_DMA

// ----------------------------------------------------------------------------
// Data structures

typedef struct
{
    cyg_uint32          src_addr;       // Source physical address
    cyg_uint32          dst_addr;       // Dest physical address
    cyg_uint16          dst_count;      // Byte count -1
    cyg_uint16          src_count;      // Byte count -1
    cyg_uint32          flags;          // Flags, see below
} ide_dma_descriptor;

#define IDE_DMA_FLAGS_CMD               (0xFF << 8)             // Command byte
#define IDE_DMA_FLAGS_CMD_SHIFT         8
#define IDE_DMA_FLAGS_WRITE_SIZE_1      (0x00 << 6)             // Write size
#define IDE_DMA_FLAGS_WRITE_SIZE_2      (0x01 << 6)
#define IDE_DMA_FLAGS_WRITE_SIZE_4      (0x02 << 6)
#define IDE_DMA_FLAGS_WRITE_SIZE_8      (0x03 << 6)
#define IDE_DMA_FLAGS_END               (0x01 << 5)             // End of table
#define IDE_DMA_FLAGS_INTERRUPT         (0x01 << 4)             // Interrupt
#define IDE_DMA_FLAGS_DIRECTION_S2D     (0x00 << 2)             // Src to dest
#define IDE_DMA_FLAGS_DIRECTION_S2P     (0x01 << 2)             // Src to port
#define IDE_DMA_FLAGS_DIRECTION_P2D     (0x02 << 2)             // Port to dest
#define IDE_DMA_FLAGS_DIRECTION_SPD     (0x03 << 2)             // Src to dest via port
#define IDE_DMA_FLAGS_READ_SIZE_1       (0x00 << 0)             // Write size
#define IDE_DMA_FLAGS_READ_SIZE_2       (0x01 << 0)
#define IDE_DMA_FLAGS_READ_SIZE_4       (0x02 << 0)
#define IDE_DMA_FLAGS_READ_SIZE_8       (0x03 << 0)


#define IDE_DMA_BLOCKSIZE               (64*1024)
//#define IDE_DMA_BLOCKSIZE               (12*1024)

typedef struct
{
    ide_dma_descriptor  desc[(1024*1024)/IDE_DMA_BLOCKSIZE];    // Enough for a 1MB transfer
    
} ide_dma_info;

// ----------------------------------------------------------------------------

static void ide_dma_setup( ide_controller_info_t *ctlr, int op, const void *buf, cyg_uint32 len )
{
    ide_dma_info *dma = (ide_dma_info *)ctlr->dma;
    int d = 0;
    const cyg_uint8 *bbuf = buf;
    ide_dma_descriptor *desc = NULL;

    ide_diag("ctlr %d op %d buf %p len %d\n", ctlr->ctlr, op, buf, len );
    
    // Set up the descriptor table
    while( len > 0 )
    {
        cyg_uint32 dlen = len;

        if( dlen > IDE_DMA_BLOCKSIZE )
            dlen = IDE_DMA_BLOCKSIZE;

        desc = (ide_dma_descriptor *)CYGARC_UNCACHED_ADDRESS(&dma->desc[d++]);

        desc->flags = 0;
        
        if( op == IDE_OP_READ+IDE_OP_DMA )
        {
            desc->dst_addr = CYGARC_PHYSICAL_ADDRESS(bbuf);
            desc->dst_count = dlen-1;
            desc->flags |= IDE_DMA_FLAGS_DIRECTION_P2D|
                           IDE_DMA_FLAGS_READ_SIZE_2  |
                           IDE_DMA_FLAGS_WRITE_SIZE_1 ;                
                           
            ide_diag("desc %p %p[%6d] fl %08x\n", desc, desc->dst_addr, desc->dst_count, desc->flags );
        }
        else
        {
            desc->src_addr = CYGARC_PHYSICAL_ADDRESS(bbuf);
            desc->src_count = dlen-1;
            desc->flags |= IDE_DMA_FLAGS_DIRECTION_S2P|
                           IDE_DMA_FLAGS_READ_SIZE_1  |                
                           IDE_DMA_FLAGS_WRITE_SIZE_2 ;
                           
            ide_diag("desc %p %p[%6d] fl %08x\n", desc, desc->src_addr, desc->src_count, desc->flags );
        }

        bbuf += dlen;
        len -= dlen;
    }
    
    // Mark last descriptor as the end of data.
    desc->flags |= IDE_DMA_FLAGS_END;

    // Flush the cache so that the buffers are up to date with memory
    // (NB this is for the buffers specifically - not the descriptors, since the
    // descriptors were already accessed via uncached space, although FIXME: is
    // accessing the descriptors uncached worth it then?).
    HAL_DCACHE_SYNC();
    
    // Set the DMA controller going.
    HAL_WRITE_UINT32( HAL_PNX8330_VD_NDA_A, CYGARC_PHYSICAL_ADDRESS(&dma->desc[0]) );
    HAL_WRITE_UINT32( HAL_PNX8330_VD_CMD, HAL_PNX8330_VD_CMD_NDAA_VALIDATE | HAL_PNX8330_VD_CMD_VD_ENABLE );
}

// ----------------------------------------------------------------------------

static void ide_dma_shutdown( ide_controller_info_t *ctlr, int op )
{
    // If this was a read op, flush and invalidate the cache
    if( op == IDE_OP_READ+IDE_OP_DMA )
    {
        // We must disable interrupts, because if an interrupt intervenes between
        // the SYNC and the INVALIDATE, then any memory changes it made could be
        // lost.
        CYG_INTERRUPT_STATE oldints;
        HAL_DISABLE_INTERRUPTS(oldints);
        HAL_DCACHE_SYNC();
        HAL_DCACHE_INVALIDATE_ALL();
        HAL_RESTORE_INTERRUPTS(oldints);
    }
}

// ----------------------------------------------------------------------------

static int ide_dma_init( ide_controller_info_t *ctlr, int mode, int speed )
{
    int result = 0;
    cyg_uint32 dmatim = 0;
    // Reset the DMA controller
    HAL_WRITE_UINT32( HAL_PNX8330_VD_CMD, HAL_PNX8330_VD_CMD_VD_RESET );

    if( mode == IDE_DMA_MODE_MDMA )
    {
        // MDMA mode doesn't appear to work on this hardware.
        result = -1;
#if 1
        dmatim |= HAL_PNX8330_IDE_DMA_TIM_MDMA                  |
                  HAL_PNX8330_IDE_DMA_TIM_MDMA_ADDR_ST(3)       |
                  HAL_PNX8330_IDE_DMA_TIM_MDMA_DIOX_ACTIVE(15)  |
                  HAL_PNX8330_IDE_DMA_TIM_MDMA_DIOX_RECOVERY(15);
#else
        dmatim |= HAL_PNX8330_IDE_DMA_TIM_MDMA                  |
                  HAL_PNX8330_IDE_DMA_TIM_MDMA_ADDR_ST(1)       |
                  HAL_PNX8330_IDE_DMA_TIM_MDMA_DIOX_ACTIVE(8)   |
                  HAL_PNX8330_IDE_DMA_TIM_MDMA_DIOX_RECOVERY(8) ;
#endif
    }
    else
    {
#if 1
        dmatim |= HAL_PNX8330_IDE_DMA_TIM_UDMA       |
                  HAL_PNX8330_IDE_DMA_TIM_UDMA_RP0(3)|
                  HAL_PNX8330_IDE_DMA_TIM_UDMA_CT0(3)|
                  HAL_PNX8330_IDE_DMA_TIM_UDMA_RP1(3)|
                  HAL_PNX8330_IDE_DMA_TIM_UDMA_CT1(3);
#else
        dmatim |= HAL_PNX8330_IDE_DMA_TIM_UDMA       |
                  HAL_PNX8330_IDE_DMA_TIM_UDMA_RP0(2)|
                  HAL_PNX8330_IDE_DMA_TIM_UDMA_CT0(2)|
                  HAL_PNX8330_IDE_DMA_TIM_UDMA_RP1(2)|
                  HAL_PNX8330_IDE_DMA_TIM_UDMA_CT1(2);
#endif
        result = 2;
    }
    
    HAL_WRITE_UINT32( HAL_PNX8330_IDE_DMA_TIM, dmatim );

    return result;
}

#endif


//==========================================================================
// IDE disks

// ----------------------------------------------------------------------------

#if defined(CYGVAR_DEVS_DISK_IDE_DISK0) || defined(CYGVAR_DEVS_DISK_IDE_DISK1)

#if CYGINT_DEVS_DISK_IDE_DMA
// DMA descriptors must be aligned to cache lines, otherwise they risk
// sharing a cache line with other data. Since the descriptors are accessed
// through the uncached memory address space, this would lead to problems
// the unrelated adjacent data sharing the cache line changed, causing the
// whole cache line to be written to memory.
static ide_dma_info dma_0 CYGBLD_ATTRIB_ALIGN(HAL_DCACHE_LINE_SIZE);
#endif

static ide_controller_info_t ide_controller_info_0 = {
    ctlr:       0,
#ifndef CYGVAR_DEVS_DISK_IDE_POLLED    
    vector:     HAL_IDE_INTERRUPT_PRI,
#endif
#if CYGINT_DEVS_DISK_IDE_DMA
    dma:        (CYG_ADDRWORD)&dma_0,
#endif
};

DISK_CONTROLLER( ide_disk_controller_0, ide_controller_info_0 );

#endif

// ----------------------------------------------------------------------------

#define IDE_DISK_INSTANCE(_number_,_ctlr_,_dev_,_mbr_supp_)     \
static ide_disk_info_t ide_disk_info##_number_ = {              \
    num:           _number_,                                    \
    ctlr:          &ide_controller_info_##_ctlr_,               \
    dev:           _dev_,                                       \
};                                                              \
DISK_CHANNEL(ide_disk_channel##_number_,                        \
             ide_disk_funs,                                     \
             ide_disk_info##_number_,                           \
             ide_disk_controller_##_ctlr_,                      \
             _mbr_supp_,                                        \
             4                                                  \
);                                                              \
BLOCK_DEVTAB_ENTRY(ide_disk_io##_number_,                       \
             CYGDAT_IO_DISK_IDE_DISK##_number_##_NAME,          \
             0,                                                 \
             &cyg_io_disk_devio,                                \
             ide_disk_init,                                     \
             ide_disk_lookup,                                   \
             &ide_disk_channel##_number_                        \
);

// ----------------------------------------------------------------------------

#ifdef CYGVAR_DEVS_DISK_IDE_DISK0
IDE_DISK_INSTANCE(0, 0, 0, true);
#endif
#ifdef CYGVAR_DEVS_DISK_IDE_DISK1
IDE_DISK_INSTANCE(1, 0, 1, true);
#endif

#endif

// ----------------------------------------------------------------------------
// EOF mips_pc_disk_ide_drivers.inl
