bd8580b897e9532533edc88f8389edcb4c939639
[sfrench/cifs-2.6.git] / drivers / iommu / rockchip-iommu.c
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License version 2 as
4  * published by the Free Software Foundation.
5  */
6
7 #include <linux/clk.h>
8 #include <linux/compiler.h>
9 #include <linux/delay.h>
10 #include <linux/device.h>
11 #include <linux/dma-iommu.h>
12 #include <linux/dma-mapping.h>
13 #include <linux/errno.h>
14 #include <linux/interrupt.h>
15 #include <linux/io.h>
16 #include <linux/iommu.h>
17 #include <linux/iopoll.h>
18 #include <linux/list.h>
19 #include <linux/mm.h>
20 #include <linux/module.h>
21 #include <linux/of.h>
22 #include <linux/of_iommu.h>
23 #include <linux/of_platform.h>
24 #include <linux/platform_device.h>
25 #include <linux/slab.h>
26 #include <linux/spinlock.h>
27
28 /** MMU register offsets */
29 #define RK_MMU_DTE_ADDR         0x00    /* Directory table address */
30 #define RK_MMU_STATUS           0x04
31 #define RK_MMU_COMMAND          0x08
32 #define RK_MMU_PAGE_FAULT_ADDR  0x0C    /* IOVA of last page fault */
33 #define RK_MMU_ZAP_ONE_LINE     0x10    /* Shootdown one IOTLB entry */
34 #define RK_MMU_INT_RAWSTAT      0x14    /* IRQ status ignoring mask */
35 #define RK_MMU_INT_CLEAR        0x18    /* Acknowledge and re-arm irq */
36 #define RK_MMU_INT_MASK         0x1C    /* IRQ enable */
37 #define RK_MMU_INT_STATUS       0x20    /* IRQ status after masking */
38 #define RK_MMU_AUTO_GATING      0x24
39
40 #define DTE_ADDR_DUMMY          0xCAFEBABE
41
42 #define RK_MMU_POLL_PERIOD_US           100
43 #define RK_MMU_FORCE_RESET_TIMEOUT_US   100000
44 #define RK_MMU_POLL_TIMEOUT_US          1000
45
46 /* RK_MMU_STATUS fields */
47 #define RK_MMU_STATUS_PAGING_ENABLED       BIT(0)
48 #define RK_MMU_STATUS_PAGE_FAULT_ACTIVE    BIT(1)
49 #define RK_MMU_STATUS_STALL_ACTIVE         BIT(2)
50 #define RK_MMU_STATUS_IDLE                 BIT(3)
51 #define RK_MMU_STATUS_REPLAY_BUFFER_EMPTY  BIT(4)
52 #define RK_MMU_STATUS_PAGE_FAULT_IS_WRITE  BIT(5)
53 #define RK_MMU_STATUS_STALL_NOT_ACTIVE     BIT(31)
54
55 /* RK_MMU_COMMAND command values */
56 #define RK_MMU_CMD_ENABLE_PAGING    0  /* Enable memory translation */
57 #define RK_MMU_CMD_DISABLE_PAGING   1  /* Disable memory translation */
58 #define RK_MMU_CMD_ENABLE_STALL     2  /* Stall paging to allow other cmds */
59 #define RK_MMU_CMD_DISABLE_STALL    3  /* Stop stall re-enables paging */
60 #define RK_MMU_CMD_ZAP_CACHE        4  /* Shoot down entire IOTLB */
61 #define RK_MMU_CMD_PAGE_FAULT_DONE  5  /* Clear page fault */
62 #define RK_MMU_CMD_FORCE_RESET      6  /* Reset all registers */
63
64 /* RK_MMU_INT_* register fields */
65 #define RK_MMU_IRQ_PAGE_FAULT    0x01  /* page fault */
66 #define RK_MMU_IRQ_BUS_ERROR     0x02  /* bus read error */
67 #define RK_MMU_IRQ_MASK          (RK_MMU_IRQ_PAGE_FAULT | RK_MMU_IRQ_BUS_ERROR)
68
69 #define NUM_DT_ENTRIES 1024
70 #define NUM_PT_ENTRIES 1024
71
72 #define SPAGE_ORDER 12
73 #define SPAGE_SIZE (1 << SPAGE_ORDER)
74
75  /*
76   * Support mapping any size that fits in one page table:
77   *   4 KiB to 4 MiB
78   */
79 #define RK_IOMMU_PGSIZE_BITMAP 0x007ff000
80
81 struct rk_iommu_domain {
82         struct list_head iommus;
83         u32 *dt; /* page directory table */
84         dma_addr_t dt_dma;
85         spinlock_t iommus_lock; /* lock for iommus list */
86         spinlock_t dt_lock; /* lock for modifying page directory table */
87
88         struct iommu_domain domain;
89 };
90
91 /* list of clocks required by IOMMU */
92 static const char * const rk_iommu_clocks[] = {
93         "aclk", "iface",
94 };
95
96 struct rk_iommu {
97         struct device *dev;
98         void __iomem **bases;
99         int num_mmu;
100         struct clk_bulk_data *clocks;
101         int num_clocks;
102         bool reset_disabled;
103         struct iommu_device iommu;
104         struct list_head node; /* entry in rk_iommu_domain.iommus */
105         struct iommu_domain *domain; /* domain to which iommu is attached */
106 };
107
108 struct rk_iommudata {
109         struct rk_iommu *iommu;
110 };
111
112 static struct device *dma_dev;
113
114 static inline void rk_table_flush(struct rk_iommu_domain *dom, dma_addr_t dma,
115                                   unsigned int count)
116 {
117         size_t size = count * sizeof(u32); /* count of u32 entry */
118
119         dma_sync_single_for_device(dma_dev, dma, size, DMA_TO_DEVICE);
120 }
121
122 static struct rk_iommu_domain *to_rk_domain(struct iommu_domain *dom)
123 {
124         return container_of(dom, struct rk_iommu_domain, domain);
125 }
126
127 /*
128  * The Rockchip rk3288 iommu uses a 2-level page table.
129  * The first level is the "Directory Table" (DT).
130  * The DT consists of 1024 4-byte Directory Table Entries (DTEs), each pointing
131  * to a "Page Table".
132  * The second level is the 1024 Page Tables (PT).
133  * Each PT consists of 1024 4-byte Page Table Entries (PTEs), each pointing to
134  * a 4 KB page of physical memory.
135  *
136  * The DT and each PT fits in a single 4 KB page (4-bytes * 1024 entries).
137  * Each iommu device has a MMU_DTE_ADDR register that contains the physical
138  * address of the start of the DT page.
139  *
140  * The structure of the page table is as follows:
141  *
142  *                   DT
143  * MMU_DTE_ADDR -> +-----+
144  *                 |     |
145  *                 +-----+     PT
146  *                 | DTE | -> +-----+
147  *                 +-----+    |     |     Memory
148  *                 |     |    +-----+     Page
149  *                 |     |    | PTE | -> +-----+
150  *                 +-----+    +-----+    |     |
151  *                            |     |    |     |
152  *                            |     |    |     |
153  *                            +-----+    |     |
154  *                                       |     |
155  *                                       |     |
156  *                                       +-----+
157  */
158
159 /*
160  * Each DTE has a PT address and a valid bit:
161  * +---------------------+-----------+-+
162  * | PT address          | Reserved  |V|
163  * +---------------------+-----------+-+
164  *  31:12 - PT address (PTs always starts on a 4 KB boundary)
165  *  11: 1 - Reserved
166  *      0 - 1 if PT @ PT address is valid
167  */
168 #define RK_DTE_PT_ADDRESS_MASK    0xfffff000
169 #define RK_DTE_PT_VALID           BIT(0)
170
171 static inline phys_addr_t rk_dte_pt_address(u32 dte)
172 {
173         return (phys_addr_t)dte & RK_DTE_PT_ADDRESS_MASK;
174 }
175
176 static inline bool rk_dte_is_pt_valid(u32 dte)
177 {
178         return dte & RK_DTE_PT_VALID;
179 }
180
181 static inline u32 rk_mk_dte(dma_addr_t pt_dma)
182 {
183         return (pt_dma & RK_DTE_PT_ADDRESS_MASK) | RK_DTE_PT_VALID;
184 }
185
186 /*
187  * Each PTE has a Page address, some flags and a valid bit:
188  * +---------------------+---+-------+-+
189  * | Page address        |Rsv| Flags |V|
190  * +---------------------+---+-------+-+
191  *  31:12 - Page address (Pages always start on a 4 KB boundary)
192  *  11: 9 - Reserved
193  *   8: 1 - Flags
194  *      8 - Read allocate - allocate cache space on read misses
195  *      7 - Read cache - enable cache & prefetch of data
196  *      6 - Write buffer - enable delaying writes on their way to memory
197  *      5 - Write allocate - allocate cache space on write misses
198  *      4 - Write cache - different writes can be merged together
199  *      3 - Override cache attributes
200  *          if 1, bits 4-8 control cache attributes
201  *          if 0, the system bus defaults are used
202  *      2 - Writable
203  *      1 - Readable
204  *      0 - 1 if Page @ Page address is valid
205  */
206 #define RK_PTE_PAGE_ADDRESS_MASK  0xfffff000
207 #define RK_PTE_PAGE_FLAGS_MASK    0x000001fe
208 #define RK_PTE_PAGE_WRITABLE      BIT(2)
209 #define RK_PTE_PAGE_READABLE      BIT(1)
210 #define RK_PTE_PAGE_VALID         BIT(0)
211
212 static inline phys_addr_t rk_pte_page_address(u32 pte)
213 {
214         return (phys_addr_t)pte & RK_PTE_PAGE_ADDRESS_MASK;
215 }
216
217 static inline bool rk_pte_is_page_valid(u32 pte)
218 {
219         return pte & RK_PTE_PAGE_VALID;
220 }
221
222 /* TODO: set cache flags per prot IOMMU_CACHE */
223 static u32 rk_mk_pte(phys_addr_t page, int prot)
224 {
225         u32 flags = 0;
226         flags |= (prot & IOMMU_READ) ? RK_PTE_PAGE_READABLE : 0;
227         flags |= (prot & IOMMU_WRITE) ? RK_PTE_PAGE_WRITABLE : 0;
228         page &= RK_PTE_PAGE_ADDRESS_MASK;
229         return page | flags | RK_PTE_PAGE_VALID;
230 }
231
232 static u32 rk_mk_pte_invalid(u32 pte)
233 {
234         return pte & ~RK_PTE_PAGE_VALID;
235 }
236
237 /*
238  * rk3288 iova (IOMMU Virtual Address) format
239  *  31       22.21       12.11          0
240  * +-----------+-----------+-------------+
241  * | DTE index | PTE index | Page offset |
242  * +-----------+-----------+-------------+
243  *  31:22 - DTE index   - index of DTE in DT
244  *  21:12 - PTE index   - index of PTE in PT @ DTE.pt_address
245  *  11: 0 - Page offset - offset into page @ PTE.page_address
246  */
247 #define RK_IOVA_DTE_MASK    0xffc00000
248 #define RK_IOVA_DTE_SHIFT   22
249 #define RK_IOVA_PTE_MASK    0x003ff000
250 #define RK_IOVA_PTE_SHIFT   12
251 #define RK_IOVA_PAGE_MASK   0x00000fff
252 #define RK_IOVA_PAGE_SHIFT  0
253
254 static u32 rk_iova_dte_index(dma_addr_t iova)
255 {
256         return (u32)(iova & RK_IOVA_DTE_MASK) >> RK_IOVA_DTE_SHIFT;
257 }
258
259 static u32 rk_iova_pte_index(dma_addr_t iova)
260 {
261         return (u32)(iova & RK_IOVA_PTE_MASK) >> RK_IOVA_PTE_SHIFT;
262 }
263
264 static u32 rk_iova_page_offset(dma_addr_t iova)
265 {
266         return (u32)(iova & RK_IOVA_PAGE_MASK) >> RK_IOVA_PAGE_SHIFT;
267 }
268
269 static u32 rk_iommu_read(void __iomem *base, u32 offset)
270 {
271         return readl(base + offset);
272 }
273
274 static void rk_iommu_write(void __iomem *base, u32 offset, u32 value)
275 {
276         writel(value, base + offset);
277 }
278
279 static void rk_iommu_command(struct rk_iommu *iommu, u32 command)
280 {
281         int i;
282
283         for (i = 0; i < iommu->num_mmu; i++)
284                 writel(command, iommu->bases[i] + RK_MMU_COMMAND);
285 }
286
287 static void rk_iommu_base_command(void __iomem *base, u32 command)
288 {
289         writel(command, base + RK_MMU_COMMAND);
290 }
291 static void rk_iommu_zap_lines(struct rk_iommu *iommu, dma_addr_t iova_start,
292                                size_t size)
293 {
294         int i;
295         dma_addr_t iova_end = iova_start + size;
296         /*
297          * TODO(djkurtz): Figure out when it is more efficient to shootdown the
298          * entire iotlb rather than iterate over individual iovas.
299          */
300         for (i = 0; i < iommu->num_mmu; i++) {
301                 dma_addr_t iova;
302
303                 for (iova = iova_start; iova < iova_end; iova += SPAGE_SIZE)
304                         rk_iommu_write(iommu->bases[i], RK_MMU_ZAP_ONE_LINE, iova);
305         }
306 }
307
308 static bool rk_iommu_is_stall_active(struct rk_iommu *iommu)
309 {
310         bool active = true;
311         int i;
312
313         for (i = 0; i < iommu->num_mmu; i++)
314                 active &= !!(rk_iommu_read(iommu->bases[i], RK_MMU_STATUS) &
315                                            RK_MMU_STATUS_STALL_ACTIVE);
316
317         return active;
318 }
319
320 static bool rk_iommu_is_paging_enabled(struct rk_iommu *iommu)
321 {
322         bool enable = true;
323         int i;
324
325         for (i = 0; i < iommu->num_mmu; i++)
326                 enable &= !!(rk_iommu_read(iommu->bases[i], RK_MMU_STATUS) &
327                                            RK_MMU_STATUS_PAGING_ENABLED);
328
329         return enable;
330 }
331
332 static bool rk_iommu_is_reset_done(struct rk_iommu *iommu)
333 {
334         bool done = true;
335         int i;
336
337         for (i = 0; i < iommu->num_mmu; i++)
338                 done &= rk_iommu_read(iommu->bases[i], RK_MMU_DTE_ADDR) == 0;
339
340         return done;
341 }
342
343 static int rk_iommu_enable_stall(struct rk_iommu *iommu)
344 {
345         int ret, i;
346         bool val;
347
348         if (rk_iommu_is_stall_active(iommu))
349                 return 0;
350
351         /* Stall can only be enabled if paging is enabled */
352         if (!rk_iommu_is_paging_enabled(iommu))
353                 return 0;
354
355         rk_iommu_command(iommu, RK_MMU_CMD_ENABLE_STALL);
356
357         ret = readx_poll_timeout(rk_iommu_is_stall_active, iommu, val,
358                                  val, RK_MMU_POLL_PERIOD_US,
359                                  RK_MMU_POLL_TIMEOUT_US);
360         if (ret)
361                 for (i = 0; i < iommu->num_mmu; i++)
362                         dev_err(iommu->dev, "Enable stall request timed out, status: %#08x\n",
363                                 rk_iommu_read(iommu->bases[i], RK_MMU_STATUS));
364
365         return ret;
366 }
367
368 static int rk_iommu_disable_stall(struct rk_iommu *iommu)
369 {
370         int ret, i;
371         bool val;
372
373         if (!rk_iommu_is_stall_active(iommu))
374                 return 0;
375
376         rk_iommu_command(iommu, RK_MMU_CMD_DISABLE_STALL);
377
378         ret = readx_poll_timeout(rk_iommu_is_stall_active, iommu, val,
379                                  !val, RK_MMU_POLL_PERIOD_US,
380                                  RK_MMU_POLL_TIMEOUT_US);
381         if (ret)
382                 for (i = 0; i < iommu->num_mmu; i++)
383                         dev_err(iommu->dev, "Disable stall request timed out, status: %#08x\n",
384                                 rk_iommu_read(iommu->bases[i], RK_MMU_STATUS));
385
386         return ret;
387 }
388
389 static int rk_iommu_enable_paging(struct rk_iommu *iommu)
390 {
391         int ret, i;
392         bool val;
393
394         if (rk_iommu_is_paging_enabled(iommu))
395                 return 0;
396
397         rk_iommu_command(iommu, RK_MMU_CMD_ENABLE_PAGING);
398
399         ret = readx_poll_timeout(rk_iommu_is_paging_enabled, iommu, val,
400                                  val, RK_MMU_POLL_PERIOD_US,
401                                  RK_MMU_POLL_TIMEOUT_US);
402         if (ret)
403                 for (i = 0; i < iommu->num_mmu; i++)
404                         dev_err(iommu->dev, "Enable paging request timed out, status: %#08x\n",
405                                 rk_iommu_read(iommu->bases[i], RK_MMU_STATUS));
406
407         return ret;
408 }
409
410 static int rk_iommu_disable_paging(struct rk_iommu *iommu)
411 {
412         int ret, i;
413         bool val;
414
415         if (!rk_iommu_is_paging_enabled(iommu))
416                 return 0;
417
418         rk_iommu_command(iommu, RK_MMU_CMD_DISABLE_PAGING);
419
420         ret = readx_poll_timeout(rk_iommu_is_paging_enabled, iommu, val,
421                                  !val, RK_MMU_POLL_PERIOD_US,
422                                  RK_MMU_POLL_TIMEOUT_US);
423         if (ret)
424                 for (i = 0; i < iommu->num_mmu; i++)
425                         dev_err(iommu->dev, "Disable paging request timed out, status: %#08x\n",
426                                 rk_iommu_read(iommu->bases[i], RK_MMU_STATUS));
427
428         return ret;
429 }
430
431 static int rk_iommu_force_reset(struct rk_iommu *iommu)
432 {
433         int ret, i;
434         u32 dte_addr;
435         bool val;
436
437         if (iommu->reset_disabled)
438                 return 0;
439
440         /*
441          * Check if register DTE_ADDR is working by writing DTE_ADDR_DUMMY
442          * and verifying that upper 5 nybbles are read back.
443          */
444         for (i = 0; i < iommu->num_mmu; i++) {
445                 rk_iommu_write(iommu->bases[i], RK_MMU_DTE_ADDR, DTE_ADDR_DUMMY);
446
447                 dte_addr = rk_iommu_read(iommu->bases[i], RK_MMU_DTE_ADDR);
448                 if (dte_addr != (DTE_ADDR_DUMMY & RK_DTE_PT_ADDRESS_MASK)) {
449                         dev_err(iommu->dev, "Error during raw reset. MMU_DTE_ADDR is not functioning\n");
450                         return -EFAULT;
451                 }
452         }
453
454         rk_iommu_command(iommu, RK_MMU_CMD_FORCE_RESET);
455
456         ret = readx_poll_timeout(rk_iommu_is_reset_done, iommu, val,
457                                  val, RK_MMU_FORCE_RESET_TIMEOUT_US,
458                                  RK_MMU_POLL_TIMEOUT_US);
459         if (ret) {
460                 dev_err(iommu->dev, "FORCE_RESET command timed out\n");
461                 return ret;
462         }
463
464         return 0;
465 }
466
467 static void log_iova(struct rk_iommu *iommu, int index, dma_addr_t iova)
468 {
469         void __iomem *base = iommu->bases[index];
470         u32 dte_index, pte_index, page_offset;
471         u32 mmu_dte_addr;
472         phys_addr_t mmu_dte_addr_phys, dte_addr_phys;
473         u32 *dte_addr;
474         u32 dte;
475         phys_addr_t pte_addr_phys = 0;
476         u32 *pte_addr = NULL;
477         u32 pte = 0;
478         phys_addr_t page_addr_phys = 0;
479         u32 page_flags = 0;
480
481         dte_index = rk_iova_dte_index(iova);
482         pte_index = rk_iova_pte_index(iova);
483         page_offset = rk_iova_page_offset(iova);
484
485         mmu_dte_addr = rk_iommu_read(base, RK_MMU_DTE_ADDR);
486         mmu_dte_addr_phys = (phys_addr_t)mmu_dte_addr;
487
488         dte_addr_phys = mmu_dte_addr_phys + (4 * dte_index);
489         dte_addr = phys_to_virt(dte_addr_phys);
490         dte = *dte_addr;
491
492         if (!rk_dte_is_pt_valid(dte))
493                 goto print_it;
494
495         pte_addr_phys = rk_dte_pt_address(dte) + (pte_index * 4);
496         pte_addr = phys_to_virt(pte_addr_phys);
497         pte = *pte_addr;
498
499         if (!rk_pte_is_page_valid(pte))
500                 goto print_it;
501
502         page_addr_phys = rk_pte_page_address(pte) + page_offset;
503         page_flags = pte & RK_PTE_PAGE_FLAGS_MASK;
504
505 print_it:
506         dev_err(iommu->dev, "iova = %pad: dte_index: %#03x pte_index: %#03x page_offset: %#03x\n",
507                 &iova, dte_index, pte_index, page_offset);
508         dev_err(iommu->dev, "mmu_dte_addr: %pa dte@%pa: %#08x valid: %u pte@%pa: %#08x valid: %u page@%pa flags: %#03x\n",
509                 &mmu_dte_addr_phys, &dte_addr_phys, dte,
510                 rk_dte_is_pt_valid(dte), &pte_addr_phys, pte,
511                 rk_pte_is_page_valid(pte), &page_addr_phys, page_flags);
512 }
513
514 static irqreturn_t rk_iommu_irq(int irq, void *dev_id)
515 {
516         struct rk_iommu *iommu = dev_id;
517         u32 status;
518         u32 int_status;
519         dma_addr_t iova;
520         irqreturn_t ret = IRQ_NONE;
521         int i;
522
523         WARN_ON(clk_bulk_enable(iommu->num_clocks, iommu->clocks));
524
525         for (i = 0; i < iommu->num_mmu; i++) {
526                 int_status = rk_iommu_read(iommu->bases[i], RK_MMU_INT_STATUS);
527                 if (int_status == 0)
528                         continue;
529
530                 ret = IRQ_HANDLED;
531                 iova = rk_iommu_read(iommu->bases[i], RK_MMU_PAGE_FAULT_ADDR);
532
533                 if (int_status & RK_MMU_IRQ_PAGE_FAULT) {
534                         int flags;
535
536                         status = rk_iommu_read(iommu->bases[i], RK_MMU_STATUS);
537                         flags = (status & RK_MMU_STATUS_PAGE_FAULT_IS_WRITE) ?
538                                         IOMMU_FAULT_WRITE : IOMMU_FAULT_READ;
539
540                         dev_err(iommu->dev, "Page fault at %pad of type %s\n",
541                                 &iova,
542                                 (flags == IOMMU_FAULT_WRITE) ? "write" : "read");
543
544                         log_iova(iommu, i, iova);
545
546                         /*
547                          * Report page fault to any installed handlers.
548                          * Ignore the return code, though, since we always zap cache
549                          * and clear the page fault anyway.
550                          */
551                         if (iommu->domain)
552                                 report_iommu_fault(iommu->domain, iommu->dev, iova,
553                                                    flags);
554                         else
555                                 dev_err(iommu->dev, "Page fault while iommu not attached to domain?\n");
556
557                         rk_iommu_base_command(iommu->bases[i], RK_MMU_CMD_ZAP_CACHE);
558                         rk_iommu_base_command(iommu->bases[i], RK_MMU_CMD_PAGE_FAULT_DONE);
559                 }
560
561                 if (int_status & RK_MMU_IRQ_BUS_ERROR)
562                         dev_err(iommu->dev, "BUS_ERROR occurred at %pad\n", &iova);
563
564                 if (int_status & ~RK_MMU_IRQ_MASK)
565                         dev_err(iommu->dev, "unexpected int_status: %#08x\n",
566                                 int_status);
567
568                 rk_iommu_write(iommu->bases[i], RK_MMU_INT_CLEAR, int_status);
569         }
570
571         clk_bulk_disable(iommu->num_clocks, iommu->clocks);
572
573         return ret;
574 }
575
576 static phys_addr_t rk_iommu_iova_to_phys(struct iommu_domain *domain,
577                                          dma_addr_t iova)
578 {
579         struct rk_iommu_domain *rk_domain = to_rk_domain(domain);
580         unsigned long flags;
581         phys_addr_t pt_phys, phys = 0;
582         u32 dte, pte;
583         u32 *page_table;
584
585         spin_lock_irqsave(&rk_domain->dt_lock, flags);
586
587         dte = rk_domain->dt[rk_iova_dte_index(iova)];
588         if (!rk_dte_is_pt_valid(dte))
589                 goto out;
590
591         pt_phys = rk_dte_pt_address(dte);
592         page_table = (u32 *)phys_to_virt(pt_phys);
593         pte = page_table[rk_iova_pte_index(iova)];
594         if (!rk_pte_is_page_valid(pte))
595                 goto out;
596
597         phys = rk_pte_page_address(pte) + rk_iova_page_offset(iova);
598 out:
599         spin_unlock_irqrestore(&rk_domain->dt_lock, flags);
600
601         return phys;
602 }
603
604 static void rk_iommu_zap_iova(struct rk_iommu_domain *rk_domain,
605                               dma_addr_t iova, size_t size)
606 {
607         struct list_head *pos;
608         unsigned long flags;
609
610         /* shootdown these iova from all iommus using this domain */
611         spin_lock_irqsave(&rk_domain->iommus_lock, flags);
612         list_for_each(pos, &rk_domain->iommus) {
613                 struct rk_iommu *iommu;
614                 iommu = list_entry(pos, struct rk_iommu, node);
615                 WARN_ON(clk_bulk_enable(iommu->num_clocks, iommu->clocks));
616                 rk_iommu_zap_lines(iommu, iova, size);
617                 clk_bulk_disable(iommu->num_clocks, iommu->clocks);
618         }
619         spin_unlock_irqrestore(&rk_domain->iommus_lock, flags);
620 }
621
622 static void rk_iommu_zap_iova_first_last(struct rk_iommu_domain *rk_domain,
623                                          dma_addr_t iova, size_t size)
624 {
625         rk_iommu_zap_iova(rk_domain, iova, SPAGE_SIZE);
626         if (size > SPAGE_SIZE)
627                 rk_iommu_zap_iova(rk_domain, iova + size - SPAGE_SIZE,
628                                         SPAGE_SIZE);
629 }
630
631 static u32 *rk_dte_get_page_table(struct rk_iommu_domain *rk_domain,
632                                   dma_addr_t iova)
633 {
634         u32 *page_table, *dte_addr;
635         u32 dte_index, dte;
636         phys_addr_t pt_phys;
637         dma_addr_t pt_dma;
638
639         assert_spin_locked(&rk_domain->dt_lock);
640
641         dte_index = rk_iova_dte_index(iova);
642         dte_addr = &rk_domain->dt[dte_index];
643         dte = *dte_addr;
644         if (rk_dte_is_pt_valid(dte))
645                 goto done;
646
647         page_table = (u32 *)get_zeroed_page(GFP_ATOMIC | GFP_DMA32);
648         if (!page_table)
649                 return ERR_PTR(-ENOMEM);
650
651         pt_dma = dma_map_single(dma_dev, page_table, SPAGE_SIZE, DMA_TO_DEVICE);
652         if (dma_mapping_error(dma_dev, pt_dma)) {
653                 dev_err(dma_dev, "DMA mapping error while allocating page table\n");
654                 free_page((unsigned long)page_table);
655                 return ERR_PTR(-ENOMEM);
656         }
657
658         dte = rk_mk_dte(pt_dma);
659         *dte_addr = dte;
660
661         rk_table_flush(rk_domain, pt_dma, NUM_PT_ENTRIES);
662         rk_table_flush(rk_domain,
663                        rk_domain->dt_dma + dte_index * sizeof(u32), 1);
664 done:
665         pt_phys = rk_dte_pt_address(dte);
666         return (u32 *)phys_to_virt(pt_phys);
667 }
668
669 static size_t rk_iommu_unmap_iova(struct rk_iommu_domain *rk_domain,
670                                   u32 *pte_addr, dma_addr_t pte_dma,
671                                   size_t size)
672 {
673         unsigned int pte_count;
674         unsigned int pte_total = size / SPAGE_SIZE;
675
676         assert_spin_locked(&rk_domain->dt_lock);
677
678         for (pte_count = 0; pte_count < pte_total; pte_count++) {
679                 u32 pte = pte_addr[pte_count];
680                 if (!rk_pte_is_page_valid(pte))
681                         break;
682
683                 pte_addr[pte_count] = rk_mk_pte_invalid(pte);
684         }
685
686         rk_table_flush(rk_domain, pte_dma, pte_count);
687
688         return pte_count * SPAGE_SIZE;
689 }
690
691 static int rk_iommu_map_iova(struct rk_iommu_domain *rk_domain, u32 *pte_addr,
692                              dma_addr_t pte_dma, dma_addr_t iova,
693                              phys_addr_t paddr, size_t size, int prot)
694 {
695         unsigned int pte_count;
696         unsigned int pte_total = size / SPAGE_SIZE;
697         phys_addr_t page_phys;
698
699         assert_spin_locked(&rk_domain->dt_lock);
700
701         for (pte_count = 0; pte_count < pte_total; pte_count++) {
702                 u32 pte = pte_addr[pte_count];
703
704                 if (rk_pte_is_page_valid(pte))
705                         goto unwind;
706
707                 pte_addr[pte_count] = rk_mk_pte(paddr, prot);
708
709                 paddr += SPAGE_SIZE;
710         }
711
712         rk_table_flush(rk_domain, pte_dma, pte_total);
713
714         /*
715          * Zap the first and last iova to evict from iotlb any previously
716          * mapped cachelines holding stale values for its dte and pte.
717          * We only zap the first and last iova, since only they could have
718          * dte or pte shared with an existing mapping.
719          */
720         rk_iommu_zap_iova_first_last(rk_domain, iova, size);
721
722         return 0;
723 unwind:
724         /* Unmap the range of iovas that we just mapped */
725         rk_iommu_unmap_iova(rk_domain, pte_addr, pte_dma,
726                             pte_count * SPAGE_SIZE);
727
728         iova += pte_count * SPAGE_SIZE;
729         page_phys = rk_pte_page_address(pte_addr[pte_count]);
730         pr_err("iova: %pad already mapped to %pa cannot remap to phys: %pa prot: %#x\n",
731                &iova, &page_phys, &paddr, prot);
732
733         return -EADDRINUSE;
734 }
735
736 static int rk_iommu_map(struct iommu_domain *domain, unsigned long _iova,
737                         phys_addr_t paddr, size_t size, int prot)
738 {
739         struct rk_iommu_domain *rk_domain = to_rk_domain(domain);
740         unsigned long flags;
741         dma_addr_t pte_dma, iova = (dma_addr_t)_iova;
742         u32 *page_table, *pte_addr;
743         u32 dte_index, pte_index;
744         int ret;
745
746         spin_lock_irqsave(&rk_domain->dt_lock, flags);
747
748         /*
749          * pgsize_bitmap specifies iova sizes that fit in one page table
750          * (1024 4-KiB pages = 4 MiB).
751          * So, size will always be 4096 <= size <= 4194304.
752          * Since iommu_map() guarantees that both iova and size will be
753          * aligned, we will always only be mapping from a single dte here.
754          */
755         page_table = rk_dte_get_page_table(rk_domain, iova);
756         if (IS_ERR(page_table)) {
757                 spin_unlock_irqrestore(&rk_domain->dt_lock, flags);
758                 return PTR_ERR(page_table);
759         }
760
761         dte_index = rk_domain->dt[rk_iova_dte_index(iova)];
762         pte_index = rk_iova_pte_index(iova);
763         pte_addr = &page_table[pte_index];
764         pte_dma = rk_dte_pt_address(dte_index) + pte_index * sizeof(u32);
765         ret = rk_iommu_map_iova(rk_domain, pte_addr, pte_dma, iova,
766                                 paddr, size, prot);
767
768         spin_unlock_irqrestore(&rk_domain->dt_lock, flags);
769
770         return ret;
771 }
772
773 static size_t rk_iommu_unmap(struct iommu_domain *domain, unsigned long _iova,
774                              size_t size)
775 {
776         struct rk_iommu_domain *rk_domain = to_rk_domain(domain);
777         unsigned long flags;
778         dma_addr_t pte_dma, iova = (dma_addr_t)_iova;
779         phys_addr_t pt_phys;
780         u32 dte;
781         u32 *pte_addr;
782         size_t unmap_size;
783
784         spin_lock_irqsave(&rk_domain->dt_lock, flags);
785
786         /*
787          * pgsize_bitmap specifies iova sizes that fit in one page table
788          * (1024 4-KiB pages = 4 MiB).
789          * So, size will always be 4096 <= size <= 4194304.
790          * Since iommu_unmap() guarantees that both iova and size will be
791          * aligned, we will always only be unmapping from a single dte here.
792          */
793         dte = rk_domain->dt[rk_iova_dte_index(iova)];
794         /* Just return 0 if iova is unmapped */
795         if (!rk_dte_is_pt_valid(dte)) {
796                 spin_unlock_irqrestore(&rk_domain->dt_lock, flags);
797                 return 0;
798         }
799
800         pt_phys = rk_dte_pt_address(dte);
801         pte_addr = (u32 *)phys_to_virt(pt_phys) + rk_iova_pte_index(iova);
802         pte_dma = pt_phys + rk_iova_pte_index(iova) * sizeof(u32);
803         unmap_size = rk_iommu_unmap_iova(rk_domain, pte_addr, pte_dma, size);
804
805         spin_unlock_irqrestore(&rk_domain->dt_lock, flags);
806
807         /* Shootdown iotlb entries for iova range that was just unmapped */
808         rk_iommu_zap_iova(rk_domain, iova, unmap_size);
809
810         return unmap_size;
811 }
812
813 static struct rk_iommu *rk_iommu_from_dev(struct device *dev)
814 {
815         struct rk_iommudata *data = dev->archdata.iommu;
816
817         return data ? data->iommu : NULL;
818 }
819
820 static int rk_iommu_attach_device(struct iommu_domain *domain,
821                                   struct device *dev)
822 {
823         struct rk_iommu *iommu;
824         struct rk_iommu_domain *rk_domain = to_rk_domain(domain);
825         unsigned long flags;
826         int ret, i;
827
828         /*
829          * Allow 'virtual devices' (e.g., drm) to attach to domain.
830          * Such a device does not belong to an iommu group.
831          */
832         iommu = rk_iommu_from_dev(dev);
833         if (!iommu)
834                 return 0;
835
836         ret = clk_bulk_enable(iommu->num_clocks, iommu->clocks);
837         if (ret)
838                 return ret;
839
840         ret = rk_iommu_enable_stall(iommu);
841         if (ret)
842                 goto out_disable_clocks;
843
844         ret = rk_iommu_force_reset(iommu);
845         if (ret)
846                 goto out_disable_stall;
847
848         iommu->domain = domain;
849
850         for (i = 0; i < iommu->num_mmu; i++) {
851                 rk_iommu_write(iommu->bases[i], RK_MMU_DTE_ADDR,
852                                rk_domain->dt_dma);
853                 rk_iommu_base_command(iommu->bases[i], RK_MMU_CMD_ZAP_CACHE);
854                 rk_iommu_write(iommu->bases[i], RK_MMU_INT_MASK, RK_MMU_IRQ_MASK);
855         }
856
857         ret = rk_iommu_enable_paging(iommu);
858         if (ret)
859                 goto out_disable_stall;
860
861         spin_lock_irqsave(&rk_domain->iommus_lock, flags);
862         list_add_tail(&iommu->node, &rk_domain->iommus);
863         spin_unlock_irqrestore(&rk_domain->iommus_lock, flags);
864
865         dev_dbg(dev, "Attached to iommu domain\n");
866
867 out_disable_stall:
868         rk_iommu_disable_stall(iommu);
869 out_disable_clocks:
870         clk_bulk_disable(iommu->num_clocks, iommu->clocks);
871         return ret;
872 }
873
874 static void rk_iommu_detach_device(struct iommu_domain *domain,
875                                    struct device *dev)
876 {
877         struct rk_iommu *iommu;
878         struct rk_iommu_domain *rk_domain = to_rk_domain(domain);
879         unsigned long flags;
880         int i;
881
882         /* Allow 'virtual devices' (eg drm) to detach from domain */
883         iommu = rk_iommu_from_dev(dev);
884         if (!iommu)
885                 return;
886
887         spin_lock_irqsave(&rk_domain->iommus_lock, flags);
888         list_del_init(&iommu->node);
889         spin_unlock_irqrestore(&rk_domain->iommus_lock, flags);
890
891         /* Ignore error while disabling, just keep going */
892         WARN_ON(clk_bulk_enable(iommu->num_clocks, iommu->clocks));
893         rk_iommu_enable_stall(iommu);
894         rk_iommu_disable_paging(iommu);
895         for (i = 0; i < iommu->num_mmu; i++) {
896                 rk_iommu_write(iommu->bases[i], RK_MMU_INT_MASK, 0);
897                 rk_iommu_write(iommu->bases[i], RK_MMU_DTE_ADDR, 0);
898         }
899         rk_iommu_disable_stall(iommu);
900         clk_bulk_disable(iommu->num_clocks, iommu->clocks);
901
902         iommu->domain = NULL;
903
904         dev_dbg(dev, "Detached from iommu domain\n");
905 }
906
907 static struct iommu_domain *rk_iommu_domain_alloc(unsigned type)
908 {
909         struct rk_iommu_domain *rk_domain;
910
911         if (type != IOMMU_DOMAIN_UNMANAGED && type != IOMMU_DOMAIN_DMA)
912                 return NULL;
913
914         if (!dma_dev)
915                 return NULL;
916
917         rk_domain = devm_kzalloc(dma_dev, sizeof(*rk_domain), GFP_KERNEL);
918         if (!rk_domain)
919                 return NULL;
920
921         if (type == IOMMU_DOMAIN_DMA &&
922             iommu_get_dma_cookie(&rk_domain->domain))
923                 return NULL;
924
925         /*
926          * rk32xx iommus use a 2 level pagetable.
927          * Each level1 (dt) and level2 (pt) table has 1024 4-byte entries.
928          * Allocate one 4 KiB page for each table.
929          */
930         rk_domain->dt = (u32 *)get_zeroed_page(GFP_KERNEL | GFP_DMA32);
931         if (!rk_domain->dt)
932                 goto err_put_cookie;
933
934         rk_domain->dt_dma = dma_map_single(dma_dev, rk_domain->dt,
935                                            SPAGE_SIZE, DMA_TO_DEVICE);
936         if (dma_mapping_error(dma_dev, rk_domain->dt_dma)) {
937                 dev_err(dma_dev, "DMA map error for DT\n");
938                 goto err_free_dt;
939         }
940
941         rk_table_flush(rk_domain, rk_domain->dt_dma, NUM_DT_ENTRIES);
942
943         spin_lock_init(&rk_domain->iommus_lock);
944         spin_lock_init(&rk_domain->dt_lock);
945         INIT_LIST_HEAD(&rk_domain->iommus);
946
947         rk_domain->domain.geometry.aperture_start = 0;
948         rk_domain->domain.geometry.aperture_end   = DMA_BIT_MASK(32);
949         rk_domain->domain.geometry.force_aperture = true;
950
951         return &rk_domain->domain;
952
953 err_free_dt:
954         free_page((unsigned long)rk_domain->dt);
955 err_put_cookie:
956         if (type == IOMMU_DOMAIN_DMA)
957                 iommu_put_dma_cookie(&rk_domain->domain);
958
959         return NULL;
960 }
961
962 static void rk_iommu_domain_free(struct iommu_domain *domain)
963 {
964         struct rk_iommu_domain *rk_domain = to_rk_domain(domain);
965         int i;
966
967         WARN_ON(!list_empty(&rk_domain->iommus));
968
969         for (i = 0; i < NUM_DT_ENTRIES; i++) {
970                 u32 dte = rk_domain->dt[i];
971                 if (rk_dte_is_pt_valid(dte)) {
972                         phys_addr_t pt_phys = rk_dte_pt_address(dte);
973                         u32 *page_table = phys_to_virt(pt_phys);
974                         dma_unmap_single(dma_dev, pt_phys,
975                                          SPAGE_SIZE, DMA_TO_DEVICE);
976                         free_page((unsigned long)page_table);
977                 }
978         }
979
980         dma_unmap_single(dma_dev, rk_domain->dt_dma,
981                          SPAGE_SIZE, DMA_TO_DEVICE);
982         free_page((unsigned long)rk_domain->dt);
983
984         if (domain->type == IOMMU_DOMAIN_DMA)
985                 iommu_put_dma_cookie(&rk_domain->domain);
986 }
987
988 static int rk_iommu_add_device(struct device *dev)
989 {
990         struct iommu_group *group;
991         struct rk_iommu *iommu;
992
993         iommu = rk_iommu_from_dev(dev);
994         if (!iommu)
995                 return -ENODEV;
996
997         group = iommu_group_get_for_dev(dev);
998         if (IS_ERR(group))
999                 return PTR_ERR(group);
1000         iommu_group_put(group);
1001
1002         iommu_device_link(&iommu->iommu, dev);
1003
1004         return 0;
1005 }
1006
1007 static void rk_iommu_remove_device(struct device *dev)
1008 {
1009         struct rk_iommu *iommu;
1010
1011         iommu = rk_iommu_from_dev(dev);
1012
1013         iommu_device_unlink(&iommu->iommu, dev);
1014         iommu_group_remove_device(dev);
1015 }
1016
1017 static int rk_iommu_of_xlate(struct device *dev,
1018                              struct of_phandle_args *args)
1019 {
1020         struct platform_device *iommu_dev;
1021         struct rk_iommudata *data;
1022
1023         data = devm_kzalloc(dma_dev, sizeof(*data), GFP_KERNEL);
1024         if (!data)
1025                 return -ENOMEM;
1026
1027         iommu_dev = of_find_device_by_node(args->np);
1028
1029         data->iommu = platform_get_drvdata(iommu_dev);
1030         dev->archdata.iommu = data;
1031
1032         of_dev_put(iommu_dev);
1033
1034         return 0;
1035 }
1036
1037 static const struct iommu_ops rk_iommu_ops = {
1038         .domain_alloc = rk_iommu_domain_alloc,
1039         .domain_free = rk_iommu_domain_free,
1040         .attach_dev = rk_iommu_attach_device,
1041         .detach_dev = rk_iommu_detach_device,
1042         .map = rk_iommu_map,
1043         .unmap = rk_iommu_unmap,
1044         .map_sg = default_iommu_map_sg,
1045         .add_device = rk_iommu_add_device,
1046         .remove_device = rk_iommu_remove_device,
1047         .iova_to_phys = rk_iommu_iova_to_phys,
1048         .device_group = generic_device_group,
1049         .pgsize_bitmap = RK_IOMMU_PGSIZE_BITMAP,
1050         .of_xlate = rk_iommu_of_xlate,
1051 };
1052
1053 static int rk_iommu_probe(struct platform_device *pdev)
1054 {
1055         struct device *dev = &pdev->dev;
1056         struct rk_iommu *iommu;
1057         struct resource *res;
1058         int num_res = pdev->num_resources;
1059         int err, i, irq;
1060
1061         iommu = devm_kzalloc(dev, sizeof(*iommu), GFP_KERNEL);
1062         if (!iommu)
1063                 return -ENOMEM;
1064
1065         platform_set_drvdata(pdev, iommu);
1066         iommu->dev = dev;
1067         iommu->num_mmu = 0;
1068
1069         iommu->bases = devm_kzalloc(dev, sizeof(*iommu->bases) * num_res,
1070                                     GFP_KERNEL);
1071         if (!iommu->bases)
1072                 return -ENOMEM;
1073
1074         for (i = 0; i < num_res; i++) {
1075                 res = platform_get_resource(pdev, IORESOURCE_MEM, i);
1076                 if (!res)
1077                         continue;
1078                 iommu->bases[i] = devm_ioremap_resource(&pdev->dev, res);
1079                 if (IS_ERR(iommu->bases[i]))
1080                         continue;
1081                 iommu->num_mmu++;
1082         }
1083         if (iommu->num_mmu == 0)
1084                 return PTR_ERR(iommu->bases[0]);
1085
1086         i = 0;
1087         while ((irq = platform_get_irq(pdev, i++)) != -ENXIO) {
1088                 if (irq < 0)
1089                         return irq;
1090
1091                 err = devm_request_irq(iommu->dev, irq, rk_iommu_irq,
1092                                        IRQF_SHARED, dev_name(dev), iommu);
1093                 if (err)
1094                         return err;
1095         }
1096
1097         iommu->reset_disabled = device_property_read_bool(dev,
1098                                         "rockchip,disable-mmu-reset");
1099
1100         iommu->num_clocks = ARRAY_SIZE(rk_iommu_clocks);
1101         iommu->clocks = devm_kcalloc(iommu->dev, iommu->num_clocks,
1102                                      sizeof(*iommu->clocks), GFP_KERNEL);
1103         if (!iommu->clocks)
1104                 return -ENOMEM;
1105
1106         for (i = 0; i < iommu->num_clocks; ++i)
1107                 iommu->clocks[i].id = rk_iommu_clocks[i];
1108
1109         err = devm_clk_bulk_get(iommu->dev, iommu->num_clocks, iommu->clocks);
1110         if (err)
1111                 return err;
1112
1113         err = clk_bulk_prepare(iommu->num_clocks, iommu->clocks);
1114         if (err)
1115                 return err;
1116
1117         err = iommu_device_sysfs_add(&iommu->iommu, dev, NULL, dev_name(dev));
1118         if (err)
1119                 goto err_unprepare_clocks;
1120
1121         iommu_device_set_ops(&iommu->iommu, &rk_iommu_ops);
1122         iommu_device_set_fwnode(&iommu->iommu, &dev->of_node->fwnode);
1123
1124         err = iommu_device_register(&iommu->iommu);
1125         if (err)
1126                 goto err_remove_sysfs;
1127
1128         /*
1129          * Use the first registered IOMMU device for domain to use with DMA
1130          * API, since a domain might not physically correspond to a single
1131          * IOMMU device..
1132          */
1133         if (!dma_dev)
1134                 dma_dev = &pdev->dev;
1135
1136         return 0;
1137 err_remove_sysfs:
1138         iommu_device_sysfs_remove(&iommu->iommu);
1139 err_unprepare_clocks:
1140         clk_bulk_unprepare(iommu->num_clocks, iommu->clocks);
1141         return err;
1142 }
1143
1144 static void rk_iommu_shutdown(struct platform_device *pdev)
1145 {
1146         struct rk_iommu *iommu = platform_get_drvdata(pdev);
1147
1148         /*
1149          * Be careful not to try to shutdown an otherwise unused
1150          * IOMMU, as it is likely not to be clocked, and accessing it
1151          * would just block. An IOMMU without a domain is likely to be
1152          * unused, so let's use this as a (weak) guard.
1153          */
1154         if (iommu && iommu->domain) {
1155                 rk_iommu_enable_stall(iommu);
1156                 rk_iommu_disable_paging(iommu);
1157                 rk_iommu_force_reset(iommu);
1158         }
1159 }
1160
1161 static const struct of_device_id rk_iommu_dt_ids[] = {
1162         { .compatible = "rockchip,iommu" },
1163         { /* sentinel */ }
1164 };
1165 MODULE_DEVICE_TABLE(of, rk_iommu_dt_ids);
1166
1167 static struct platform_driver rk_iommu_driver = {
1168         .probe = rk_iommu_probe,
1169         .shutdown = rk_iommu_shutdown,
1170         .driver = {
1171                    .name = "rk_iommu",
1172                    .of_match_table = rk_iommu_dt_ids,
1173                    .suppress_bind_attrs = true,
1174         },
1175 };
1176
1177 static int __init rk_iommu_init(void)
1178 {
1179         struct device_node *np;
1180         int ret;
1181
1182         np = of_find_matching_node(NULL, rk_iommu_dt_ids);
1183         if (!np)
1184                 return 0;
1185
1186         of_node_put(np);
1187
1188         ret = bus_set_iommu(&platform_bus_type, &rk_iommu_ops);
1189         if (ret)
1190                 return ret;
1191
1192         return platform_driver_register(&rk_iommu_driver);
1193 }
1194 subsys_initcall(rk_iommu_init);
1195
1196 IOMMU_OF_DECLARE(rk_iommu_of, "rockchip,iommu");
1197
1198 MODULE_DESCRIPTION("IOMMU API for Rockchip");
1199 MODULE_AUTHOR("Simon Xue <xxm@rock-chips.com> and Daniel Kurtz <djkurtz@chromium.org>");
1200 MODULE_ALIAS("platform:rockchip-iommu");
1201 MODULE_LICENSE("GPL v2");