+/*
+ * TX and RX descriptors are 16 bytes. This causes problems with the cache
+ * maintenance on CPUs where the cache-line size exceeds the size of these
+ * descriptors. What will happen is that when the driver receives a packet
+ * it will be immediately requeued for the hardware to reuse. The CPU will
+ * therefore need to flush the cache-line containing the descriptor, which
+ * will cause all other descriptors in the same cache-line to be flushed
+ * along with it. If one of those descriptors had been written to by the
+ * device those changes (and the associated packet) will be lost.
+ *
+ * To work around this, we make use of non-cached memory if available. If
+ * descriptors are mapped uncached there's no need to manually flush them
+ * or invalidate them.
+ *
+ * Note that this only applies to descriptors. The packet data buffers do
+ * not have the same constraints since they are 1536 bytes large, so they
+ * are unlikely to share cache-lines.
+ */
+static void *rtl_alloc_descs(unsigned int num)
+{
+ size_t size = num * RTL8169_DESC_SIZE;
+
+#ifdef CONFIG_SYS_NONCACHED_MEMORY
+ return (void *)noncached_alloc(size, RTL8169_ALIGN);
+#else
+ return memalign(RTL8169_ALIGN, size);
+#endif
+}
+
+/*
+ * Cache maintenance functions. These are simple wrappers around the more
+ * general purpose flush_cache() and invalidate_dcache_range() functions.
+ */
+
+static void rtl_inval_rx_desc(struct RxDesc *desc)
+{
+#ifndef CONFIG_SYS_NONCACHED_MEMORY
+ unsigned long start = (unsigned long)desc & ~(ARCH_DMA_MINALIGN - 1);
+ unsigned long end = ALIGN(start + sizeof(*desc), ARCH_DMA_MINALIGN);
+
+ invalidate_dcache_range(start, end);
+#endif
+}
+
+static void rtl_flush_rx_desc(struct RxDesc *desc)
+{
+#ifndef CONFIG_SYS_NONCACHED_MEMORY
+ flush_cache((unsigned long)desc, sizeof(*desc));
+#endif
+}
+
+static void rtl_inval_tx_desc(struct TxDesc *desc)
+{
+#ifndef CONFIG_SYS_NONCACHED_MEMORY
+ unsigned long start = (unsigned long)desc & ~(ARCH_DMA_MINALIGN - 1);
+ unsigned long end = ALIGN(start + sizeof(*desc), ARCH_DMA_MINALIGN);
+
+ invalidate_dcache_range(start, end);
+#endif
+}
+
+static void rtl_flush_tx_desc(struct TxDesc *desc)
+{
+#ifndef CONFIG_SYS_NONCACHED_MEMORY
+ flush_cache((unsigned long)desc, sizeof(*desc));
+#endif
+}
+
+static void rtl_inval_buffer(void *buf, size_t size)
+{
+ unsigned long start = (unsigned long)buf & ~(ARCH_DMA_MINALIGN - 1);
+ unsigned long end = ALIGN(start + size, ARCH_DMA_MINALIGN);
+
+ invalidate_dcache_range(start, end);
+}
+
+static void rtl_flush_buffer(void *buf, size_t size)
+{
+ flush_cache((unsigned long)buf, size);
+}
+