dma.cpp 9.79 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/** DMA driver
 *
 * @author Daniel Krebs <github@daniel-krebs.net>
 * @copyright 2018, RWTH Institute for Automation of Complex Power Systems (ACS)
 * @license GNU General Public License (version 3)
 *
 * VILLASfpga
 *
 * This program 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 3 of the License, or
 * any later version.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/

#include <sstream>
#include <string>

#include <xilinx/xaxidma.h>

28
#include <villas/memory.hpp>
29

30 31 32
#include <villas/fpga/card.hpp>
#include <villas/fpga/ips/dma.hpp>
#include <villas/fpga/ips/intc.hpp>
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

// max. size of a DMA transfer in simple mode
#define FPGA_DMA_BOUNDARY	0x1000


namespace villas {
namespace fpga {
namespace ip {

// instantiate factory to make available to plugin infrastructure
static DmaFactory factory;

DmaFactory::DmaFactory() :
    IpNodeFactory(getName())
{
	// nothing to do
}


bool
Dma::init()
{
	// if there is a scatter-gather interface, then this instance has it
	hasSG = busMasterInterfaces.count(sgInterface) == 1;
	logger->info("Scatter-Gather support: {}", hasScatterGather());

	XAxiDma_Config xdma_cfg;

	xdma_cfg.BaseAddr = getBaseAddr(registerMemory);
	xdma_cfg.HasStsCntrlStrm = 0;
	xdma_cfg.HasMm2S = 1;
	xdma_cfg.HasMm2SDRE = 1;
	xdma_cfg.Mm2SDataWidth = 128;
	xdma_cfg.HasS2Mm = 1;
	xdma_cfg.HasS2MmDRE = 1; /* Data Realignment Engine */
	xdma_cfg.HasSg = hasScatterGather();
	xdma_cfg.S2MmDataWidth = 128;
	xdma_cfg.Mm2sNumChannels = 1;
	xdma_cfg.S2MmNumChannels = 1;
	xdma_cfg.Mm2SBurstSize = 64;
	xdma_cfg.S2MmBurstSize = 64;
	xdma_cfg.MicroDmaMode = 0;
	xdma_cfg.AddrWidth = 32;

	if (XAxiDma_CfgInitialize(&xDma, &xdma_cfg) != XST_SUCCESS) {
		logger->error("Cannot initialize Xilinx DMA driver");
		return false;
	}

	if (XAxiDma_Selftest(&xDma) != XST_SUCCESS) {
		logger->error("DMA selftest failed");
		return false;
	} else {
		logger->debug("DMA selftest passed");
	}

	/* Map buffer descriptors */
	if (hasScatterGather()) {
		logger->warn("Scatter Gather not yet implemented");
		return false;

//		ret = dma_alloc(c, &dma->bd, FPGA_DMA_BD_SIZE, 0);
//		if (ret)
//			return -3;

//		ret = dma_init_rings(&xDma, &dma->bd);
//		if (ret)
//			return -4;
	}

	/* Enable completion interrupts for both channels */
	XAxiDma_IntrEnable(&xDma, XAXIDMA_IRQ_IOC_MASK, XAXIDMA_DMA_TO_DEVICE);
	XAxiDma_IntrEnable(&xDma, XAXIDMA_IRQ_IOC_MASK, XAXIDMA_DEVICE_TO_DMA);

107 108
	irqs[mm2sInterrupt].irqController->enableInterrupt(irqs[mm2sInterrupt], true);
	irqs[s2mmInterrupt].irqController->enableInterrupt(irqs[s2mmInterrupt], true);
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133

	return true;
}


bool
Dma::reset()
{
	XAxiDma_Reset(&xDma);

	// value taken from libxil implementation
	int timeout = 500;

	while(timeout > 0) {
		if(XAxiDma_ResetIsDone(&xDma))
			return true;

		timeout--;
	}

	return false;
}


bool
134
Dma::memcpy(const MemoryBlock& src, const MemoryBlock& dst, size_t len)
135
{
136 137 138 139 140 141
	if(len == 0)
		return true;

	if(not connectLoopback())
		return false;

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
	if(this->read(dst, len) == 0)
		return false;

	if(this->write(src, len) == 0)
		return false;

	if(not this->writeComplete())
		return false;

	if(not this->readComplete())
		return false;

	return true;
}


158
bool
159 160 161
Dma::write(const MemoryBlock& mem, size_t len)
{
	auto& mm = MemoryManager::get();
162 163

	// user has to make sure that memory is accessible, otherwise this will throw
164 165 166 167
	auto translation = mm.getTranslation(busMasterInterfaces[mm2sInterface],
	                                     mem.getAddrSpaceId());
	const void* buf = reinterpret_cast<void*>(translation.getLocalAddr(0));

Daniel Krebs's avatar
Daniel Krebs committed
168
	logger->debug("Write to stream from address {:p}", buf);
169 170 171 172
	return hasScatterGather() ? writeSG(buf, len) : writeSimple(buf, len);
}


173
bool
174 175 176
Dma::read(const MemoryBlock& mem, size_t len)
{
	auto& mm = MemoryManager::get();
177 178

	// user has to make sure that memory is accessible, otherwise this will throw
179 180 181 182
	auto translation = mm.getTranslation(busMasterInterfaces[s2mmInterface],
	                                     mem.getAddrSpaceId());
	void* buf = reinterpret_cast<void*>(translation.getLocalAddr(0));

Daniel Krebs's avatar
Daniel Krebs committed
183
	logger->debug("Read from stream and write to address {:p}", buf);
184 185 186 187
	return hasScatterGather() ? readSG(buf, len) : readSimple(buf, len);
}


188
bool
189 190 191 192 193 194
Dma::writeSG(const void* buf, size_t len)
{
	(void) buf;
	(void) len;
	logger->error("DMA Scatter Gather write not implemented");

195
	return false;
196 197 198
}


199
bool
200 201 202 203 204 205
Dma::readSG(void* buf, size_t len)
{
	(void) buf;
	(void) len;
	logger->error("DMA Scatter Gather read not implemented");

206
	return false;
207 208 209
}


210
size_t
211 212 213 214
Dma::writeCompleteSG()
{
	logger->error("DMA Scatter Gather write not implemented");

215
	return 0;
216 217 218
}


219
size_t
220 221 222 223
Dma::readCompleteSG()
{
	logger->error("DMA Scatter Gather read not implemented");

224
	return 0;
225 226 227
}


228
bool
229 230 231 232 233
Dma::writeSimple(const void *buf, size_t len)
{
	XAxiDma_BdRing *ring = XAxiDma_GetTxRing(&xDma);

	if ((len == 0) || (len > FPGA_DMA_BOUNDARY))
234
		return false;
235 236 237 238 239 240 241

	if (not ring->HasDRE) {
		const uint32_t mask = xDma.MicroDmaMode
		                      ? XAXIDMA_MICROMODE_MIN_BUF_ALIGN
		                      : ring->DataWidth - 1;

		if (reinterpret_cast<uintptr_t>(buf) & mask) {
242
			return false;
243 244 245 246 247 248 249 250 251 252
		}
	}

	const bool dmaChannelHalted =
	        XAxiDma_ReadReg(ring->ChanBase, XAXIDMA_SR_OFFSET) & XAXIDMA_HALTED_MASK;

	const bool dmaToDeviceBusy = XAxiDma_Busy(&xDma, XAXIDMA_DMA_TO_DEVICE);

	/* If the engine is doing a transfer, cannot submit  */
	if (not dmaChannelHalted and dmaToDeviceBusy) {
253
		return false;
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
	}

	// set lower 32 bit of source address
	XAxiDma_WriteReg(ring->ChanBase, XAXIDMA_SRCADDR_OFFSET,
	                 LOWER_32_BITS(reinterpret_cast<uintptr_t>(buf)));

	// if neccessary, set upper 32 bit of source address
	if (xDma.AddrWidth > 32) {
		XAxiDma_WriteReg(ring->ChanBase, XAXIDMA_SRCADDR_MSB_OFFSET,
		                 UPPER_32_BITS(reinterpret_cast<uintptr_t>(buf)));
	}

	// start DMA channel
	auto channelControl = XAxiDma_ReadReg(ring->ChanBase, XAXIDMA_CR_OFFSET);
	channelControl |= XAXIDMA_CR_RUNSTOP_MASK;
	XAxiDma_WriteReg(ring->ChanBase, XAXIDMA_CR_OFFSET, channelControl);

	// set tail descriptor pointer
	XAxiDma_WriteReg(ring->ChanBase, XAXIDMA_BUFFLEN_OFFSET, len);


275
	return true;
276 277 278
}


279
bool
280 281 282 283 284
Dma::readSimple(void *buf, size_t len)
{
	XAxiDma_BdRing *ring = XAxiDma_GetRxRing(&xDma);

	if ((len == 0) || (len > FPGA_DMA_BOUNDARY))
285
		return false;
286 287 288 289 290 291 292

	if (not ring->HasDRE) {
		const uint32_t mask = xDma.MicroDmaMode
		                      ? XAXIDMA_MICROMODE_MIN_BUF_ALIGN
		                      : ring->DataWidth - 1;

		if (reinterpret_cast<uintptr_t>(buf) & mask) {
293
			return false;
294 295 296 297 298 299 300 301 302 303
		}
	}

	const bool dmaChannelHalted =
	        XAxiDma_ReadReg(ring->ChanBase, XAXIDMA_SR_OFFSET) & XAXIDMA_HALTED_MASK;

	const bool deviceToDmaBusy = XAxiDma_Busy(&xDma, XAXIDMA_DEVICE_TO_DMA);

	/* If the engine is doing a transfer, cannot submit  */
	if (not dmaChannelHalted and deviceToDmaBusy) {
304
		return false;
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
	}

	// set lower 32 bit of destination address
	XAxiDma_WriteReg(ring->ChanBase, XAXIDMA_DESTADDR_OFFSET,
	                 LOWER_32_BITS(reinterpret_cast<uintptr_t>(buf)));

	// if neccessary, set upper 32 bit of destination address
	if (xDma.AddrWidth > 32)
		XAxiDma_WriteReg(ring->ChanBase, XAXIDMA_DESTADDR_MSB_OFFSET,
		                 UPPER_32_BITS(reinterpret_cast<uintptr_t>(buf)));

	// start DMA channel
	auto channelControl = XAxiDma_ReadReg(ring->ChanBase, XAXIDMA_CR_OFFSET);
	channelControl |= XAXIDMA_CR_RUNSTOP_MASK;
	XAxiDma_WriteReg(ring->ChanBase, XAXIDMA_CR_OFFSET, channelControl);

	// set tail descriptor pointer
	XAxiDma_WriteReg(ring->ChanBase, XAXIDMA_BUFFLEN_OFFSET, len);

324
	return true;
325 326 327
}


328
size_t
329 330 331 332 333 334 335
Dma::writeCompleteSimple()
{
	while (!(XAxiDma_IntrGetIrq(&xDma, XAXIDMA_DMA_TO_DEVICE) & XAXIDMA_IRQ_IOC_MASK))
		irqs[mm2sInterrupt].irqController->waitForInterrupt(irqs[mm2sInterrupt]);

	XAxiDma_IntrAckIrq(&xDma, XAXIDMA_IRQ_IOC_MASK, XAXIDMA_DMA_TO_DEVICE);

336 337 338 339
	const XAxiDma_BdRing* ring = XAxiDma_GetTxRing(&xDma);
	const size_t bytesWritten = XAxiDma_ReadReg(ring->ChanBase, XAXIDMA_BUFFLEN_OFFSET);

	return bytesWritten;
340 341 342
}


343
size_t
344 345 346 347 348 349 350
Dma::readCompleteSimple()
{
	while (!(XAxiDma_IntrGetIrq(&xDma, XAXIDMA_DEVICE_TO_DMA) & XAXIDMA_IRQ_IOC_MASK))
		irqs[s2mmInterrupt].irqController->waitForInterrupt(irqs[s2mmInterrupt]);

	XAxiDma_IntrAckIrq(&xDma, XAXIDMA_IRQ_IOC_MASK, XAXIDMA_DEVICE_TO_DMA);

351 352 353 354
	const XAxiDma_BdRing* ring = XAxiDma_GetRxRing(&xDma);
	const size_t bytesRead = XAxiDma_ReadReg(ring->ChanBase, XAXIDMA_BUFFLEN_OFFSET);

	return bytesRead;
355 356 357
}


358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
bool
Dma::makeAccesibleFromVA(const MemoryBlock& mem)
{
	// only symmetric mapping supported currently
	if(isMemoryBlockAccesible(mem, s2mmInterface) and
	   isMemoryBlockAccesible(mem, mm2sInterface)) {
		return true;
	}

	// try mapping via FPGA-card (VFIO)
	if(not card->mapMemoryBlock(mem)) {
		logger->error("Memory not accessible by DMA");
		return false;
	}

	// sanity-check if mapping worked, this shouldn't be neccessary
	if(not isMemoryBlockAccesible(mem, s2mmInterface) or
	   not isMemoryBlockAccesible(mem, mm2sInterface)) {
		logger->error("Mapping memory via card didn't work, but reported success?!");
		return false;
	}

	return true;
}


bool
Dma::isMemoryBlockAccesible(const MemoryBlock& mem, const std::string& interface)
{
	auto& mm = MemoryManager::get();

	try {
		mm.findPath(getMasterAddrSpaceByInterface(interface), mem.getAddrSpaceId());
	} catch(const std::out_of_range&) {
		// not (yet) accessible
		return false;
	}

	return true;
}


400 401 402
} // namespace ip
} // namespace fpga
} // namespace villas