diff --git a/build/RockchipDrivers.sln b/build/RockchipDrivers.sln index 6331150..0fa6bdb 100644 --- a/build/RockchipDrivers.sln +++ b/build/RockchipDrivers.sln @@ -9,6 +9,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "rk3xi2c", "..\drivers\i2c\r EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "rk3xgpio", "..\drivers\gpio\rk3xgpio\rk3xgpio.vcxproj", "{A80FE9DD-C140-40F6-A3F4-55A2A55BFAD4}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pl330dma", "..\drivers\dma\pl330dma\pl330.vcxproj", "{58434B4F-EE73-4D1E-A78D-9FEC5CEC83C7}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|ARM64 = Debug|ARM64 @@ -33,6 +35,12 @@ Global {A80FE9DD-C140-40F6-A3F4-55A2A55BFAD4}.Release|ARM64.ActiveCfg = Release|ARM64 {A80FE9DD-C140-40F6-A3F4-55A2A55BFAD4}.Release|ARM64.Build.0 = Release|ARM64 {A80FE9DD-C140-40F6-A3F4-55A2A55BFAD4}.Release|ARM64.Deploy.0 = Release|ARM64 + {58434B4F-EE73-4D1E-A78D-9FEC5CEC83C7}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {58434B4F-EE73-4D1E-A78D-9FEC5CEC83C7}.Debug|ARM64.Build.0 = Debug|ARM64 + {58434B4F-EE73-4D1E-A78D-9FEC5CEC83C7}.Debug|ARM64.Deploy.0 = Debug|ARM64 + {58434B4F-EE73-4D1E-A78D-9FEC5CEC83C7}.Release|ARM64.ActiveCfg = Release|ARM64 + {58434B4F-EE73-4D1E-A78D-9FEC5CEC83C7}.Release|ARM64.Build.0 = Release|ARM64 + {58434B4F-EE73-4D1E-A78D-9FEC5CEC83C7}.Release|ARM64.Deploy.0 = Release|ARM64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/drivers/dma/LICENSE.txt b/drivers/dma/LICENSE.txt new file mode 100644 index 0000000..3880e06 --- /dev/null +++ b/drivers/dma/LICENSE.txt @@ -0,0 +1,13 @@ +Copyright 2023 CoolStar + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/drivers/dma/README.md b/drivers/dma/README.md new file mode 100644 index 0000000..7854a95 --- /dev/null +++ b/drivers/dma/README.md @@ -0,0 +1,3 @@ +ARM PL330 Driver + +Tested on RK3588S \ No newline at end of file diff --git a/drivers/dma/pl330dma/bitops.h b/drivers/dma/pl330dma/bitops.h new file mode 100644 index 0000000..5616cd6 --- /dev/null +++ b/drivers/dma/pl330dma/bitops.h @@ -0,0 +1,36 @@ +/** + * __ffs - find first bit in word. + * @word: The word to search + * + * Undefined if no bit exists, so code should check against 0 first. + */ +static unsigned long __ffs(unsigned long word) +{ + int num = 0; + +#if BITS_PER_LONG == 64 + if ((word & 0xffffffff) == 0) { + num += 32; + word >>= 32; + } +#endif + if ((word & 0xffff) == 0) { + num += 16; + word >>= 16; + } + if ((word & 0xff) == 0) { + num += 8; + word >>= 8; + } + if ((word & 0xf) == 0) { + num += 4; + word >>= 4; + } + if ((word & 0x3) == 0) { + num += 2; + word >>= 2; + } + if ((word & 0x1) == 0) + num += 1; + return num; +} \ No newline at end of file diff --git a/drivers/dma/pl330dma/dmacontroller.c b/drivers/dma/pl330dma/dmacontroller.c new file mode 100644 index 0000000..cfd4f06 --- /dev/null +++ b/drivers/dma/pl330dma/dmacontroller.c @@ -0,0 +1,341 @@ +#include "driver.h" + +static ULONG Pl330DmaDebugLevel = 100; +static ULONG Pl330DmaDebugCatagories = DBG_INIT || DBG_PNP || DBG_IOCTL; + +void ReadDmacConfiguration(PPL330DMA_CONTEXT pDevice) { + UINT32 val; + + val = read32(pDevice, CRD) >> CRD_DATA_WIDTH_SHIFT; + val &= CRD_DATA_WIDTH_MASK; + pDevice->Config.DataBusWidth = 8 * (1 << val); + + val = read32(pDevice, CRD) >> CRD_DATA_BUFF_SHIFT; + val &= CRD_DATA_BUFF_MASK; + pDevice->Config.DataBufDepth = val + 1; + + val = read32(pDevice, CRD) >> CR0_NUM_CHANS_SHIFT; + val &= CR0_NUM_CHANS_MASK; + val += 1; + pDevice->Config.NumChan = val; + + val = read32(pDevice, CR0); + if (val & CR0_PERIPH_REQ_SET) { + val = (val >> CR0_NUM_PERIPH_SHIFT) & CR0_NUM_PERIPH_MASK; + val += 1; + pDevice->Config.NumPeripherals = val; + pDevice->Config.PeripheralNS = read32(pDevice, CR4); + } + else { + pDevice->Config.NumPeripherals = 0; + } + + val = read32(pDevice, CR0); + if (val & CR0_BOOT_MAN_NS) + pDevice->Config.Mode |= DMAC_MODE_NS; + else + pDevice->Config.Mode &= ~DMAC_MODE_NS; + + val = read32(pDevice, CR0) >> CR0_NUM_EVENTS_SHIFT; + val &= CR0_NUM_EVENTS_MASK; + val += 1; + pDevice->Config.NumEvents = val; + + pDevice->Config.IrqNS = read32(pDevice, CR3); + + Pl330DmaPrint(DEBUG_LEVEL_INFO, DBG_INIT, + "%s Data Width: %d, Channels: %d\n", __func__, pDevice->Config.DataBusWidth, pDevice->Config.NumChan); +} + +BOOLEAN pl330_dma_irq(WDFINTERRUPT Interrupt, ULONG MessageID) { + UNREFERENCED_PARAMETER(MessageID); + Pl330DmaPrint(DEBUG_LEVEL_INFO, DBG_INIT, + "%s %d\n", __func__, MessageID); + + WDFDEVICE FxDevice = WdfInterruptGetDevice(Interrupt); + PPL330DMA_CONTEXT pDevice = GetDeviceContext(FxDevice); + + UINT32 val = read32(pDevice, FSM) + 0x1; + Pl330DmaPrint(DEBUG_LEVEL_ERROR, DBG_IOCTL, "Reset Manager? %d\n", val); + + val = read32(pDevice, FSC) & ((1 << pDevice->Config.NumChan) - 1); + Pl330DmaPrint(DEBUG_LEVEL_ERROR, DBG_IOCTL, "Reset Channels: %x\n", val); + + BOOLEAN queueDPC = FALSE; + + val = read32(pDevice, ES); + pDevice->irqLastEvents = val; + for (UINT32 ev = 0; ev < pDevice->Config.NumEvents; ev++) { + if (val & (1 << ev)) { /* Event occurred */ + Pl330DmaPrint(DEBUG_LEVEL_ERROR, DBG_IOCTL, "Event on channel %d\n", ev); + + UINT32 intEn = read32(pDevice, INTEN); + if (intEn & (1 << ev)) { + write32(pDevice, INTCLR, (1 << ev)); //Clear the event + + queueDPC = TRUE; + } + } + } + + if (queueDPC) { + WdfInterruptQueueDpcForIsr(Interrupt); + } + + return TRUE; +} + +void pl330_dma_dpc(WDFINTERRUPT Interrupt, WDFOBJECT AssociatedObject) { + UNREFERENCED_PARAMETER(AssociatedObject); + + WDFDEVICE Device = WdfInterruptGetDevice(Interrupt); + PPL330DMA_CONTEXT pDevice = GetDeviceContext(Device); + + UINT32 val = pDevice->irqLastEvents; + for (UINT32 ev = 0; ev < pDevice->Config.NumEvents; ev++) { + if (val & (1 << ev)) { /* Event occurred */ + PPL330DMA_THREAD Thread = &pDevice->Channels[ev]; + for (int regEv = 0; regEv < MAX_NOTIF_EVENTS; regEv++) { + if (Thread->registeredCallbacks[regEv].InUse) { + Thread->registeredCallbacks[regEv].NotificationCallback(Thread->registeredCallbacks[regEv].CallbackContext); + } + } + } + } +} + +/* Returns Time-Out */ +static NTSTATUS UntilDmacIdle(PPL330DMA_THREAD Thread) +{ + PPL330DMA_CONTEXT pDevice = Thread->Device; + UINT32 timeout_us = 5 * 1000; // 5 ms + + LARGE_INTEGER StartTime; + KeQuerySystemTimePrecise(&StartTime); + + for (;;) { + /* Until Manager is Idle */ + if (!(read32(pDevice, DBGSTATUS) & DBG_BUSY)) + return STATUS_SUCCESS; + + __yield(); + + LARGE_INTEGER CurrentTime; + KeQuerySystemTimePrecise(&CurrentTime); + + if (((CurrentTime.QuadPart - StartTime.QuadPart) / 10) > timeout_us) { + return STATUS_IO_TIMEOUT; + } + } +} + +static inline void _execute_DBGINSN( + PPL330DMA_THREAD Thread, + UINT8 insn[], + BOOLEAN AsManager +) { + PPL330DMA_CONTEXT pDevice = Thread->Device; + UINT32 val; + + Pl330DmaPrint(DEBUG_LEVEL_INFO, DBG_INIT, + "%s: entry\n", __func__); + + if (!NT_SUCCESS(UntilDmacIdle(Thread))) { + Pl330DmaPrint(DEBUG_LEVEL_ERROR, DBG_INIT, + "DMAC halted!\n"); + return; + } + + val = (insn[0] << 16) | (insn[1] << 24); + if (!AsManager) { + val |= (1 << 0); + val |= (Thread->Id << 8); /* Channel Number */ + } + write32(pDevice, DBGINST0, val); + + val = *((UINT32*)&insn[2]); + write32(pDevice, DBGINST1, val); + + /* Get going */ + write32(pDevice, DBGCMD, 0); +} + +static inline BOOLEAN IsManager(PPL330DMA_THREAD Thread) +{ + return Thread->Device->Manager == Thread; +} + +/* If manager of the thread is in Non-Secure mode */ +static inline BOOLEAN _manager_ns(PPL330DMA_THREAD Thread) +{ + return (Thread->Device->Config.Mode & DMAC_MODE_NS) ? TRUE : FALSE; +} + +static inline UINT32 GetRevision(UINT32 periph_id) +{ + return (periph_id >> PERIPH_REV_SHIFT) & PERIPH_REV_MASK; +} + +static inline UINT32 _state(PPL330DMA_THREAD Thread) +{ + PPL330DMA_CONTEXT pDevice = Thread->Device; + UINT32 val; + + if (IsManager(Thread)) + val = read32(pDevice, DS) & 0xf; + else + val = read32(pDevice, CS(Thread->Id)) & 0xf; + + switch (val) { + case DS_ST_STOP: + return PL330_STATE_STOPPED; + case DS_ST_EXEC: + return PL330_STATE_EXECUTING; + case DS_ST_CMISS: + return PL330_STATE_CACHEMISS; + case DS_ST_UPDTPC: + return PL330_STATE_UPDTPC; + case DS_ST_WFE: + return PL330_STATE_WFE; + case DS_ST_FAULT: + return PL330_STATE_FAULTING; + case DS_ST_ATBRR: + if (IsManager(Thread)) + return PL330_STATE_INVALID; + else + return PL330_STATE_ATBARRIER; + case DS_ST_QBUSY: + if (IsManager(Thread)) + return PL330_STATE_INVALID; + else + return PL330_STATE_QUEUEBUSY; + case DS_ST_WFP: + if (IsManager(Thread)) + return PL330_STATE_INVALID; + else + return PL330_STATE_WFP; + case DS_ST_KILL: + if (IsManager(Thread)) + return PL330_STATE_INVALID; + else + return PL330_STATE_KILLING; + case DS_ST_CMPLT: + if (IsManager(Thread)) + return PL330_STATE_INVALID; + else + return PL330_STATE_COMPLETING; + case DS_ST_FLTCMP: + if (IsManager(Thread)) + return PL330_STATE_INVALID; + else + return PL330_STATE_FAULT_COMPLETING; + default: + return PL330_STATE_INVALID; + } +} + +void _stop(PPL330DMA_THREAD Thread) +{ + PPL330DMA_CONTEXT pDevice = Thread->Device; + UINT8 insn[6] = { 0, 0, 0, 0, 0, 0 }; + UINT32 inten = read32(pDevice, INTEN); + + if (_state(Thread) == PL330_STATE_FAULT_COMPLETING) + UNTIL(Thread, PL330_STATE_FAULTING | PL330_STATE_KILLING); + + /* Return if nothing needs to be done */ + if (_state(Thread) == PL330_STATE_COMPLETING + || _state(Thread) == PL330_STATE_KILLING + || _state(Thread) == PL330_STATE_STOPPED) + return; + + _emit_KILL(0, insn); + + _execute_DBGINSN(Thread, insn, IsManager(Thread)); + + /* clear the event */ + if (inten & (1 << Thread->ev)) + write32(pDevice, INTCLR, 1 << Thread->ev); + /* Stop generating interrupts for SEV */ + write32(pDevice, INTEN, inten & ~(1 << Thread->ev)); + + Thread->ReqRunning = FALSE; +} + +/* Start doing req 'idx' of thread 'Thread' */ +static BOOLEAN _trigger(PPL330DMA_THREAD Thread) +{ + PPL330DMA_CONTEXT pDevice = Thread->Device; + PPL330DMA_REQ pReq; + struct _arg_GO go; + unsigned ns; + UINT8 insn[6] = { 0, 0, 0, 0, 0, 0 }; + + /* Return if already ACTIVE */ + if (_state(Thread) != PL330_STATE_STOPPED) + return TRUE; + + pReq = &Thread->Req[0]; + + /* Return if req is running */ + if (Thread->ReqRunning) + return TRUE; + + ns = 1; //Always Non-Secure + + /* See 'Abort Sources' point-4 at Page 2-25 */ + if (_manager_ns(Thread) && !ns) + Pl330DmaPrint(DEBUG_LEVEL_INFO, DBG_IOCTL, + "%s:%d Recipe for ABORT!\n", + __func__, __LINE__); + + go.chan = Thread->Id; + go.addr = pReq->MCbus.LowPart; + go.ns = ns; + Pl330DmaPrint(DEBUG_LEVEL_INFO, DBG_IOCTL, + "%s: GO id %d, Addr 0x%x, NS %d\n", __func__, go.chan, go.addr, go.ns); + _emit_GO(0, insn, &go); + + /* Set to generate interrupts for SEV */ + write32(pDevice, INTEN, read32(pDevice, INTEN) | (1 << Thread->ev)); + + /* Only manager can execute GO */ + _execute_DBGINSN(Thread, insn, TRUE); + + Thread->ReqRunning = TRUE; + + return TRUE; +} + +BOOLEAN _start(PPL330DMA_THREAD Thread) +{ + switch (_state(Thread)) { + case PL330_STATE_FAULT_COMPLETING: + UNTIL(Thread, PL330_STATE_FAULTING | PL330_STATE_KILLING); + + if (_state(Thread) == PL330_STATE_KILLING) + UNTIL(Thread, PL330_STATE_STOPPED) + + case PL330_STATE_FAULTING: + _stop(Thread); + + case PL330_STATE_KILLING: + case PL330_STATE_COMPLETING: + UNTIL(Thread, PL330_STATE_STOPPED) + + case PL330_STATE_STOPPED: + return _trigger(Thread); + + case PL330_STATE_WFP: + case PL330_STATE_QUEUEBUSY: + case PL330_STATE_ATBARRIER: + case PL330_STATE_UPDTPC: + case PL330_STATE_CACHEMISS: + case PL330_STATE_EXECUTING: + return TRUE; + + case PL330_STATE_WFE: /* For RESUME, nothing yet */ + default: + return FALSE; + } +} \ No newline at end of file diff --git a/drivers/dma/pl330dma/driver.h b/drivers/dma/pl330dma/driver.h new file mode 100644 index 0000000..2e72d0e --- /dev/null +++ b/drivers/dma/pl330dma/driver.h @@ -0,0 +1,294 @@ +#if !defined(_PL330DMA_H_) +#define _PL330DMA_H_ + +#pragma warning(disable:4200) // suppress nameless struct/union warning +#pragma warning(disable:4201) // suppress nameless struct/union warning +#pragma warning(disable:4214) // suppress bit field types other than int warning +#include +#include +#include +#include + +#pragma warning(default:4200) +#pragma warning(default:4201) +#pragma warning(default:4214) +#include +#include + +#include "bitops.h" +#include "pl330.h" + +// +// String definitions +// + +#define DRIVERNAME "pl330dma.sys: " + +#define PL330DMA_POOL_TAG (ULONG) '033P' +#define PL330DMA_HARDWARE_IDS L"CoolStar\\PL330DMA\0\0" +#define PL330DMA_HARDWARE_IDS_LENGTH sizeof(PL330DMA_HARDWARE_IDS) + +#define SYMBOLIC_NAME_PREFIX L"\\DosDevices\\%hs" + +typedef +void +(*PDMA_NOTIFICATION_CALLBACK)( + PVOID context + ); + +typedef +HANDLE +(*PGET_HANDLE)( + IN PVOID Context, + IN int Idx + ); + +typedef +BOOLEAN +(*PFREE_HANDLE)( + IN PVOID Context, + IN HANDLE Handle + ); + +typedef +VOID +(*PSTOP_DMA)( + IN PVOID Context, + IN HANDLE Handle + ); + +typedef +VOID +(*PGET_THREAD_REGISTERS)( + IN PVOID Context, + IN HANDLE Handle, + OUT UINT32* cpc, + OUT UINT32* sa, + OUT UINT32* da + ); + +typedef +NTSTATUS +(*PSUBMIT_AUDIO_DMA) ( + IN PVOID Context, + IN HANDLE Handle, + IN BOOLEAN fromDevice, + IN UINT32 srcAddr, + IN UINT32 dstAddr, + IN UINT32 len, + IN UINT32 periodLen + ); + +typedef +NTSTATUS +(*PSUBMIT_DMA) ( + IN PVOID Context, + IN HANDLE Handle, + IN BOOLEAN fromDevice, + IN PMDL pMDL, + IN UINT32 dstAddr + ); + +typedef +NTSTATUS +(*PREGISTER_NOTIFICATION_CALLBACK)( + IN PVOID Context, + IN HANDLE Handle, + IN PDEVICE_OBJECT Fdo, + IN PDMA_NOTIFICATION_CALLBACK NotificationCallback, + IN PVOID CallbackContext + ); + +typedef +NTSTATUS +(*PUNREGISTER_NOTIFICATION_CALLBACK)( + IN PVOID Context, + IN HANDLE Handle, + IN PDMA_NOTIFICATION_CALLBACK NotificationCallback, + IN PVOID CallbackContext + ); + +DEFINE_GUID(GUID_PL330DMA_INTERFACE_STANDARD, + 0xdb4b9e2c, 0x7fc6, 0x11ee, 0x95, 0x37, 0x00, 0x15, 0x5d, 0x45, 0x35, 0x74); + +typedef struct _PL330DMA_INTERFACE_STANDARD { + INTERFACE InterfaceHeader; + PGET_HANDLE GetChannel; + PFREE_HANDLE FreeChannel; + PSTOP_DMA StopDMA; + PGET_THREAD_REGISTERS GetThreadRegisters; + PSUBMIT_AUDIO_DMA SubmitAudioDMA; + PSUBMIT_DMA SubmitDMA; //reserved for future use + PREGISTER_NOTIFICATION_CALLBACK RegisterNotificationCallback; + PUNREGISTER_NOTIFICATION_CALLBACK UnregisterNotificationCallback; +} PL330DMA_INTERFACE_STANDARD, * PPL330DMA_INTERFACE_STANDARD; + +typedef struct _PL330DMA_CONFIG { +#define DMAC_MODE_NS (1 << 0) + UINT32 Mode; + UINT32 DataBusWidth : 10; + UINT32 DataBufDepth : 11; + UINT32 NumChan : 4; + UINT32 NumPeripherals : 6; + UINT32 PeripheralNS; + UINT32 NumEvents : 6; + UINT32 IrqNS; +} PL330DMA_CONFIG, *PPL330DMA_CONFIG; + +typedef struct _XFER_SPEC { + UINT32 ccr; + + BOOLEAN involvesDevice; + BOOLEAN toDevice; + UINT8 Peripheral; + + int numPeriods; + + UINT32 srcAddr; + UINT32 dstAddr; + UINT32 periodBytes; +} XFER_SPEC, *PXFER_SPEC; + +typedef struct _PL330DMA_REQ { + PHYSICAL_ADDRESS MCbus; + UINT8* MCcpu; + XFER_SPEC Xfer; +} PL330DMA_REQ, *PPL330DMA_REQ; + +struct _PL330DMA_CONTEXT; + +typedef struct _PL330DMA_THREAD_CALLBACK { + BOOLEAN InUse; + PDEVICE_OBJECT Fdo; + PDMA_NOTIFICATION_CALLBACK NotificationCallback; + PVOID CallbackContext; +} PL330DMA_THREAD_CALLBACK, *PPL330DMA_THREAD_CALLBACK; + +#define MAX_NOTIF_EVENTS 16 + +typedef struct _PL330DMA_THREAD { + UINT8 Id; + int ev; + /* If the channel isn't in use yet */ + BOOLEAN Free; + /* Parent Device */ + struct _PL330DMA_CONTEXT *Device; + /* Only 1 at a time */ + PL330DMA_REQ Req[1]; + + PL330DMA_THREAD_CALLBACK registeredCallbacks[MAX_NOTIF_EVENTS]; + + /* Index of last submitted request (or -1 if stopped) */ + BOOLEAN ReqRunning; +} PL330DMA_THREAD, *PPL330DMA_THREAD; + +typedef struct _PL330DMA_CONTEXT +{ + // + // Handle back to the WDFDEVICE + // + + WDFDEVICE FxDevice; + + PVOID MMIOAddress; + SIZE_T MMIOSize; + WDFINTERRUPT Interrupt; + WDFINTERRUPT Interrupt2; + + PL330DMA_CONFIG Config; + + //Size of MicroCode buffers for each channel + unsigned MCBufSz; + + //CPU address of MicroCode buffer + UINT8 *MCodeCPU; + + //List of all Channel Threads + PPL330DMA_THREAD Channels; + //Pointer to the Manager thread + PPL330DMA_THREAD Manager; + + //Interrupt Context + UINT32 irqLastEvents; +} PL330DMA_CONTEXT, *PPL330DMA_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(PL330DMA_CONTEXT, GetDeviceContext) + +// +// Function definitions +// + +DRIVER_INITIALIZE DriverEntry; + +EVT_WDF_DRIVER_UNLOAD Pl330DmaDriverUnload; + +EVT_WDF_DRIVER_DEVICE_ADD Pl330DmaEvtDeviceAdd; + +EVT_WDF_IO_QUEUE_IO_INTERNAL_DEVICE_CONTROL Pl330DmaEvtInternalDeviceControl; + +EVT_WDF_INTERRUPT_ISR pl330_dma_irq; +EVT_WDF_INTERRUPT_DPC pl330_dma_dpc; + +void udelay(ULONG usec); +UINT32 read32(PPL330DMA_CONTEXT pDevice, UINT32 reg); +void write32(PPL330DMA_CONTEXT pDevice, UINT32 reg, UINT32 val); + +void ReadDmacConfiguration(PPL330DMA_CONTEXT pDevice); +NTSTATUS AllocResources(PPL330DMA_CONTEXT pDevice); +void FreeResources(PPL330DMA_CONTEXT pDevice); + +void _stop(PPL330DMA_THREAD Thread); +BOOLEAN _start(PPL330DMA_THREAD Thread); + +PPL330DMA_THREAD GetHandle(PPL330DMA_CONTEXT pDevice, int Idx); +BOOLEAN FreeHandle(PPL330DMA_CONTEXT pDevice, PPL330DMA_THREAD Thread); +void StopThread(PPL330DMA_CONTEXT pDevice, PPL330DMA_THREAD Thread); +void GetThreadRegisters(PPL330DMA_CONTEXT pDevice, PPL330DMA_THREAD Thread, UINT32* cpc, UINT32* sa, UINT32* da); + +NTSTATUS SubmitAudioDMA( + PPL330DMA_CONTEXT pDevice, + PPL330DMA_THREAD Thread, + BOOLEAN fromDevice, + UINT32 srcAddr, UINT32 dstAddr, + UINT32 len, UINT32 periodLen +); + +NTSTATUS RegisterNotificationCallback( + PPL330DMA_CONTEXT pDevice, + PPL330DMA_THREAD Thread, + PDEVICE_OBJECT Fdo, + PDMA_NOTIFICATION_CALLBACK NotificationCallback, + PVOID CallbackContext); + +NTSTATUS UnregisterNotificationCallback( + PPL330DMA_CONTEXT pDevice, + PPL330DMA_THREAD Thread, + PDMA_NOTIFICATION_CALLBACK NotificationCallback, + PVOID CallbackContext); + +// +// Helper macros +// + +#define DEBUG_LEVEL_ERROR 1 +#define DEBUG_LEVEL_INFO 2 +#define DEBUG_LEVEL_VERBOSE 3 + +#define DBG_INIT 1 +#define DBG_PNP 2 +#define DBG_IOCTL 4 + +#if 0 +#define Pl330DmaPrint(dbglevel, dbgcatagory, fmt, ...) { \ + if (Pl330DmaDebugLevel >= dbglevel && \ + (Pl330DmaDebugCatagories && dbgcatagory)) \ + { \ + DbgPrint(DRIVERNAME); \ + DbgPrint(fmt, __VA_ARGS__); \ + } \ +} +#else +#define Pl330DmaPrint(dbglevel, fmt, ...) { \ +} +#endif +#endif \ No newline at end of file diff --git a/drivers/dma/pl330dma/insn.c b/drivers/dma/pl330dma/insn.c new file mode 100644 index 0000000..a442154 --- /dev/null +++ b/drivers/dma/pl330dma/insn.c @@ -0,0 +1,301 @@ +#include "driver.h" + +static int _ldst_memtomem(BOOLEAN dryRun, UINT8 buf[], int cyc) +{ + int off = 0; + + while (cyc--) { + off += _emit_LD(dryRun, &buf[off], ALWAYS); + off += _emit_ST(dryRun, &buf[off], ALWAYS); + } + + return off; +} + +static UINT32 _emit_load(BOOLEAN dryRun, UINT8 buf[], + enum pl330_cond cond, PXFER_SPEC pxs) +{ + int off = 0; + + if (!pxs->involvesDevice || (pxs->involvesDevice && pxs->toDevice)) { + off += _emit_LD(dryRun, &buf[off], cond); + } + else { + if (cond == ALWAYS) { + off += _emit_LDP(dryRun, &buf[off], SINGLE, + pxs->Peripheral); + off += _emit_LDP(dryRun, &buf[off], BURST, + pxs->Peripheral); + } + else { + off += _emit_LDP(dryRun, &buf[off], cond, + pxs->Peripheral); + } + } + + return off; +} + +static UINT32 _emit_store(BOOLEAN dryRun, UINT8 buf[], + enum pl330_cond cond, PXFER_SPEC pxs) +{ + int off = 0; + + if (!pxs->involvesDevice || (pxs->involvesDevice && !pxs->toDevice)) { + off += _emit_ST(dryRun, &buf[off], cond); + } + else { + if (cond == ALWAYS) { + off += _emit_STP(dryRun, &buf[off], SINGLE, + pxs->Peripheral); + off += _emit_STP(dryRun, &buf[off], BURST, + pxs->Peripheral); + } + else { + off += _emit_STP(dryRun, &buf[off], cond, + pxs->Peripheral); + } + } + + return off; +} + +static inline int _ldst_peripheral(BOOLEAN dryRun, UINT8 buf[], + PXFER_SPEC pxs, int cyc, + enum pl330_cond cond) +{ + int off = 0; + + /* + * do FLUSHP at beginning to clear any stale dma requests before the + * first WFP. + */ + off += _emit_FLUSHP(dryRun, &buf[off], pxs->Peripheral); + + while (cyc--) { + off += _emit_WFP(dryRun, &buf[off], cond, pxs->Peripheral); + off += _emit_load(dryRun, &buf[off], cond, pxs); + off += _emit_store(dryRun, &buf[off], cond, pxs); + } + + return off; +} + +static int _bursts(BOOLEAN dryRun, UINT8 buf[], PXFER_SPEC pxs, int cyc) { + int off = 0; + enum pl330_cond cond = BURST; + + if (pxs->involvesDevice) { + off += _ldst_peripheral(dryRun, &buf[off], pxs, cyc, + cond); + } + else { + off += _ldst_memtomem(dryRun, &buf[off], cyc); + } + return off; +} + +/* + * only the unaligned bursts transfers have the dregs. + * transfer dregs with a reduced size burst to peripheral, + * or a reduced size burst for mem-to-mem. + */ +static int _dregs(BOOLEAN dryRun, UINT8 buf[], + PXFER_SPEC pxs, int transfer_length) +{ + int off = 0; + int dregs_ccr; + + if (transfer_length == 0) + return off; + + if (pxs->involvesDevice) { + /* + * dregs_len = (total bytes - BURST_TO_BYTE(bursts, ccr)) / + * BRST_SIZE(ccr) + * the dregs len must be smaller than burst len, + * so, for higher efficiency, we can modify CCR + * to use a reduced size burst len for the dregs. + */ + dregs_ccr = pxs->ccr; + dregs_ccr &= ~((0xf << CC_SRCBRSTLEN_SHFT) | + (0xf << CC_DSTBRSTLEN_SHFT)); + dregs_ccr |= (((transfer_length - 1) & 0xf) << + CC_SRCBRSTLEN_SHFT); + dregs_ccr |= (((transfer_length - 1) & 0xf) << + CC_DSTBRSTLEN_SHFT); + off += _emit_MOV(dryRun, &buf[off], CCR, dregs_ccr); + off += _ldst_peripheral(dryRun, &buf[off], pxs, 1, + BURST); + } + else { + dregs_ccr = pxs->ccr; + dregs_ccr &= ~((0xf << CC_SRCBRSTLEN_SHFT) | + (0xf << CC_DSTBRSTLEN_SHFT)); + dregs_ccr |= (((transfer_length - 1) & 0xf) << + CC_SRCBRSTLEN_SHFT); + dregs_ccr |= (((transfer_length - 1) & 0xf) << + CC_DSTBRSTLEN_SHFT); + off += _emit_MOV(dryRun, &buf[off], CCR, dregs_ccr); + + off += _ldst_memtomem(dryRun, &buf[off], 1); + } + + return off; +} + +static int _period(BOOLEAN dryRun, UINT8 buf[], + PXFER_SPEC pxs, unsigned long bursts, int ev) +{ + unsigned int lcnt1, ljmp1; + int cyc, off = 0, num_dregs = 0; + struct _arg_LPEND lpend; + + if (bursts > 256) { + lcnt1 = 256; + cyc = bursts / 256; + } + else { + lcnt1 = bursts; + cyc = 1; + } + + /* loop1 */ + off += _emit_LP(dryRun, &buf[off], 1, lcnt1); + ljmp1 = off; + off += _bursts(dryRun, &buf[off], pxs, cyc); + lpend.cond = ALWAYS; + lpend.forever = FALSE; + lpend.loop = 1; + lpend.bjump = off - ljmp1; + off += _emit_LPEND(dryRun, &buf[off], &lpend); + + /* remainder */ + lcnt1 = bursts - (lcnt1 * cyc); + + if (lcnt1) { + off += _emit_LP(dryRun, &buf[off], 1, lcnt1); + ljmp1 = off; + off += _bursts(dryRun, &buf[off], pxs, 1); + lpend.cond = ALWAYS; + lpend.forever = FALSE; + lpend.loop = 1; + lpend.bjump = off - ljmp1; + off += _emit_LPEND(dryRun, &buf[off], &lpend); + } + + num_dregs = BYTE_MOD_BURST_LEN(pxs->periodBytes, pxs->ccr); + + if (num_dregs) { + off += _dregs(dryRun, &buf[off], pxs, num_dregs); + off += _emit_MOV(dryRun, &buf[off], CCR, pxs->ccr); + } + + off += _emit_SEV(dryRun, &buf[off], ev); + + return off; +} + +static int _loop_cyclic(BOOLEAN dryRun, + UINT8 buf[], unsigned long bursts, + PXFER_SPEC pxs, int ev) +{ + int off, periods, residue, i; + unsigned int lcnt0, ljmp0, ljmpfe; + struct _arg_LPEND lpend; + + off = 0; + ljmpfe = off; + lcnt0 = pxs->numPeriods; + periods = 1; + + while (lcnt0 > 256) { + periods++; + lcnt0 = pxs->numPeriods / periods; + } + + residue = pxs->numPeriods % periods; + + /* forever loop */ + off += _emit_MOV(dryRun, &buf[off], SAR, pxs->srcAddr); + off += _emit_MOV(dryRun, &buf[off], DAR, pxs->dstAddr); + + /* loop0 */ + off += _emit_LP(dryRun, &buf[off], 0, lcnt0); + ljmp0 = off; + + for (i = 0; i < periods; i++) + off += _period(dryRun, &buf[off], pxs, bursts, ev); + + lpend.cond = ALWAYS; + lpend.forever = FALSE; + lpend.loop = 0; + lpend.bjump = off - ljmp0; + off += _emit_LPEND(dryRun, &buf[off], &lpend); + + for (i = 0; i < residue; i++) + off += _period(dryRun, &buf[off], pxs, bursts, ev); + + lpend.cond = ALWAYS; + lpend.forever = TRUE; + lpend.loop = 1; + lpend.bjump = off - ljmpfe; + off += _emit_LPEND(dryRun, &buf[off], &lpend); + + return off; +} + +NTSTATUS SubmitAudioDMA( + PPL330DMA_CONTEXT pDevice, + PPL330DMA_THREAD Thread, + BOOLEAN fromDevice, + UINT32 srcAddr, UINT32 dstAddr, + UINT32 len, UINT32 periodLen +) { + UINT32 ccr = fromDevice ? CC_DSTINC : CC_SRCINC; + + ccr |= CC_SRCNS | CC_DSTNS; + + UINT32 addrWidth = 4; + UINT32 maxBurst = 8; + + //port width + ccr |= ((maxBurst - 1) << CC_SRCBRSTLEN_SHFT); + ccr |= ((maxBurst - 1) << CC_DSTBRSTLEN_SHFT); + + UINT32 burstSz = __ffs(addrWidth); //bus width = 4 bytes + ccr |= (burstSz << CC_SRCBRSTSIZE_SHFT); + ccr |= (burstSz << CC_DSTBRSTSIZE_SHFT); + ccr |= (CCTRL0 << CC_SRCCCTRL_SHFT); + ccr |= (CCTRL0 << CC_DSTCCTRL_SHFT); + ccr |= (SWAP_NO << CC_SWAP_SHFT); + + PL330_DBGMC_START(Thread->Req[0].MCbus.LowPart); + + UINT8* buf = Thread->Req[0].MCcpu; + + //DMAMOV CCR, ccr + int off = 0; + off += _emit_MOV(FALSE, &buf[off], CCR, ccr); + + XFER_SPEC pxs = { 0 }; + pxs.ccr = ccr; + pxs.involvesDevice = TRUE; + pxs.toDevice = !fromDevice; + pxs.Peripheral = Thread->Id; + + pxs.numPeriods = len / periodLen; + pxs.srcAddr = srcAddr; + pxs.dstAddr = dstAddr; + pxs.periodBytes = periodLen; + + Thread->Req[0].Xfer = pxs; + + UINT32 bursts = BYTE_TO_BURST(periodLen, ccr); + off += _loop_cyclic(FALSE, &buf[off], bursts, &pxs, Thread->Id); + + BOOLEAN started = _start(Thread); + if (started) + return STATUS_SUCCESS; + return STATUS_UNSUCCESSFUL; +} \ No newline at end of file diff --git a/drivers/dma/pl330dma/opcodes.h b/drivers/dma/pl330dma/opcodes.h new file mode 100644 index 0000000..0477af3 --- /dev/null +++ b/drivers/dma/pl330dma/opcodes.h @@ -0,0 +1,302 @@ +static inline UINT32 _emit_ADDH(unsigned dry_run, UINT8 buf[], + enum pl330_dst da, UINT16 val) { + if (dry_run) + return SZ_DMAADDH; + + buf[0] = CMD_DMAADDH; + buf[0] |= (da << 1); + *((UINT16*)&buf[1]) = val; + + PL330_DBGCMD_DUMP(SZ_DMAADDH, "\tDMAADDH %s %u\n", + da == 1 ? "DA" : "SA", val); + + return SZ_DMAADDH; +} + +static inline UINT32 _emit_END(unsigned dry_run, UINT8 buf[]) +{ + if (dry_run) + return SZ_DMAEND; + + buf[0] = CMD_DMAEND; + + PL330_DBGCMD_DUMP(SZ_DMAEND, "\tDMAEND\n"); + + return SZ_DMAEND; +} + +static inline UINT32 _emit_FLUSHP(unsigned dry_run, UINT8 buf[], UINT8 peri) +{ + if (dry_run) + return SZ_DMAFLUSHP; + + buf[0] = CMD_DMAFLUSHP; + + peri &= 0x1f; + peri <<= 3; + buf[1] = peri; + + PL330_DBGCMD_DUMP(SZ_DMAFLUSHP, "\tDMAFLUSHP %u\n", peri >> 3); + + return SZ_DMAFLUSHP; +} + +static inline UINT32 _emit_LD(unsigned dry_run, UINT8 buf[], enum pl330_cond cond) +{ + if (dry_run) + return SZ_DMALD; + + buf[0] = CMD_DMALD; + + if (cond == SINGLE) + buf[0] |= (0 << 1) | (1 << 0); + else if (cond == BURST) + buf[0] |= (1 << 1) | (1 << 0); + + PL330_DBGCMD_DUMP(SZ_DMALD, "\tDMALD%c\n", + cond == SINGLE ? 'S' : (cond == BURST ? 'B' : 'A')); + + return SZ_DMALD; +} + +static inline UINT32 _emit_LDP(unsigned dry_run, UINT8 buf[], + enum pl330_cond cond, UINT8 peri) +{ + if (dry_run) + return SZ_DMALDP; + + buf[0] = CMD_DMALDP; + + if (cond == BURST) + buf[0] |= (1 << 1); + + peri &= 0x1f; + peri <<= 3; + buf[1] = peri; + + PL330_DBGCMD_DUMP(SZ_DMALDP, "\tDMALDP%c %u\n", + cond == SINGLE ? 'S' : 'B', peri >> 3); + + return SZ_DMALDP; +} + +static inline UINT32 _emit_LP(unsigned dry_run, UINT8 buf[], + unsigned loop, UINT8 cnt) +{ + if (dry_run) + return SZ_DMALP; + + buf[0] = CMD_DMALP; + + if (loop) + buf[0] |= (1 << 1); + + cnt--; /* DMAC increments by 1 internally */ + buf[1] = cnt; + + PL330_DBGCMD_DUMP(SZ_DMALP, "\tDMALP_%c %u\n", loop ? '1' : '0', cnt); + + return SZ_DMALP; +} + +struct _arg_LPEND { + enum pl330_cond cond; + BOOLEAN forever; + unsigned loop; + UINT8 bjump; +}; + +static inline UINT32 _emit_LPEND(unsigned dry_run, UINT8 buf[], + const struct _arg_LPEND* arg) +{ + enum pl330_cond cond = arg->cond; + BOOLEAN forever = arg->forever; + unsigned loop = arg->loop; + UINT8 bjump = arg->bjump; + + if (dry_run) + return SZ_DMALPEND; + + buf[0] = CMD_DMALPEND; + + if (loop) + buf[0] |= (1 << 2); + + if (!forever) + buf[0] |= (1 << 4); + + if (cond == SINGLE) + buf[0] |= (0 << 1) | (1 << 0); + else if (cond == BURST) + buf[0] |= (1 << 1) | (1 << 0); + + buf[1] = bjump; + + PL330_DBGCMD_DUMP(SZ_DMALPEND, "\tDMALP%s%c_%c bjmpto_%x\n", + forever ? "FE" : "END", + cond == SINGLE ? 'S' : (cond == BURST ? 'B' : 'A'), + loop ? '1' : '0', + bjump); + + return SZ_DMALPEND; +} + +static inline UINT32 _emit_KILL(unsigned dry_run, UINT8 buf[]) +{ + if (dry_run) + return SZ_DMAKILL; + + buf[0] = CMD_DMAKILL; + + return SZ_DMAKILL; +} + +static inline UINT32 _emit_MOV(unsigned dry_run, UINT8 buf[], + enum dmamov_dst dst, UINT32 val) +{ + if (dry_run) + return SZ_DMAMOV; + + buf[0] = CMD_DMAMOV; + buf[1] = dst; + buf[2] = val & 0xff; + buf[3] = (val >> 8) & 0xff; + buf[4] = (val >> 16) & 0xff; + buf[5] = (val >> 24) & 0xff; + + PL330_DBGCMD_DUMP(SZ_DMAMOV, "\tDMAMOV %s 0x%x\n", + dst == SAR ? "SAR" : (dst == DAR ? "DAR" : "CCR"), val); + + return SZ_DMAMOV; +} + +static inline UINT32 _emit_RMB(unsigned dry_run, UINT8 buf[]) +{ + if (dry_run) + return SZ_DMARMB; + + buf[0] = CMD_DMARMB; + + PL330_DBGCMD_DUMP(SZ_DMARMB, "\tDMARMB\n"); + + return SZ_DMARMB; +} + +static inline UINT32 _emit_SEV(unsigned dry_run, UINT8 buf[], UINT8 ev) +{ + if (dry_run) + return SZ_DMASEV; + + buf[0] = CMD_DMASEV; + + ev &= 0x1f; + ev <<= 3; + buf[1] = ev; + + PL330_DBGCMD_DUMP(SZ_DMASEV, "\tDMASEV %u\n", ev >> 3); + + return SZ_DMASEV; +} + +static inline UINT32 _emit_ST(unsigned dry_run, UINT8 buf[], enum pl330_cond cond) +{ + if (dry_run) + return SZ_DMAST; + + buf[0] = CMD_DMAST; + + if (cond == SINGLE) + buf[0] |= (0 << 1) | (1 << 0); + else if (cond == BURST) + buf[0] |= (1 << 1) | (1 << 0); + + PL330_DBGCMD_DUMP(SZ_DMAST, "\tDMAST%c\n", + cond == SINGLE ? 'S' : (cond == BURST ? 'B' : 'A')); + + return SZ_DMAST; +} + +static inline UINT32 _emit_STP(unsigned dry_run, UINT8 buf[], + enum pl330_cond cond, UINT8 peri) +{ + if (dry_run) + return SZ_DMASTP; + + buf[0] = CMD_DMASTP; + + if (cond == BURST) + buf[0] |= (1 << 1); + + peri &= 0x1f; + peri <<= 3; + buf[1] = peri; + + PL330_DBGCMD_DUMP(SZ_DMASTP, "\tDMASTP%c %u\n", + cond == SINGLE ? 'S' : 'B', peri >> 3); + + return SZ_DMASTP; +} + +static inline UINT32 _emit_WFP(unsigned dry_run, UINT8 buf[], + enum pl330_cond cond, UINT8 peri) +{ + if (dry_run) + return SZ_DMAWFP; + + buf[0] = CMD_DMAWFP; + + if (cond == SINGLE) + buf[0] |= (0 << 1) | (0 << 0); + else if (cond == BURST) + buf[0] |= (1 << 1) | (0 << 0); + else + buf[0] |= (0 << 1) | (1 << 0); + + peri &= 0x1f; + peri <<= 3; + buf[1] = peri; + + PL330_DBGCMD_DUMP(SZ_DMAWFP, "\tDMAWFP%c %u\n", + cond == SINGLE ? 'S' : (cond == BURST ? 'B' : 'P'), peri >> 3); + + return SZ_DMAWFP; +} + +static inline UINT32 _emit_WMB(unsigned dry_run, UINT8 buf[]) +{ + if (dry_run) + return SZ_DMAWMB; + + buf[0] = CMD_DMAWMB; + + PL330_DBGCMD_DUMP(SZ_DMAWMB, "\tDMAWMB\n"); + + return SZ_DMAWMB; +} + +struct _arg_GO { + UINT8 chan; + UINT32 addr; + unsigned ns; +}; + +static inline UINT32 _emit_GO(unsigned dry_run, UINT8 buf[], + const struct _arg_GO* arg) +{ + UINT8 chan = arg->chan; + UINT32 addr = arg->addr; + unsigned ns = arg->ns; + + if (dry_run) + return SZ_DMAGO; + + buf[0] = CMD_DMAGO; + buf[0] |= (ns << 1); + buf[1] = chan & 0x7; + buf[2] = addr & 0xff; + buf[3] = (addr >> 8) & 0xff; + buf[4] = (addr >> 16) & 0xff; + buf[5] = (addr >> 24) & 0xff; + + return SZ_DMAGO; +} \ No newline at end of file diff --git a/drivers/dma/pl330dma/pl330.c b/drivers/dma/pl330dma/pl330.c new file mode 100644 index 0000000..42773f8 --- /dev/null +++ b/drivers/dma/pl330dma/pl330.c @@ -0,0 +1,502 @@ +#include "driver.h" +#include "stdint.h" + +#define bool int +#define MS_IN_US 1000 + +static ULONG Pl330DmaDebugLevel = 100; +static ULONG Pl330DmaDebugCatagories = DBG_INIT || DBG_PNP || DBG_IOCTL; + +void udelay(ULONG usec) { + LARGE_INTEGER Interval; + Interval.QuadPart = -10 * (LONGLONG)usec; + KeDelayExecutionThread(KernelMode, FALSE, &Interval); +} + +UINT32 read32(PPL330DMA_CONTEXT pDevice, UINT32 reg) +{ + return *(UINT32 *)((CHAR *)pDevice->MMIOAddress + reg); +} + +void write32(PPL330DMA_CONTEXT pDevice, UINT32 reg, UINT32 val) { + *(UINT32 *)((CHAR *)pDevice->MMIOAddress + reg) = val; +} + +NTSTATUS +DriverEntry( +__in PDRIVER_OBJECT DriverObject, +__in PUNICODE_STRING RegistryPath +) +{ + NTSTATUS status = STATUS_SUCCESS; + WDF_DRIVER_CONFIG config; + WDF_OBJECT_ATTRIBUTES attributes; + + Pl330DmaPrint(DEBUG_LEVEL_INFO, DBG_INIT, + "Driver Entry\n"); + + WDF_DRIVER_CONFIG_INIT(&config, Pl330DmaEvtDeviceAdd); + + WDF_OBJECT_ATTRIBUTES_INIT(&attributes); + + // + // Create a framework driver object to represent our driver. + // + + status = WdfDriverCreate(DriverObject, + RegistryPath, + &attributes, + &config, + WDF_NO_HANDLE + ); + + if (!NT_SUCCESS(status)) + { + Pl330DmaPrint(DEBUG_LEVEL_ERROR, DBG_INIT, + "WdfDriverCreate failed with status 0x%x\n", status); + } + + return status; +} + +static NTSTATUS GetStringProperty( + _In_ WDFDEVICE FxDevice, + char* propertyStr, + char* property, + UINT32 propertyLen +) { + WDFMEMORY outputMemory = WDF_NO_HANDLE; + + NTSTATUS status = STATUS_ACPI_NOT_INITIALIZED; + + size_t inputBufferLen = sizeof(ACPI_GET_DEVICE_SPECIFIC_DATA) + strlen(propertyStr) + 1; + ACPI_GET_DEVICE_SPECIFIC_DATA* inputBuffer = ExAllocatePoolZero(NonPagedPool, inputBufferLen, PL330DMA_POOL_TAG); + if (!inputBuffer) { + goto Exit; + } + RtlZeroMemory(inputBuffer, inputBufferLen); + + inputBuffer->Signature = IOCTL_ACPI_GET_DEVICE_SPECIFIC_DATA_SIGNATURE; + + unsigned char uuidend[] = { 0x8a, 0x91, 0xbc, 0x9b, 0xbf, 0x4a, 0xa3, 0x01 }; + + inputBuffer->Section.Data1 = 0xdaffd814; + inputBuffer->Section.Data2 = 0x6eba; + inputBuffer->Section.Data3 = 0x4d8c; + memcpy(inputBuffer->Section.Data4, uuidend, sizeof(uuidend)); //Avoid Windows defender false positive + + strcpy(inputBuffer->PropertyName, propertyStr); + inputBuffer->PropertyNameLength = strlen(propertyStr) + 1; + + PACPI_EVAL_OUTPUT_BUFFER outputBuffer; + size_t outputBufferSize = FIELD_OFFSET(ACPI_EVAL_OUTPUT_BUFFER, Argument) + sizeof(ACPI_METHOD_ARGUMENT_V1) + propertyLen; + + WDF_OBJECT_ATTRIBUTES attributes; + WDF_OBJECT_ATTRIBUTES_INIT(&attributes); + attributes.ParentObject = FxDevice; + status = WdfMemoryCreate(&attributes, + NonPagedPoolNx, + 0, + outputBufferSize, + &outputMemory, + &outputBuffer); + if (!NT_SUCCESS(status)) { + goto Exit; + } + + WDF_MEMORY_DESCRIPTOR inputMemDesc; + WDF_MEMORY_DESCRIPTOR outputMemDesc; + WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&inputMemDesc, inputBuffer, (ULONG)inputBufferLen); + WDF_MEMORY_DESCRIPTOR_INIT_HANDLE(&outputMemDesc, outputMemory, NULL); + + status = WdfIoTargetSendInternalIoctlSynchronously( + WdfDeviceGetIoTarget(FxDevice), + NULL, + IOCTL_ACPI_GET_DEVICE_SPECIFIC_DATA, + &inputMemDesc, + &outputMemDesc, + NULL, + NULL + ); + if (!NT_SUCCESS(status)) { + Pl330DmaPrint( + DEBUG_LEVEL_ERROR, + DBG_IOCTL, + "Error getting device data - 0x%x\n", + status); + goto Exit; + } + + if (outputBuffer->Signature != ACPI_EVAL_OUTPUT_BUFFER_SIGNATURE_V1 && + outputBuffer->Count < 1 && + outputBuffer->Argument->Type != ACPI_METHOD_ARGUMENT_INTEGER && + outputBuffer->Argument->DataLength < 1) { + status = STATUS_ACPI_INVALID_ARGUMENT; + goto Exit; + } + + if (property) { + RtlZeroMemory(property, propertyLen); + RtlCopyMemory(property, outputBuffer->Argument->Data, min(propertyLen, outputBuffer->Argument->DataLength)); + } + +Exit: + if (inputBuffer) { + ExFreePoolWithTag(inputBuffer, PL330DMA_POOL_TAG); + } + if (outputMemory != WDF_NO_HANDLE) { + WdfObjectDelete(outputMemory); + } + return status; +} + +NTSTATUS +OnPrepareHardware( +_In_ WDFDEVICE FxDevice, +_In_ WDFCMRESLIST FxResourcesRaw, +_In_ WDFCMRESLIST FxResourcesTranslated +) +/*++ + +Routine Description: + +This routine caches the SPB resource connection ID. + +Arguments: + +FxDevice - a handle to the framework device object +FxResourcesRaw - list of translated hardware resources that +the PnP manager has assigned to the device +FxResourcesTranslated - list of raw hardware resources that +the PnP manager has assigned to the device + +Return Value: + +Status + +--*/ +{ + PPL330DMA_CONTEXT pDevice = GetDeviceContext(FxDevice); + NTSTATUS status = STATUS_INSUFFICIENT_RESOURCES; + ULONG resourceCount; + BOOLEAN mmioFound; + + UNREFERENCED_PARAMETER(FxResourcesRaw); + + resourceCount = WdfCmResourceListGetCount(FxResourcesTranslated); + mmioFound = FALSE; + + Pl330DmaPrint(DEBUG_LEVEL_INFO, DBG_INIT, + "%s\n", __func__); + + for (ULONG i = 0; i < resourceCount; i++) + { + PCM_PARTIAL_RESOURCE_DESCRIPTOR pDescriptor; + + pDescriptor = WdfCmResourceListGetDescriptor( + FxResourcesTranslated, i); + + switch (pDescriptor->Type) + { + case CmResourceTypeMemory: + if (!mmioFound) { + pDevice->MMIOAddress = MmMapIoSpace(pDescriptor->u.Memory.Start, pDescriptor->u.Memory.Length, MmNonCached); + pDevice->MMIOSize = pDescriptor->u.Memory.Length; + + mmioFound = TRUE; + } + break; + } + } + + if (!pDevice->MMIOAddress || !mmioFound) { + status = STATUS_NOT_FOUND; //MMIO is required + return status; + } + + ReadDmacConfiguration(pDevice); + + status = AllocResources(pDevice); + + if (!NT_SUCCESS(status)) { + return status; + } + + return status; +} + +NTSTATUS +OnReleaseHardware( +_In_ WDFDEVICE FxDevice, +_In_ WDFCMRESLIST FxResourcesTranslated +) +/*++ + +Routine Description: + +Arguments: + +FxDevice - a handle to the framework device object +FxResourcesTranslated - list of raw hardware resources that +the PnP manager has assigned to the device + +Return Value: + +Status + +--*/ +{ + NTSTATUS status = STATUS_SUCCESS; + + UNREFERENCED_PARAMETER(FxResourcesTranslated); + + PPL330DMA_CONTEXT pDevice = GetDeviceContext(FxDevice); + + FreeResources(pDevice); + + if (pDevice->MMIOAddress) { + MmUnmapIoSpace(pDevice->MMIOAddress, pDevice->MMIOSize); + } + + return status; +} + +NTSTATUS +OnD0Entry( +_In_ WDFDEVICE FxDevice, +_In_ WDF_POWER_DEVICE_STATE FxPreviousState +) +/*++ + +Routine Description: + +This routine allocates objects needed by the driver. + +Arguments: + +FxDevice - a handle to the framework device object +FxPreviousState - previous power state + +Return Value: + +Status + +--*/ +{ + UNREFERENCED_PARAMETER(FxDevice); + UNREFERENCED_PARAMETER(FxPreviousState); + + return STATUS_SUCCESS; +} + +NTSTATUS +OnD0Exit( +_In_ WDFDEVICE FxDevice, +_In_ WDF_POWER_DEVICE_STATE FxTargetState +) +/*++ + +Routine Description: + +This routine destroys objects needed by the driver. + +Arguments: + +FxDevice - a handle to the framework device object +FxTargetState - target power state + +Return Value: + +Status + +--*/ +{ + UNREFERENCED_PARAMETER(FxDevice); + UNREFERENCED_PARAMETER(FxTargetState); + return STATUS_SUCCESS; +} + +NTSTATUS +Pl330DmaEvtDeviceAdd( +IN WDFDRIVER Driver, +IN PWDFDEVICE_INIT DeviceInit +) +{ + NTSTATUS status = STATUS_SUCCESS; + WDF_OBJECT_ATTRIBUTES attributes; + WDFDEVICE device; + PPL330DMA_CONTEXT devContext; + WDF_QUERY_INTERFACE_CONFIG qiConfig; + WDF_INTERRUPT_CONFIG interruptConfig; + + UNREFERENCED_PARAMETER(Driver); + + PAGED_CODE(); + + Pl330DmaPrint(DEBUG_LEVEL_INFO, DBG_PNP, + "Pl330DmaEvtDeviceAdd called\n"); + + { + WDF_PNPPOWER_EVENT_CALLBACKS pnpCallbacks; + WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&pnpCallbacks); + + pnpCallbacks.EvtDevicePrepareHardware = OnPrepareHardware; + pnpCallbacks.EvtDeviceReleaseHardware = OnReleaseHardware; + pnpCallbacks.EvtDeviceD0Entry = OnD0Entry; + pnpCallbacks.EvtDeviceD0Exit = OnD0Exit; + + WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &pnpCallbacks); + } + + // + // Setup the device context + // + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, PL330DMA_CONTEXT); + + // Set DeviceType + WdfDeviceInitSetDeviceType(DeviceInit, FILE_DEVICE_CONTROLLER); + + // + // Create a framework device object.This call will in turn create + // a WDM device object, attach to the lower stack, and set the + // appropriate flags and attributes. + // + + status = WdfDeviceCreate(&DeviceInit, &attributes, &device); + + if (!NT_SUCCESS(status)) + { + Pl330DmaPrint(DEBUG_LEVEL_ERROR, DBG_PNP, + "WdfDeviceCreate failed with status code 0x%x\n", status); + + return status; + } + + { + WDF_DEVICE_STATE deviceState; + WDF_DEVICE_STATE_INIT(&deviceState); + + deviceState.NotDisableable = WdfFalse; + WdfDeviceSetDeviceState(device, &deviceState); + } + + devContext = GetDeviceContext(device); + + devContext->FxDevice = device; + + // + // Create an interrupt object for hardware notifications + // + WDF_INTERRUPT_CONFIG_INIT( + &interruptConfig, + pl330_dma_irq, + pl330_dma_dpc); + + status = WdfInterruptCreate( + device, + &interruptConfig, + WDF_NO_OBJECT_ATTRIBUTES, + &devContext->Interrupt); + + if (!NT_SUCCESS(status)) + { + Pl330DmaPrint(DEBUG_LEVEL_ERROR, DBG_PNP, + "Error creating WDF interrupt object - %!STATUS!", + status); + + return status; + } + + // + // Create a second interrupt object for hardware notifications + // + WDF_INTERRUPT_CONFIG_INIT( + &interruptConfig, + pl330_dma_irq, + NULL); + + status = WdfInterruptCreate( + device, + &interruptConfig, + WDF_NO_OBJECT_ATTRIBUTES, + &devContext->Interrupt2); + + if (!NT_SUCCESS(status)) + { + Pl330DmaPrint(DEBUG_LEVEL_ERROR, DBG_PNP, + "Error creating WDF interrupt object 2 - %!STATUS!", + status); + + return status; + } + + char dmaName[10]; + status = GetStringProperty(device, "ctlrName", dmaName, sizeof(dmaName)); + if (!NT_SUCCESS(status)) + { + Pl330DmaPrint(DEBUG_LEVEL_ERROR, DBG_PNP, + "Error getting ctlrName - %!STATUS!", + status); + + return status; + } + + DECLARE_UNICODE_STRING_SIZE(dosDeviceName, 25); + status = RtlUnicodeStringPrintf(&dosDeviceName, SYMBOLIC_NAME_PREFIX, dmaName); + if (!NT_SUCCESS(status)) { + Pl330DmaPrint(DEBUG_LEVEL_ERROR, DBG_PNP, + "Error building symbolic link name - %!STATUS!", + status); + + return status; + } + + status = WdfDeviceCreateSymbolicLink(device, + &dosDeviceName + ); + if (!NT_SUCCESS(status)) { + Pl330DmaPrint(DEBUG_LEVEL_ERROR, DBG_PNP, + "WdfDeviceCreateSymbolicLink failed 0x%x\n", status); + return status; + } + + { // V1 + PL330DMA_INTERFACE_STANDARD Pl330DMAInterface; + RtlZeroMemory(&Pl330DMAInterface, sizeof(Pl330DMAInterface)); + + Pl330DMAInterface.InterfaceHeader.Size = sizeof(Pl330DMAInterface); + Pl330DMAInterface.InterfaceHeader.Version = 1; + Pl330DMAInterface.InterfaceHeader.Context = (PVOID)devContext; + + // + // Let the framework handle reference counting. + // + Pl330DMAInterface.InterfaceHeader.InterfaceReference = WdfDeviceInterfaceReferenceNoOp; + Pl330DMAInterface.InterfaceHeader.InterfaceDereference = WdfDeviceInterfaceDereferenceNoOp; + + Pl330DMAInterface.GetChannel = GetHandle; + Pl330DMAInterface.FreeChannel = FreeHandle; + Pl330DMAInterface.StopDMA = StopThread; + Pl330DMAInterface.GetThreadRegisters = GetThreadRegisters; + Pl330DMAInterface.SubmitAudioDMA = SubmitAudioDMA; + + Pl330DMAInterface.RegisterNotificationCallback = RegisterNotificationCallback; + Pl330DMAInterface.UnregisterNotificationCallback = UnregisterNotificationCallback; + + WDF_QUERY_INTERFACE_CONFIG_INIT(&qiConfig, + (PINTERFACE)&Pl330DMAInterface, + &GUID_PL330DMA_INTERFACE_STANDARD, + NULL); + + status = WdfDeviceAddQueryInterface(device, &qiConfig); + if (!NT_SUCCESS(status)) { + Pl330DmaPrint(DEBUG_LEVEL_ERROR, DBG_PNP, + "WdfDeviceAddQueryInterface failed 0x%x\n", status); + + return status; + } + } + + return status; +} \ No newline at end of file diff --git a/drivers/dma/pl330dma/pl330.h b/drivers/dma/pl330dma/pl330.h new file mode 100644 index 0000000..b8451e7 --- /dev/null +++ b/drivers/dma/pl330dma/pl330.h @@ -0,0 +1,301 @@ +#define BIT(n) (1 << n) + +#define PL330_MAX_CHAN 8 +#define PL330_MAX_IRQS 32 +#define PL330_MAX_PERI 32 +#define PL330_MAX_BURST 16 + +#define PL330_QUIRK_BROKEN_NO_FLUSHP BIT(0) +#define PL330_QUIRK_PERIPH_BURST BIT(1) + +enum pl330_cachectrl { + CCTRL0, /* Noncacheable and nonbufferable */ + CCTRL1, /* Bufferable only */ + CCTRL2, /* Cacheable, but do not allocate */ + CCTRL3, /* Cacheable and bufferable, but do not allocate */ + INVALID1, /* AWCACHE = 0x1000 */ + INVALID2, + CCTRL6, /* Cacheable write-through, allocate on writes only */ + CCTRL7, /* Cacheable write-back, allocate on writes only */ +}; + +enum pl330_byteswap { + SWAP_NO, + SWAP_2, + SWAP_4, + SWAP_8, + SWAP_16, +}; + +/* Register and Bit field Definitions */ +#define DS 0x0 +#define DS_ST_STOP 0x0 +#define DS_ST_EXEC 0x1 +#define DS_ST_CMISS 0x2 +#define DS_ST_UPDTPC 0x3 +#define DS_ST_WFE 0x4 +#define DS_ST_ATBRR 0x5 +#define DS_ST_QBUSY 0x6 +#define DS_ST_WFP 0x7 +#define DS_ST_KILL 0x8 +#define DS_ST_CMPLT 0x9 +#define DS_ST_FLTCMP 0xe +#define DS_ST_FAULT 0xf + +#define DPC 0x4 +#define INTEN 0x20 +#define ES 0x24 +#define INTSTATUS 0x28 +#define INTCLR 0x2c +#define FSM 0x30 +#define FSC 0x34 +#define FTM 0x38 + +#define _FTC 0x40 +#define FTC(n) (_FTC + (n)*0x4) + +#define _CS 0x100 +#define CS(n) (_CS + (n)*0x8) +#define CS_CNS (1 << 21) + +#define _CPC 0x104 +#define CPC(n) (_CPC + (n)*0x8) + +#define _SA 0x400 +#define SA(n) (_SA + (n)*0x20) + +#define _DA 0x404 +#define DA(n) (_DA + (n)*0x20) + +#define _CC 0x408 +#define CC(n) (_CC + (n)*0x20) + +#define CC_SRCINC (1 << 0) +#define CC_DSTINC (1 << 14) +#define CC_SRCPRI (1 << 8) +#define CC_DSTPRI (1 << 22) +#define CC_SRCNS (1 << 9) +#define CC_DSTNS (1 << 23) +#define CC_SRCIA (1 << 10) +#define CC_DSTIA (1 << 24) +#define CC_SRCBRSTLEN_SHFT 4 +#define CC_DSTBRSTLEN_SHFT 18 +#define CC_SRCBRSTSIZE_SHFT 1 +#define CC_DSTBRSTSIZE_SHFT 15 +#define CC_SRCCCTRL_SHFT 11 +#define CC_SRCCCTRL_MASK 0x7 +#define CC_DSTCCTRL_SHFT 25 +#define CC_DRCCCTRL_MASK 0x7 +#define CC_SWAP_SHFT 28 + +#define _LC0 0x40c +#define LC0(n) (_LC0 + (n)*0x20) + +#define _LC1 0x410 +#define LC1(n) (_LC1 + (n)*0x20) + +#define DBGSTATUS 0xd00 +#define DBG_BUSY (1 << 0) + +#define DBGCMD 0xd04 +#define DBGINST0 0xd08 +#define DBGINST1 0xd0c + +#define CR0 0xe00 +#define CR1 0xe04 +#define CR2 0xe08 +#define CR3 0xe0c +#define CR4 0xe10 +#define CRD 0xe14 + +#define PERIPH_ID 0xfe0 +#define PERIPH_REV_SHIFT 20 +#define PERIPH_REV_MASK 0xf +#define PERIPH_REV_R0P0 0 +#define PERIPH_REV_R1P0 1 +#define PERIPH_REV_R1P1 2 + +#define CR0_PERIPH_REQ_SET (1 << 0) +#define CR0_BOOT_EN_SET (1 << 1) +#define CR0_BOOT_MAN_NS (1 << 2) +#define CR0_NUM_CHANS_SHIFT 4 +#define CR0_NUM_CHANS_MASK 0x7 +#define CR0_NUM_PERIPH_SHIFT 12 +#define CR0_NUM_PERIPH_MASK 0x1f +#define CR0_NUM_EVENTS_SHIFT 17 +#define CR0_NUM_EVENTS_MASK 0x1f + +#define CR1_ICACHE_LEN_SHIFT 0 +#define CR1_ICACHE_LEN_MASK 0x7 +#define CR1_NUM_ICACHELINES_SHIFT 4 +#define CR1_NUM_ICACHELINES_MASK 0xf + +#define CRD_DATA_WIDTH_SHIFT 0 +#define CRD_DATA_WIDTH_MASK 0x7 +#define CRD_WR_CAP_SHIFT 4 +#define CRD_WR_CAP_MASK 0x7 +#define CRD_WR_Q_DEP_SHIFT 8 +#define CRD_WR_Q_DEP_MASK 0xf +#define CRD_RD_CAP_SHIFT 12 +#define CRD_RD_CAP_MASK 0x7 +#define CRD_RD_Q_DEP_SHIFT 16 +#define CRD_RD_Q_DEP_MASK 0xf +#define CRD_DATA_BUFF_SHIFT 20 +#define CRD_DATA_BUFF_MASK 0x3ff + +#define PART 0x330 +#define DESIGNER 0x41 +#define REVISION 0x0 +#define INTEG_CFG 0x0 +#define PERIPH_ID_VAL ((PART << 0) | (DESIGNER << 12)) + +#define PL330_STATE_STOPPED (1 << 0) +#define PL330_STATE_EXECUTING (1 << 1) +#define PL330_STATE_WFE (1 << 2) +#define PL330_STATE_FAULTING (1 << 3) +#define PL330_STATE_COMPLETING (1 << 4) +#define PL330_STATE_WFP (1 << 5) +#define PL330_STATE_KILLING (1 << 6) +#define PL330_STATE_FAULT_COMPLETING (1 << 7) +#define PL330_STATE_CACHEMISS (1 << 8) +#define PL330_STATE_UPDTPC (1 << 9) +#define PL330_STATE_ATBARRIER (1 << 10) +#define PL330_STATE_QUEUEBUSY (1 << 11) +#define PL330_STATE_INVALID (1 << 15) + +#define PL330_STABLE_STATES (PL330_STATE_STOPPED | PL330_STATE_EXECUTING \ + | PL330_STATE_WFE | PL330_STATE_FAULTING) + +#define CMD_DMAADDH 0x54 +#define CMD_DMAEND 0x00 +#define CMD_DMAFLUSHP 0x35 +#define CMD_DMAGO 0xa0 +#define CMD_DMALD 0x04 +#define CMD_DMALDP 0x25 +#define CMD_DMALP 0x20 +#define CMD_DMALPEND 0x28 +#define CMD_DMAKILL 0x01 +#define CMD_DMAMOV 0xbc +#define CMD_DMANOP 0x18 +#define CMD_DMARMB 0x12 +#define CMD_DMASEV 0x34 +#define CMD_DMAST 0x08 +#define CMD_DMASTP 0x29 +#define CMD_DMASTZ 0x0c +#define CMD_DMAWFE 0x36 +#define CMD_DMAWFP 0x30 +#define CMD_DMAWMB 0x13 + +#define SZ_DMAADDH 3 +#define SZ_DMAEND 1 +#define SZ_DMAFLUSHP 2 +#define SZ_DMALD 1 +#define SZ_DMALDP 2 +#define SZ_DMALP 2 +#define SZ_DMALPEND 2 +#define SZ_DMAKILL 1 +#define SZ_DMAMOV 6 +#define SZ_DMANOP 1 +#define SZ_DMARMB 1 +#define SZ_DMASEV 2 +#define SZ_DMAST 1 +#define SZ_DMASTP 2 +#define SZ_DMASTZ 1 +#define SZ_DMAWFE 2 +#define SZ_DMAWFP 2 +#define SZ_DMAWMB 1 +#define SZ_DMAGO 6 + +#define BRST_LEN(ccr) ((((ccr) >> CC_SRCBRSTLEN_SHFT) & 0xf) + 1) +#define BRST_SIZE(ccr) (1 << (((ccr) >> CC_SRCBRSTSIZE_SHFT) & 0x7)) + +#define BYTE_TO_BURST(b, ccr) ((b) / BRST_SIZE(ccr) / BRST_LEN(ccr)) +#define BURST_TO_BYTE(c, ccr) ((c) * BRST_SIZE(ccr) * BRST_LEN(ccr)) +#define BYTE_MOD_BURST_LEN(b, ccr) (((b) / BRST_SIZE(ccr)) % BRST_LEN(ccr)) + +/* + * With 256 bytes, we can do more than 2.5MB and 5MB xfers per req + * at 1byte/burst for P<->M and M<->M respectively. + * For typical scenario, at 1word/burst, 10MB and 20MB xfers per req + * should be enough for P<->M and M<->M respectively. + */ +#define MCODE_BUFF_PER_REQ 256 + +/* Use this _only_ to wait on transient states */ +#define UNTIL(t, s) while (!(_state(t) & (s))) __yield(); + + /* The number of default descriptors */ + +#define NR_DEFAULT_DESC 16 + +/* Delay for runtime PM autosuspend, ms */ +#define PL330_AUTOSUSPEND_DELAY 20 + +#ifdef PL330_DEBUG_MCGEN +static unsigned cmd_line; +#define PL330_DBGCMD_DUMP(off, x, ...) do { \ + DbgPrint("%x:", cmd_line); \ + DbgPrint(x, __VA_ARGS__); \ + cmd_line += off; \ + } while (0) +#define PL330_DBGMC_START(addr) (cmd_line = addr) +#else +#define PL330_DBGCMD_DUMP(off, x, ...) do {} while (0) +#define PL330_DBGMC_START(addr) do {} while (0) +#endif + +/* The xfer callbacks are made with one of these arguments. */ +enum pl330_op_err { + /* The all xfers in the request were success. */ + PL330_ERR_NONE, + /* If req aborted due to global error. */ + PL330_ERR_ABORT, + /* If req failed due to problem with Channel. */ + PL330_ERR_FAIL, +}; + +enum dmamov_dst { + SAR = 0, + CCR, + DAR, +}; + +enum pl330_dst { + SRC = 0, + DST, +}; + +enum pl330_cond { + SINGLE, + BURST, + ALWAYS, +}; + +enum pl330_dmac_state { + UNINIT, + INIT, + DYING, +}; + +enum desc_status { + /* In the DMAC pool */ + FREE, + /* + * Allocated to some channel during prep_xxx + * Also may be sitting on the work_list. + */ + PREP, + /* + * Sitting on the work_list and already submitted + * to the PL330 core. Not more than two descriptors + * of a channel can be BUSY at any time. + */ + BUSY, + /* + * Sitting on the channel work_list but xfer done + * by PL330 core + */ + DONE, +}; + +#include "opcodes.h" \ No newline at end of file diff --git a/drivers/dma/pl330dma/pl330.rc b/drivers/dma/pl330dma/pl330.rc new file mode 100644 index 0000000..1048196 --- /dev/null +++ b/drivers/dma/pl330dma/pl330.rc @@ -0,0 +1,41 @@ +/*++ + +Copyright (c) Microsoft Corporation All Rights Reserved + +Module Name: + + pl330.rc + +Abstract: + +--*/ + +#include + +#define VER_FILETYPE VFT_DRV +#define VER_FILESUBTYPE VFT2_DRV_SYSTEM +#define VER_FILEDESCRIPTION_STR "Arm Primecell DMA Controller" +#define VER_INTERNALNAME_STR "pl330.sys" +#define VER_ORIGINALFILENAME_STR "pl330.sys" + +#define VER_LEGALCOPYRIGHT_YEARS "2023" +#define VER_LEGALCOPYRIGHT_STR "Copyright (C) " VER_LEGALCOPYRIGHT_YEARS " CoolStar." + +#define VER_FILEVERSION 1,0,0,0 +#define VER_PRODUCTVERSION_STR "1.0.0.0" +#define VER_PRODUCTVERSION 1,0,0,0 +#define LVER_PRODUCTVERSION_STR L"1.0.0.0" + +#define VER_FILEFLAGSMASK (VS_FF_DEBUG | VS_FF_PRERELEASE) +#ifdef DEBUG +#define VER_FILEFLAGS (VS_FF_DEBUG) +#else +#define VER_FILEFLAGS (0) +#endif + +#define VER_FILEOS VOS_NT_WINDOWS32 + +#define VER_COMPANYNAME_STR "CoolStar" +#define VER_PRODUCTNAME_STR "Arm Primecell DMA Controller" + +#include "common.ver" \ No newline at end of file diff --git a/drivers/dma/pl330dma/pl330.vcxproj b/drivers/dma/pl330dma/pl330.vcxproj new file mode 100644 index 0000000..5781655 --- /dev/null +++ b/drivers/dma/pl330dma/pl330.vcxproj @@ -0,0 +1,116 @@ + + + + + Debug + ARM64 + + + Release + ARM64 + + + + {58434B4F-EE73-4D1E-A78D-9FEC5CEC83C7} + {1bc93793-694f-48fe-9372-81e2b05556fd} + v4.5 + 11.0 + Win8.1 Debug + Win32 + pl330 + pl330dma + $(LatestTargetPlatformVersion) + + + + Windows10 + false + WindowsKernelModeDriver10.0 + Driver + KMDF + + + Windows10 + true + WindowsKernelModeDriver10.0 + Driver + KMDF + + + + + + + + + + + + DbgengKernelDebugger + + + DbgengKernelDebugger + + + + true + trace.h + true + false + $(SPB_INC_PATH)\$(SPB_VERSION_MAJOR).$(SPB_VERSION_MINOR);%(AdditionalIncludeDirectories) + + + 1.0.0 + + + SHA256 + + + $(SPB_LIB_PATH)\$(SPB_VERSION_MAJOR).$(SPB_VERSION_MINOR)\SpbCxStubs.lib;%(AdditionalDependencies) + + + + + true + trace.h + true + false + $(SPB_INC_PATH)\$(SPB_VERSION_MAJOR).$(SPB_VERSION_MINOR);%(AdditionalIncludeDirectories) + + + 1.0.0 + + + SHA256 + + + $(SPB_LIB_PATH)\$(SPB_VERSION_MAJOR).$(SPB_VERSION_MINOR)\SpbCxStubs.lib;%(AdditionalDependencies) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/drivers/dma/pl330dma/pl330.vcxproj.Filters b/drivers/dma/pl330dma/pl330.vcxproj.Filters new file mode 100644 index 0000000..28d4ec7 --- /dev/null +++ b/drivers/dma/pl330dma/pl330.vcxproj.Filters @@ -0,0 +1,50 @@ + + + + + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx;* + {E10CB9FB-4852-4353-85F5-667D4D2A13DD} + + + h;hpp;hxx;hm;inl;inc;xsd + {EC8940D8-5E2B-49AB-AB85-7CABCAE698D1} + + + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms;man;xml + {42A1FDF4-6DB4-41B2-9423-8002A20D1B0D} + + + inf;inv;inx;mof;mc; + {FD9F921C-D1EF-421B-A692-F23423B32E64} + + + + + Driver Files + + + + + Source Files + + + Source Files + + + + + Resource Files + + + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/drivers/dma/pl330dma/pl330dma.inx b/drivers/dma/pl330dma/pl330dma.inx new file mode 100644 index 0000000..9d8d5c9 --- /dev/null +++ b/drivers/dma/pl330dma/pl330dma.inx @@ -0,0 +1,77 @@ +;/*++ +; +;Copyright (c) CoolStar. All rights reserved. +; +;Module Name: +; pl330dma.inf +; +;Abstract: +; INF file for installing the ARM Primecell DMA Driver +; +; +;--*/ + +[Version] +Signature = "$WINDOWS NT$" +Class = System +ClassGuid = {4d36e97d-e325-11ce-bfc1-08002be10318} +Provider = CoolStar +DriverVer = 6/30/2023,1.0.0 +CatalogFile = pl330dma.cat +PnpLockdown = 1 + +[DestinationDirs] +DefaultDestDir = 12 + +; ================= Class section ===================== + +[SourceDisksNames] +1 = %DiskId1%,,,"" + +[SourceDisksFiles] +pl330dma.sys = 1,, + +;***************************************** +; Pl330DMA Install Section +;***************************************** + +[Manufacturer] +%StdMfg%=Standard,NT$ARCH$.10.0...14393 + +; Decorated model section take precedence over undecorated +; ones on XP and later. +[Standard.NT$ARCH$.10.0...14393] +%Pl330DMA.DeviceDesc%=Pl330DMA_Device, ACPI\ARMH0330 + +[Pl330DMA_Device.NT] +CopyFiles=Drivers_Dir + +[Pl330DMA_Device.NT.HW] +AddReg=Pl330DMA_AddReg + +[Drivers_Dir] +pl330dma.sys + +[Pl330DMA_AddReg] +; Set to 1 to connect the first interrupt resource found, 0 to leave disconnected +HKR,Settings,"ConnectInterrupt",0x00010001,0 + +;-------------- Service installation +[Pl330DMA_Device.NT.Services] +AddService = Pl330DMA,%SPSVCINST_ASSOCSERVICE%, Pl330DMA_Service_Inst + +; -------------- Pl330DMA driver install sections +[Pl330DMA_Service_Inst] +DisplayName = %Pl330DMA.SVCDESC% +ServiceType = 1 ; SERVICE_KERNEL_DRIVER +StartType = 3 ; SERVICE_DEMAND_START +ErrorControl = 1 ; SERVICE_ERROR_NORMAL +ServiceBinary = %12%\pl330dma.sys +LoadOrderGroup = Base + +[Strings] +SPSVCINST_ASSOCSERVICE= 0x00000002 +StdMfg = "Arm" +DiskId1 = "Arm Primecell Installation Disk #1" +Pl330DMA.DeviceDesc = "Arm Primecell DMA Controller" +Pl330DMA.SVCDESC = "Arm Primecell DMA Controller Service" diff --git a/drivers/dma/pl330dma/threads.c b/drivers/dma/pl330dma/threads.c new file mode 100644 index 0000000..b55b17c --- /dev/null +++ b/drivers/dma/pl330dma/threads.c @@ -0,0 +1,196 @@ +#include "driver.h" + +static ULONG Pl330DmaDebugLevel = 100; +static ULONG Pl330DmaDebugCatagories = DBG_INIT || DBG_PNP || DBG_IOCTL; + +static void ResetThread(PPL330DMA_THREAD Thread) { + PPL330DMA_CONTEXT pDevice = Thread->Device; + + Thread->Req[0].MCcpu = pDevice->MCodeCPU + (Thread->Id * pDevice->MCBufSz); + Thread->Req[0].MCbus = MmGetPhysicalAddress(Thread->Req[0].MCcpu); + RtlZeroMemory(&Thread->Req[0].Xfer, sizeof(XFER_SPEC)); + + /*Thread->Req[1].MCcpu = Thread->Req[0].MCcpu + pDevice->MCBufSz / 2; + Thread->Req[1].MCbus = MmGetPhysicalAddress(Thread->Req[1].MCcpu); + Thread->Req[1].Xfer = NULL;*/ + + for (int j = 0; j < MAX_NOTIF_EVENTS; j++) { + Thread->registeredCallbacks[j].InUse = FALSE; + } + + Thread->ReqRunning = FALSE; +} + +static NTSTATUS AllocThreads(PPL330DMA_CONTEXT pDevice) { + UINT8 chans = (UINT8)pDevice->Config.NumChan; + + pDevice->Channels = ExAllocatePoolZero(NonPagedPool, (1 + chans) * sizeof(PL330DMA_THREAD), PL330DMA_POOL_TAG); + if (!pDevice->Channels) { + return STATUS_NO_MEMORY; + } + + //Init channel threads + for (UINT8 i = 0; i < chans; i++) { + PPL330DMA_THREAD Thread = &pDevice->Channels[i]; + Thread->Id = i; + Thread->Device = pDevice; + Thread->ev = i; + ResetThread(Thread); + + Thread->Free = TRUE; + } + + /* Manager is indexed at the end */ + PPL330DMA_THREAD Thread = &pDevice->Channels[chans]; + Thread->Id = chans; + Thread->Device = pDevice; + Thread->Free = FALSE; + pDevice->Manager = Thread; + return STATUS_SUCCESS; +} + +NTSTATUS AllocResources(PPL330DMA_CONTEXT pDevice) { + int chans = pDevice->Config.NumChan; + + //Use default MC Buffer Size + pDevice->MCBufSz = MCODE_BUFF_PER_REQ * 2; + + //Allocate MicroCode buffer for 'chans' Channel threads + + PHYSICAL_ADDRESS ZeroAddr = { 0 }; + + PHYSICAL_ADDRESS HighestAddr; + HighestAddr.QuadPart = MAXUINT32; + pDevice->MCodeCPU = MmAllocateContiguousMemorySpecifyCache(chans * pDevice->MCBufSz, ZeroAddr, HighestAddr, ZeroAddr, MmNonCached); + if (!pDevice->MCodeCPU) { + return STATUS_NO_MEMORY; + } + + NTSTATUS status = AllocThreads(pDevice); + if (!NT_SUCCESS(status)) { + return status; + } + + return STATUS_SUCCESS; +} + +void FreeResources(PPL330DMA_CONTEXT pDevice) { + if (pDevice->Channels) { + //TODO: Release Channel Threads + + for (UINT32 i = 0; i < pDevice->Config.NumChan; i++) { + _stop(pDevice->Channels); + } + + //Free Channel Memory + ExFreePoolWithTag(pDevice->Channels, PL330DMA_POOL_TAG); + } + + //Free MCode + if (pDevice->MCodeCPU) + MmFreeContiguousMemory(pDevice->MCodeCPU); +} + +PPL330DMA_THREAD GetHandle(PPL330DMA_CONTEXT pDevice, int Idx) { + if (!pDevice) + return NULL; + for (UINT32 i = 0; i < pDevice->Config.NumChan; i++) { + if (!pDevice->Channels[i].Free) { + continue; + } + if (i == (UINT32)Idx || Idx == -1) { + Pl330DmaPrint(DEBUG_LEVEL_ERROR, DBG_IOCTL, "Setting Channel 0x%llx to be used\n", &pDevice->Channels[i]); + pDevice->Channels[i].Free = FALSE; + return &pDevice->Channels[i]; + } + } + return NULL; +} + +void StopThread(PPL330DMA_CONTEXT pDevice, PPL330DMA_THREAD Thread) { + UNREFERENCED_PARAMETER(pDevice); + if (!Thread) + return; + _stop(Thread); +} + +void GetThreadRegisters(PPL330DMA_CONTEXT pDevice, PPL330DMA_THREAD Thread, UINT32* cpc, UINT32* sa, UINT32* da) { + if (!Thread) + return; + if (cpc) { + *cpc = read32(pDevice, CPC(Thread->Id)); + } + if (sa) { + *sa = read32(pDevice, SA(Thread->Id)); + } + if (da) { + *da = read32(pDevice, DA(Thread->Id)); + } +} + +BOOLEAN FreeHandle(PPL330DMA_CONTEXT pDevice, PPL330DMA_THREAD Thread) { + UNREFERENCED_PARAMETER(pDevice); + if (!Thread) + return FALSE; + if (Thread->ReqRunning) { + return FALSE; + } + Thread->Free = TRUE; + return TRUE; +} + +NTSTATUS RegisterNotificationCallback( + PPL330DMA_CONTEXT pDevice, + PPL330DMA_THREAD Thread, + PDEVICE_OBJECT Fdo, + PDMA_NOTIFICATION_CALLBACK NotificationCallback, + PVOID CallbackContext) { + UNREFERENCED_PARAMETER(pDevice); + if (!Thread) + return STATUS_INVALID_PARAMETER; + + BOOLEAN registered = FALSE; + + for (int i = 0; i < MAX_NOTIF_EVENTS; i++) { + if (Thread->registeredCallbacks[i].InUse) + continue; + Thread->registeredCallbacks[i].InUse = TRUE; + Thread->registeredCallbacks[i].Fdo = Fdo; + Thread->registeredCallbacks[i].NotificationCallback = NotificationCallback; + Thread->registeredCallbacks[i].CallbackContext = CallbackContext; + + InterlockedIncrement(&Fdo->ReferenceCount); + + registered = TRUE; + break; + } + + return registered ? STATUS_SUCCESS : STATUS_INSUFFICIENT_RESOURCES; +} + +NTSTATUS UnregisterNotificationCallback( + PPL330DMA_CONTEXT pDevice, + PPL330DMA_THREAD Thread, + PDMA_NOTIFICATION_CALLBACK NotificationCallback, + PVOID CallbackContext) { + UNREFERENCED_PARAMETER(pDevice); + if (!Thread) + return STATUS_INVALID_PARAMETER; + + BOOLEAN registered = FALSE; + + for (int i = 0; i < MAX_NOTIF_EVENTS; i++) { + if (Thread->registeredCallbacks[i].InUse && + Thread->registeredCallbacks[i].NotificationCallback != NotificationCallback && + Thread->registeredCallbacks[i].CallbackContext != CallbackContext) + continue; + + InterlockedDecrement(&Thread->registeredCallbacks[i].Fdo->ReferenceCount); + + RtlZeroMemory(&Thread->registeredCallbacks[i], sizeof(Thread->registeredCallbacks[i])); + registered = TRUE; + break; + } + + return registered ? STATUS_SUCCESS : STATUS_INVALID_PARAMETER; +} \ No newline at end of file diff --git a/drivers/dma/pl330dma/trace.h b/drivers/dma/pl330dma/trace.h new file mode 100644 index 0000000..19b0bdf --- /dev/null +++ b/drivers/dma/pl330dma/trace.h @@ -0,0 +1,43 @@ +#include + +#ifndef _TRACE_H_ +#define _TRACE_H_ + +extern "C" +{ + // + // Tracing Definitions: + // + // Control GUID: + // {73e3b785-f5fb-423e-94a9-56627fea9053} + // + +#define WPP_CONTROL_GUIDS \ + WPP_DEFINE_CONTROL_GUID( \ + SpbTestToolTraceGuid, \ + (73e3b785,f5fb,423e,94a9,56627fea9053), \ + WPP_DEFINE_BIT(TRACE_FLAG_WDFLOADING) \ + WPP_DEFINE_BIT(TRACE_FLAG_SPBAPI) \ + WPP_DEFINE_BIT(TRACE_FLAG_OTHER) \ + ) +} + +#define WPP_LEVEL_FLAGS_LOGGER(level,flags) WPP_LEVEL_LOGGER(flags) +#define WPP_LEVEL_FLAGS_ENABLED(level, flags) (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= level) + +#define Trace CyapaPrint +#define FuncEntry +#define FuncExit +#define WPP_INIT_TRACING +#define WPP_CLEANUP +#define TRACE_FLAG_SPBAPI 0 +#define TRACE_FLAG_WDFLOADING 0 + +// begin_wpp config +// FUNC FuncEntry{LEVEL=TRACE_LEVEL_VERBOSE}(FLAGS); +// FUNC FuncExit{LEVEL=TRACE_LEVEL_VERBOSE}(FLAGS); +// USEPREFIX(FuncEntry, "%!STDPREFIX! [%!FUNC!] --> entry"); +// USEPREFIX(FuncExit, "%!STDPREFIX! [%!FUNC!] <--"); +// end_wpp + +#endif _TRACE_H_