2 * Copyright (c) 2012-2013, 2015, 2017, 2019 ARM Limited
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
14 * Copyright (c) 2004-2005 The Regents of The University of Michigan
15 * All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 #ifndef __DEV_DMA_DEVICE_HH__
42 #define __DEV_DMA_DEVICE_HH__
47 #include "base/circlebuf.hh"
48 #include "dev/io_device.hh"
49 #include "params/DmaDevice.hh"
50 #include "sim/drain.hh"
51 #include "sim/system.hh"
55 class DmaPort : public MasterPort, public Drainable
60 * Take the first packet of the transmit list and attempt to send
61 * it as a timing request. If it is successful, schedule the
62 * sending of the next packet, otherwise remember that we are
63 * waiting for a retry.
65 void trySendTimingReq();
68 * For timing, attempt to send the first item on the transmit
69 * list, and if it is successful and there are more packets
70 * waiting, then schedule the sending of the next packet. For
71 * atomic, simply send and process everything on the transmit
77 * Handle a response packet by updating the corresponding DMA
78 * request state to reflect the bytes received, and also update
79 * the pending request counter. If the DMA request that this
80 * packet is part of is complete, then signal the completion event
81 * if present, potentially with a delay added to it.
83 * @param pkt Response packet to handler
84 * @param delay Additional delay for scheduling the completion event
86 void handleResp(PacketPtr pkt, Tick delay = 0);
88 struct DmaReqState : public Packet::SenderState
90 /** Event to call on the device when this transaction (all packets)
92 Event *completionEvent;
94 /** Total number of bytes that this transaction involves. */
97 /** Number of bytes that have been acked for this transaction. */
100 /** Amount to delay completion of dma by */
103 DmaReqState(Event *ce, Addr tb, Tick _delay)
104 : completionEvent(ce), totBytes(tb), numBytes(0), delay(_delay)
109 /** The device that owns this port. */
110 ClockedObject *const device;
112 /** The system that device/port are in. This is used to select which mode
113 * we are currently operating in. */
116 /** Id for all requests */
117 const MasterID masterId;
120 /** Use a deque as we never do any insertion or removal in the middle */
121 std::deque<PacketPtr> transmitList;
123 /** Event used to schedule a future sending from the transmit list. */
124 EventFunctionWrapper sendEvent;
126 /** Number of outstanding packets the dma port has. */
127 uint32_t pendingCount;
129 /** If the port is currently waiting for a retry before it can
130 * send whatever it is that it's sending. */
133 /** Default streamId */
134 const uint32_t defaultSid;
136 /** Default substreamId */
137 const uint32_t defaultSSid;
141 bool recvTimingResp(PacketPtr pkt) override;
142 void recvReqRetry() override;
144 void queueDma(PacketPtr pkt);
148 DmaPort(ClockedObject *dev, System *s,
149 uint32_t sid = 0, uint32_t ssid = 0);
152 dmaAction(Packet::Command cmd, Addr addr, int size, Event *event,
153 uint8_t *data, Tick delay, Request::Flags flag = 0);
156 dmaAction(Packet::Command cmd, Addr addr, int size, Event *event,
157 uint8_t *data, uint32_t sid, uint32_t ssid, Tick delay,
158 Request::Flags flag = 0);
160 bool dmaPending() const { return pendingCount > 0; }
162 DrainState drain() override;
165 class DmaDevice : public PioDevice
171 typedef DmaDeviceParams Params;
172 DmaDevice(const Params *p);
173 virtual ~DmaDevice() { }
175 void dmaWrite(Addr addr, int size, Event *event, uint8_t *data,
176 uint32_t sid, uint32_t ssid, Tick delay = 0)
178 dmaPort.dmaAction(MemCmd::WriteReq, addr, size, event, data,
182 void dmaWrite(Addr addr, int size, Event *event, uint8_t *data,
185 dmaPort.dmaAction(MemCmd::WriteReq, addr, size, event, data, delay);
188 void dmaRead(Addr addr, int size, Event *event, uint8_t *data,
189 uint32_t sid, uint32_t ssid, Tick delay = 0)
191 dmaPort.dmaAction(MemCmd::ReadReq, addr, size, event, data,
195 void dmaRead(Addr addr, int size, Event *event, uint8_t *data,
198 dmaPort.dmaAction(MemCmd::ReadReq, addr, size, event, data, delay);
201 bool dmaPending() const { return dmaPort.dmaPending(); }
203 void init() override;
205 unsigned int cacheBlockSize() const { return sys->cacheLineSize(); }
207 Port &getPort(const std::string &if_name,
208 PortID idx=InvalidPortID) override;
213 * DMA callback class.
215 * Allows one to register for a callback event after a sequence of (potentially
216 * non-contiguous) DMA transfers on a DmaPort completes. Derived classes must
217 * implement the process() method and use getChunkEvent() to allocate a
218 * callback event for each participating DMA.
220 class DmaCallback : public Drainable
223 virtual const std::string name() const { return "DmaCallback"; }
226 * DmaPort ensures that all oustanding DMA accesses have completed before
227 * it finishes draining. However, DmaChunkEvents scheduled with a delay
228 * might still be sitting on the event queue. Therefore, draining is not
229 * complete until count is 0, which ensures that all outstanding
230 * DmaChunkEvents associated with this DmaCallback have fired.
232 DrainState drain() override
234 return count ? DrainState::Draining : DrainState::Drained;
244 virtual ~DmaCallback() { }
247 * Callback function invoked on completion of all chunks.
249 virtual void process() = 0;
253 * Called by DMA engine completion event on each chunk completion.
254 * Since the object may delete itself here, callers should not use
255 * the object pointer after calling this function.
261 // Need to notify DrainManager that this object is finished
262 // draining, even though it is immediately deleted.
271 * Request a chunk event. Chunks events should be provided to each DMA
272 * request that wishes to participate in this DmaCallback.
274 Event *getChunkEvent()
277 return new EventFunctionWrapper([this]{ chunkComplete(); }, name(),
283 * Buffered DMA engine helper class
285 * This class implements a simple DMA engine that feeds a FIFO
286 * buffer. The size of the buffer, the maximum number of pending
287 * requests and the maximum request size are all set when the engine
290 * An <i>asynchronous</i> transfer of a <i>block</i> of data
291 * (designated by a start address and a size) is started by calling
292 * the startFill() method. The DMA engine will aggressively try to
293 * keep the internal FIFO full. As soon as there is room in the FIFO
294 * for more data <i>and</i> there are free request slots, a new fill
297 * Data in the FIFO can be read back using the get() and tryGet()
298 * methods. Both request a block of data from the FIFO. However, get()
299 * panics if the block cannot be satisfied, while tryGet() simply
300 * returns false. The latter call makes it possible to implement
301 * custom buffer underrun handling.
303 * A simple use case would be something like this:
305 * // Create a DMA engine with a 1KiB buffer. Issue up to 8 concurrent
306 * // uncacheable 64 byte (maximum) requests.
307 * DmaReadFifo *dma = new DmaReadFifo(port, 1024, 64, 8,
308 * Request::UNCACHEABLE);
310 * // Start copying 4KiB data from 0xFF000000
311 * dma->startFill(0xFF000000, 0x1000);
313 * // Some time later when there is data in the FIFO.
315 * dma->get(data, sizeof(data))
319 * The DMA engine allows new blocks to be requested as soon as the
320 * last request for a block has been sent (i.e., there is no need to
321 * wait for pending requests to complete). This can be queried with
322 * the atEndOfBlock() method and more advanced implementations may
323 * override the onEndOfBlock() callback.
325 class DmaReadFifo : public Drainable, public Serializable
328 DmaReadFifo(DmaPort &port, size_t size,
329 unsigned max_req_size,
330 unsigned max_pending,
331 Request::Flags flags = 0);
335 public: // Serializable
336 void serialize(CheckpointOut &cp) const override;
337 void unserialize(CheckpointIn &cp) override;
340 DrainState drain() override;
342 public: // FIFO access
348 * Try to read data from the FIFO.
350 * This method reads len bytes of data from the FIFO and stores
351 * them in the memory location pointed to by dst. The method
352 * fails, and no data is written to the buffer, if the FIFO
353 * doesn't contain enough data to satisfy the request.
355 * @param dst Pointer to a destination buffer
356 * @param len Amount of data to read.
357 * @return true on success, false otherwise.
359 bool tryGet(uint8_t *dst, size_t len);
362 bool tryGet(T &value) {
363 return tryGet(static_cast<T *>(&value), sizeof(T));
367 * Read data from the FIFO and panic on failure.
371 * @param dst Pointer to a destination buffer
372 * @param len Amount of data to read.
374 void get(uint8_t *dst, size_t len);
379 get(static_cast<uint8_t *>(&value), sizeof(T));
383 /** Get the amount of data stored in the FIFO */
384 size_t size() const { return buffer.size(); }
385 /** Flush the FIFO */
386 void flush() { buffer.flush(); }
389 public: // FIFO fill control
392 * @name FIFO fill control
395 * Start filling the FIFO.
397 * @warn It's considered an error to call start on an active DMA
398 * engine unless the last request from the active block has been
399 * sent (i.e., atEndOfBlock() is true).
401 * @param start Physical address to copy from.
402 * @param size Size of the block to copy.
404 void startFill(Addr start, size_t size);
407 * Stop the DMA engine.
409 * Stop filling the FIFO and ignore incoming responses for pending
410 * requests. The onEndOfBlock() callback will not be called after
411 * this method has been invoked. However, once the last response
412 * has been received, the onIdle() callback will still be called.
417 * Has the DMA engine sent out the last request for the active
420 bool atEndOfBlock() const {
421 return nextAddr == endAddr;
425 * Is the DMA engine active (i.e., are there still in-flight
428 bool isActive() const {
429 return !(pendingRequests.empty() && atEndOfBlock());
433 protected: // Callbacks
439 * End of block callback
441 * This callback is called <i>once</i> after the last access in a
442 * block has been sent. It is legal for a derived class to call
443 * startFill() from this method to initiate a transfer.
445 virtual void onEndOfBlock() {};
448 * Last response received callback
450 * This callback is called when the DMA engine becomes idle (i.e.,
451 * there are no pending requests).
453 * It is possible for a DMA engine to reach the end of block and
454 * become idle at the same tick. In such a case, the
455 * onEndOfBlock() callback will be called first. This callback
456 * will <i>NOT</i> be called if that callback initiates a new DMA transfer.
458 virtual void onIdle() {};
461 private: // Configuration
462 /** Maximum request size in bytes */
463 const Addr maxReqSize;
464 /** Maximum FIFO size in bytes */
465 const size_t fifoSize;
467 const Request::Flags reqFlags;
472 class DmaDoneEvent : public Event
475 DmaDoneEvent(DmaReadFifo *_parent, size_t max_size);
479 bool canceled() const { return _canceled; }
480 void reset(size_t size);
483 bool done() const { return _done; }
484 size_t requestSize() const { return _requestSize; }
485 const uint8_t *data() const { return _data.data(); }
486 uint8_t *data() { return _data.data(); }
493 std::vector<uint8_t> _data;
496 typedef std::unique_ptr<DmaDoneEvent> DmaDoneEventUPtr;
499 * DMA request done, handle incoming data and issue new
504 /** Handle pending requests that have been flagged as done. */
505 void handlePending();
507 /** Try to issue new DMA requests or bypass DMA requests*/
510 /** Try to issue new DMA requests during normal execution*/
511 void resumeFillTiming();
513 /** Try to bypass DMA requests in KVM execution mode */
514 void resumeFillFunctional();
516 private: // Internal state
517 Fifo<uint8_t> buffer;
522 std::deque<DmaDoneEventUPtr> pendingRequests;
523 std::deque<DmaDoneEventUPtr> freeRequests;
526 #endif // __DEV_DMA_DEVICE_HH__