a9c804fa3fbe646a0a8eea07d642fd2a3b65ca1c
[linux-2.6-microblaze.git] / drivers / mailbox / bcm-pdc-mailbox.c
1 /*
2  * Copyright 2016 Broadcom
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License, version 2, as
6  * published by the Free Software Foundation (the "GPL").
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License version 2 (GPLv2) for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * version 2 (GPLv2) along with this source code.
15  */
16
17 /*
18  * Broadcom PDC Mailbox Driver
19  * The PDC provides a ring based programming interface to one or more hardware
20  * offload engines. For example, the PDC driver works with both SPU-M and SPU2
21  * cryptographic offload hardware. In some chips the PDC is referred to as MDE.
22  *
23  * The PDC driver registers with the Linux mailbox framework as a mailbox
24  * controller, once for each PDC instance. Ring 0 for each PDC is registered as
25  * a mailbox channel. The PDC driver uses interrupts to determine when data
26  * transfers to and from an offload engine are complete. The PDC driver uses
27  * threaded IRQs so that response messages are handled outside of interrupt
28  * context.
29  *
30  * The PDC driver allows multiple messages to be pending in the descriptor
31  * rings. The tx_msg_start descriptor index indicates where the last message
32  * starts. The txin_numd value at this index indicates how many descriptor
33  * indexes make up the message. Similar state is kept on the receive side. When
34  * an rx interrupt indicates a response is ready, the PDC driver processes numd
35  * descriptors from the tx and rx ring, thus processing one response at a time.
36  */
37
38 #include <linux/errno.h>
39 #include <linux/module.h>
40 #include <linux/init.h>
41 #include <linux/slab.h>
42 #include <linux/debugfs.h>
43 #include <linux/interrupt.h>
44 #include <linux/wait.h>
45 #include <linux/platform_device.h>
46 #include <linux/io.h>
47 #include <linux/of.h>
48 #include <linux/of_device.h>
49 #include <linux/of_address.h>
50 #include <linux/of_irq.h>
51 #include <linux/mailbox_controller.h>
52 #include <linux/mailbox/brcm-message.h>
53 #include <linux/scatterlist.h>
54 #include <linux/dma-direction.h>
55 #include <linux/dma-mapping.h>
56 #include <linux/dmapool.h>
57
58 #define PDC_SUCCESS  0
59
60 #define RING_ENTRY_SIZE   sizeof(struct dma64dd)
61
62 /* # entries in PDC dma ring */
63 #define PDC_RING_ENTRIES  128
64 #define PDC_RING_SIZE    (PDC_RING_ENTRIES * RING_ENTRY_SIZE)
65 /* Rings are 8k aligned */
66 #define RING_ALIGN_ORDER  13
67 #define RING_ALIGN        BIT(RING_ALIGN_ORDER)
68
69 #define RX_BUF_ALIGN_ORDER  5
70 #define RX_BUF_ALIGN        BIT(RX_BUF_ALIGN_ORDER)
71
72 /* descriptor bumping macros */
73 #define XXD(x, max_mask)              ((x) & (max_mask))
74 #define TXD(x, max_mask)              XXD((x), (max_mask))
75 #define RXD(x, max_mask)              XXD((x), (max_mask))
76 #define NEXTTXD(i, max_mask)          TXD((i) + 1, (max_mask))
77 #define PREVTXD(i, max_mask)          TXD((i) - 1, (max_mask))
78 #define NEXTRXD(i, max_mask)          RXD((i) + 1, (max_mask))
79 #define PREVRXD(i, max_mask)          RXD((i) - 1, (max_mask))
80 #define NTXDACTIVE(h, t, max_mask)    TXD((t) - (h), (max_mask))
81 #define NRXDACTIVE(h, t, max_mask)    RXD((t) - (h), (max_mask))
82
83 /* Length of BCM header at start of SPU msg, in bytes */
84 #define BCM_HDR_LEN  8
85
86 /*
87  * PDC driver reserves ringset 0 on each SPU for its own use. The driver does
88  * not currently support use of multiple ringsets on a single PDC engine.
89  */
90 #define PDC_RINGSET  0
91
92 /*
93  * Interrupt mask and status definitions. Enable interrupts for tx and rx on
94  * ring 0
95  */
96 #define PDC_XMTINT_0         (24 + PDC_RINGSET)
97 #define PDC_RCVINT_0         (16 + PDC_RINGSET)
98 #define PDC_XMTINTEN_0       BIT(PDC_XMTINT_0)
99 #define PDC_RCVINTEN_0       BIT(PDC_RCVINT_0)
100 #define PDC_INTMASK  (PDC_XMTINTEN_0 | PDC_RCVINTEN_0)
101 #define PDC_LAZY_FRAMECOUNT  1
102 #define PDC_LAZY_TIMEOUT     10000
103 #define PDC_LAZY_INT  (PDC_LAZY_TIMEOUT | (PDC_LAZY_FRAMECOUNT << 24))
104 #define PDC_INTMASK_OFFSET   0x24
105 #define PDC_INTSTATUS_OFFSET 0x20
106 #define PDC_RCVLAZY0_OFFSET  (0x30 + 4 * PDC_RINGSET)
107
108 /*
109  * For SPU2, configure MDE_CKSUM_CONTROL to write 17 bytes of metadata
110  * before frame
111  */
112 #define PDC_SPU2_RESP_HDR_LEN  17
113 #define PDC_CKSUM_CTRL         BIT(27)
114 #define PDC_CKSUM_CTRL_OFFSET  0x400
115
116 #define PDC_SPUM_RESP_HDR_LEN  32
117
118 /*
119  * Sets the following bits for write to transmit control reg:
120  *  0    - XmtEn - enable activity on the tx channel
121  * 11    - PtyChkDisable - parity check is disabled
122  * 20:18 - BurstLen = 3 -> 2^7 = 128 byte data reads from memory
123  */
124 #define PDC_TX_CTL              0x000C0801
125
126 /*
127  * Sets the following bits for write to receive control reg:
128  * 0     - RcvEn - enable activity on the rx channel
129  * 7:1   - RcvOffset - size in bytes of status region at start of rx frame buf
130  * 9     - SepRxHdrDescEn - place start of new frames only in descriptors
131  *                          that have StartOfFrame set
132  * 10    - OflowContinue - on rx FIFO overflow, clear rx fifo, discard all
133  *                         remaining bytes in current frame, report error
134  *                         in rx frame status for current frame
135  * 11    - PtyChkDisable - parity check is disabled
136  * 20:18 - BurstLen = 3 -> 2^7 = 128 byte data reads from memory
137  */
138 #define PDC_RX_CTL              0x000C0E01
139
140 #define CRYPTO_D64_RS0_CD_MASK   ((PDC_RING_ENTRIES * RING_ENTRY_SIZE) - 1)
141
142 /* descriptor flags */
143 #define D64_CTRL1_EOT   BIT(28) /* end of descriptor table */
144 #define D64_CTRL1_IOC   BIT(29) /* interrupt on complete */
145 #define D64_CTRL1_EOF   BIT(30) /* end of frame */
146 #define D64_CTRL1_SOF   BIT(31) /* start of frame */
147
148 #define RX_STATUS_OVERFLOW       0x00800000
149 #define RX_STATUS_LEN            0x0000FFFF
150
151 #define PDC_TXREGS_OFFSET  0x200
152 #define PDC_RXREGS_OFFSET  0x220
153
154 /* Maximum size buffer the DMA engine can handle */
155 #define PDC_DMA_BUF_MAX 16384
156
157 struct pdc_dma_map {
158         void *ctx;          /* opaque context associated with frame */
159 };
160
161 /* dma descriptor */
162 struct dma64dd {
163         u32 ctrl1;      /* misc control bits */
164         u32 ctrl2;      /* buffer count and address extension */
165         u32 addrlow;    /* memory address of the date buffer, bits 31:0 */
166         u32 addrhigh;   /* memory address of the date buffer, bits 63:32 */
167 };
168
169 /* dma registers per channel(xmt or rcv) */
170 struct dma64_regs {
171         u32  control;   /* enable, et al */
172         u32  ptr;       /* last descriptor posted to chip */
173         u32  addrlow;   /* descriptor ring base address low 32-bits */
174         u32  addrhigh;  /* descriptor ring base address bits 63:32 */
175         u32  status0;   /* last rx descriptor written by hw */
176         u32  status1;   /* driver does not use */
177 };
178
179 /* cpp contortions to concatenate w/arg prescan */
180 #ifndef PAD
181 #define _PADLINE(line)  pad ## line
182 #define _XSTR(line)     _PADLINE(line)
183 #define PAD             _XSTR(__LINE__)
184 #endif  /* PAD */
185
186 /* dma registers. matches hw layout. */
187 struct dma64 {
188         struct dma64_regs dmaxmt;  /* dma tx */
189         u32          PAD[2];
190         struct dma64_regs dmarcv;  /* dma rx */
191         u32          PAD[2];
192 };
193
194 /* PDC registers */
195 struct pdc_regs {
196         u32  devcontrol;             /* 0x000 */
197         u32  devstatus;              /* 0x004 */
198         u32  PAD;
199         u32  biststatus;             /* 0x00c */
200         u32  PAD[4];
201         u32  intstatus;              /* 0x020 */
202         u32  intmask;                /* 0x024 */
203         u32  gptimer;                /* 0x028 */
204
205         u32  PAD;
206         u32  intrcvlazy_0;           /* 0x030 */
207         u32  intrcvlazy_1;           /* 0x034 */
208         u32  intrcvlazy_2;           /* 0x038 */
209         u32  intrcvlazy_3;           /* 0x03c */
210
211         u32  PAD[48];
212         u32  removed_intrecvlazy;    /* 0x100 */
213         u32  flowctlthresh;          /* 0x104 */
214         u32  wrrthresh;              /* 0x108 */
215         u32  gmac_idle_cnt_thresh;   /* 0x10c */
216
217         u32  PAD[4];
218         u32  ifioaccessaddr;         /* 0x120 */
219         u32  ifioaccessbyte;         /* 0x124 */
220         u32  ifioaccessdata;         /* 0x128 */
221
222         u32  PAD[21];
223         u32  phyaccess;              /* 0x180 */
224         u32  PAD;
225         u32  phycontrol;             /* 0x188 */
226         u32  txqctl;                 /* 0x18c */
227         u32  rxqctl;                 /* 0x190 */
228         u32  gpioselect;             /* 0x194 */
229         u32  gpio_output_en;         /* 0x198 */
230         u32  PAD;                    /* 0x19c */
231         u32  txq_rxq_mem_ctl;        /* 0x1a0 */
232         u32  memory_ecc_status;      /* 0x1a4 */
233         u32  serdes_ctl;             /* 0x1a8 */
234         u32  serdes_status0;         /* 0x1ac */
235         u32  serdes_status1;         /* 0x1b0 */
236         u32  PAD[11];                /* 0x1b4-1dc */
237         u32  clk_ctl_st;             /* 0x1e0 */
238         u32  hw_war;                 /* 0x1e4 */
239         u32  pwrctl;                 /* 0x1e8 */
240         u32  PAD[5];
241
242 #define PDC_NUM_DMA_RINGS   4
243         struct dma64 dmaregs[PDC_NUM_DMA_RINGS];  /* 0x0200 - 0x2fc */
244
245         /* more registers follow, but we don't use them */
246 };
247
248 /* structure for allocating/freeing DMA rings */
249 struct pdc_ring_alloc {
250         dma_addr_t  dmabase; /* DMA address of start of ring */
251         void       *vbase;   /* base kernel virtual address of ring */
252         u32         size;    /* ring allocation size in bytes */
253 };
254
255 /* PDC state structure */
256 struct pdc_state {
257         /* synchronize access to this PDC state structure */
258         spinlock_t pdc_lock;
259
260         /* Index of the PDC whose state is in this structure instance */
261         u8 pdc_idx;
262
263         /* Platform device for this PDC instance */
264         struct platform_device *pdev;
265
266         /*
267          * Each PDC instance has a mailbox controller. PDC receives request
268          * messages through mailboxes, and sends response messages through the
269          * mailbox framework.
270          */
271         struct mbox_controller mbc;
272
273         unsigned int pdc_irq;
274
275         /*
276          * Last interrupt status read from PDC device. Saved in interrupt
277          * handler so the handler can clear the interrupt in the device,
278          * and the interrupt thread called later can know which interrupt
279          * bits are active.
280          */
281         unsigned long intstatus;
282
283         /* Number of bytes of receive status prior to each rx frame */
284         u32 rx_status_len;
285         /* Whether a BCM header is prepended to each frame */
286         bool use_bcm_hdr;
287         /* Sum of length of BCM header and rx status header */
288         u32 pdc_resp_hdr_len;
289
290         /* The base virtual address of DMA hw registers */
291         void __iomem *pdc_reg_vbase;
292
293         /* Pool for allocation of DMA rings */
294         struct dma_pool *ring_pool;
295
296         /* Pool for allocation of metadata buffers for response messages */
297         struct dma_pool *rx_buf_pool;
298
299         /*
300          * The base virtual address of DMA tx/rx descriptor rings. Corresponding
301          * DMA address and size of ring allocation.
302          */
303         struct pdc_ring_alloc tx_ring_alloc;
304         struct pdc_ring_alloc rx_ring_alloc;
305
306         struct pdc_regs *regs;    /* start of PDC registers */
307
308         struct dma64_regs *txregs_64; /* dma tx engine registers */
309         struct dma64_regs *rxregs_64; /* dma rx engine registers */
310
311         /*
312          * Arrays of PDC_RING_ENTRIES descriptors
313          * To use multiple ringsets, this needs to be extended
314          */
315         struct dma64dd   *txd_64;  /* tx descriptor ring */
316         struct dma64dd   *rxd_64;  /* rx descriptor ring */
317
318         /* descriptor ring sizes */
319         u32      ntxd;       /* # tx descriptors */
320         u32      nrxd;       /* # rx descriptors */
321         u32      nrxpost;    /* # rx buffers to keep posted */
322         u32      ntxpost;    /* max number of tx buffers that can be posted */
323
324         /*
325          * Index of next tx descriptor to reclaim. That is, the descriptor
326          * index of the oldest tx buffer for which the host has yet to process
327          * the corresponding response.
328          */
329         u32  txin;
330
331         /*
332          * Index of the first receive descriptor for the sequence of
333          * message fragments currently under construction. Used to build up
334          * the rxin_numd count for a message. Updated to rxout when the host
335          * starts a new sequence of rx buffers for a new message.
336          */
337         u32  tx_msg_start;
338
339         /* Index of next tx descriptor to post. */
340         u32  txout;
341
342         /*
343          * Number of tx descriptors associated with the message that starts
344          * at this tx descriptor index.
345          */
346         u32      txin_numd[PDC_RING_ENTRIES];
347
348         /*
349          * Index of next rx descriptor to reclaim. This is the index of
350          * the next descriptor whose data has yet to be processed by the host.
351          */
352         u32  rxin;
353
354         /*
355          * Index of the first receive descriptor for the sequence of
356          * message fragments currently under construction. Used to build up
357          * the rxin_numd count for a message. Updated to rxout when the host
358          * starts a new sequence of rx buffers for a new message.
359          */
360         u32  rx_msg_start;
361
362         /*
363          * Saved value of current hardware rx descriptor index.
364          * The last rx buffer written by the hw is the index previous to
365          * this one.
366          */
367         u32  last_rx_curr;
368
369         /* Index of next rx descriptor to post. */
370         u32  rxout;
371
372         /*
373          * opaque context associated with frame that starts at each
374          * rx ring index.
375          */
376         void *rxp_ctx[PDC_RING_ENTRIES];
377
378         /*
379          * Scatterlists used to form request and reply frames beginning at a
380          * given ring index. Retained in order to unmap each sg after reply
381          * is processed
382          */
383         struct scatterlist *src_sg[PDC_RING_ENTRIES];
384         struct scatterlist *dst_sg[PDC_RING_ENTRIES];
385
386         /*
387          * Number of rx descriptors associated with the message that starts
388          * at this descriptor index. Not set for every index. For example,
389          * if descriptor index i points to a scatterlist with 4 entries, then
390          * the next three descriptor indexes don't have a value set.
391          */
392         u32  rxin_numd[PDC_RING_ENTRIES];
393
394         void *resp_hdr[PDC_RING_ENTRIES];
395         dma_addr_t resp_hdr_daddr[PDC_RING_ENTRIES];
396
397         struct dentry *debugfs_stats;  /* debug FS stats file for this PDC */
398
399         /* counters */
400         u32  pdc_requests;    /* number of request messages submitted */
401         u32  pdc_replies;     /* number of reply messages received */
402         u32  txnobuf;         /* count of tx ring full */
403         u32  rxnobuf;         /* count of rx ring full */
404         u32  rx_oflow;        /* count of rx overflows */
405 };
406
407 /* Global variables */
408
409 struct pdc_globals {
410         /* Actual number of SPUs in hardware, as reported by device tree */
411         u32 num_spu;
412 };
413
414 static struct pdc_globals pdcg;
415
416 /* top level debug FS directory for PDC driver */
417 static struct dentry *debugfs_dir;
418
419 static ssize_t pdc_debugfs_read(struct file *filp, char __user *ubuf,
420                                 size_t count, loff_t *offp)
421 {
422         struct pdc_state *pdcs;
423         char *buf;
424         ssize_t ret, out_offset, out_count;
425
426         out_count = 512;
427
428         buf = kmalloc(out_count, GFP_KERNEL);
429         if (!buf)
430                 return -ENOMEM;
431
432         pdcs = filp->private_data;
433         out_offset = 0;
434         out_offset += snprintf(buf + out_offset, out_count - out_offset,
435                                "SPU %u stats:\n", pdcs->pdc_idx);
436         out_offset += snprintf(buf + out_offset, out_count - out_offset,
437                                "PDC requests............%u\n",
438                                pdcs->pdc_requests);
439         out_offset += snprintf(buf + out_offset, out_count - out_offset,
440                                "PDC responses...........%u\n",
441                                pdcs->pdc_replies);
442         out_offset += snprintf(buf + out_offset, out_count - out_offset,
443                                "Tx err ring full........%u\n",
444                                pdcs->txnobuf);
445         out_offset += snprintf(buf + out_offset, out_count - out_offset,
446                                "Rx err ring full........%u\n",
447                                pdcs->rxnobuf);
448         out_offset += snprintf(buf + out_offset, out_count - out_offset,
449                                "Receive overflow........%u\n",
450                                pdcs->rx_oflow);
451
452         if (out_offset > out_count)
453                 out_offset = out_count;
454
455         ret = simple_read_from_buffer(ubuf, count, offp, buf, out_offset);
456         kfree(buf);
457         return ret;
458 }
459
460 static const struct file_operations pdc_debugfs_stats = {
461         .owner = THIS_MODULE,
462         .open = simple_open,
463         .read = pdc_debugfs_read,
464 };
465
466 /**
467  * pdc_setup_debugfs() - Create the debug FS directories. If the top-level
468  * directory has not yet been created, create it now. Create a stats file in
469  * this directory for a SPU.
470  * @pdcs: PDC state structure
471  */
472 static void pdc_setup_debugfs(struct pdc_state *pdcs)
473 {
474         char spu_stats_name[16];
475
476         if (!debugfs_initialized())
477                 return;
478
479         snprintf(spu_stats_name, 16, "pdc%d_stats", pdcs->pdc_idx);
480         if (!debugfs_dir)
481                 debugfs_dir = debugfs_create_dir(KBUILD_MODNAME, NULL);
482
483         /* S_IRUSR == 0400 */
484         pdcs->debugfs_stats = debugfs_create_file(spu_stats_name, 0400,
485                                                   debugfs_dir, pdcs,
486                                                   &pdc_debugfs_stats);
487 }
488
489 static void pdc_free_debugfs(void)
490 {
491         if (debugfs_dir && simple_empty(debugfs_dir)) {
492                 debugfs_remove_recursive(debugfs_dir);
493                 debugfs_dir = NULL;
494         }
495 }
496
497 /**
498  * pdc_build_rxd() - Build DMA descriptor to receive SPU result.
499  * @pdcs:      PDC state for SPU that will generate result
500  * @dma_addr:  DMA address of buffer that descriptor is being built for
501  * @buf_len:   Length of the receive buffer, in bytes
502  * @flags:     Flags to be stored in descriptor
503  */
504 static inline void
505 pdc_build_rxd(struct pdc_state *pdcs, dma_addr_t dma_addr,
506               u32 buf_len, u32 flags)
507 {
508         struct device *dev = &pdcs->pdev->dev;
509
510         dev_dbg(dev,
511                 "Writing rx descriptor for PDC %u at index %u with length %u. flags %#x\n",
512                 pdcs->pdc_idx, pdcs->rxout, buf_len, flags);
513
514         iowrite32(lower_32_bits(dma_addr),
515                   (void *)&pdcs->rxd_64[pdcs->rxout].addrlow);
516         iowrite32(upper_32_bits(dma_addr),
517                   (void *)&pdcs->rxd_64[pdcs->rxout].addrhigh);
518         iowrite32(flags, (void *)&pdcs->rxd_64[pdcs->rxout].ctrl1);
519         iowrite32(buf_len, (void *)&pdcs->rxd_64[pdcs->rxout].ctrl2);
520         /* bump ring index and return */
521         pdcs->rxout = NEXTRXD(pdcs->rxout, pdcs->nrxpost);
522 }
523
524 /**
525  * pdc_build_txd() - Build a DMA descriptor to transmit a SPU request to
526  * hardware.
527  * @pdcs:        PDC state for the SPU that will process this request
528  * @dma_addr:    DMA address of packet to be transmitted
529  * @buf_len:     Length of tx buffer, in bytes
530  * @flags:       Flags to be stored in descriptor
531  */
532 static inline void
533 pdc_build_txd(struct pdc_state *pdcs, dma_addr_t dma_addr, u32 buf_len,
534               u32 flags)
535 {
536         struct device *dev = &pdcs->pdev->dev;
537
538         dev_dbg(dev,
539                 "Writing tx descriptor for PDC %u at index %u with length %u, flags %#x\n",
540                 pdcs->pdc_idx, pdcs->txout, buf_len, flags);
541
542         iowrite32(lower_32_bits(dma_addr),
543                   (void *)&pdcs->txd_64[pdcs->txout].addrlow);
544         iowrite32(upper_32_bits(dma_addr),
545                   (void *)&pdcs->txd_64[pdcs->txout].addrhigh);
546         iowrite32(flags, (void *)&pdcs->txd_64[pdcs->txout].ctrl1);
547         iowrite32(buf_len, (void *)&pdcs->txd_64[pdcs->txout].ctrl2);
548
549         /* bump ring index and return */
550         pdcs->txout = NEXTTXD(pdcs->txout, pdcs->ntxpost);
551 }
552
553 /**
554  * pdc_receive() - Receive a response message from a given SPU.
555  * @pdcs:    PDC state for the SPU to receive from
556  * @mssg:    mailbox message to be returned to client
557  *
558  * When the return code indicates success, the response message is available in
559  * the receive buffers provided prior to submission of the request.
560  *
561  * Input:
562  *   pdcs - PDC state structure for the SPU to be polled
563  *   mssg - mailbox message to be returned to client. This function sets the
564  *          context pointer on the message to help the client associate the
565  *          response with a request.
566  *
567  * Return:  PDC_SUCCESS if one or more receive descriptors was processed
568  *          -EAGAIN indicates that no response message is available
569  *          -EIO an error occurred
570  */
571 static int
572 pdc_receive(struct pdc_state *pdcs, struct brcm_message *mssg)
573 {
574         struct device *dev = &pdcs->pdev->dev;
575         u32 len, rx_status;
576         u32 num_frags;
577         int i;
578         u8 *resp_hdr;    /* virtual addr of start of resp message DMA header */
579         u32 frags_rdy;   /* number of fragments ready to read */
580         u32 rx_idx;      /* ring index of start of receive frame */
581         dma_addr_t resp_hdr_daddr;
582
583         spin_lock(&pdcs->pdc_lock);
584
585         /*
586          * return if a complete response message is not yet ready.
587          * rxin_numd[rxin] is the number of fragments in the next msg
588          * to read.
589          */
590         frags_rdy = NRXDACTIVE(pdcs->rxin, pdcs->last_rx_curr, pdcs->nrxpost);
591         if ((frags_rdy == 0) || (frags_rdy < pdcs->rxin_numd[pdcs->rxin])) {
592                 /* See if the hw has written more fragments than we know */
593                 pdcs->last_rx_curr =
594                     (ioread32((void *)&pdcs->rxregs_64->status0) &
595                      CRYPTO_D64_RS0_CD_MASK) / RING_ENTRY_SIZE;
596                 frags_rdy = NRXDACTIVE(pdcs->rxin, pdcs->last_rx_curr,
597                                        pdcs->nrxpost);
598                 if ((frags_rdy == 0) ||
599                     (frags_rdy < pdcs->rxin_numd[pdcs->rxin])) {
600                         /* No response ready */
601                         spin_unlock(&pdcs->pdc_lock);
602                         return -EAGAIN;
603                 }
604                 /* can't read descriptors/data until write index is read */
605                 rmb();
606         }
607
608         num_frags = pdcs->txin_numd[pdcs->txin];
609         dma_unmap_sg(dev, pdcs->src_sg[pdcs->txin],
610                      sg_nents(pdcs->src_sg[pdcs->txin]), DMA_TO_DEVICE);
611
612         for (i = 0; i < num_frags; i++)
613                 pdcs->txin = NEXTTXD(pdcs->txin, pdcs->ntxpost);
614
615         dev_dbg(dev, "PDC %u reclaimed %d tx descriptors",
616                 pdcs->pdc_idx, num_frags);
617
618         rx_idx = pdcs->rxin;
619         num_frags = pdcs->rxin_numd[rx_idx];
620         /* Return opaque context with result */
621         mssg->ctx = pdcs->rxp_ctx[rx_idx];
622         pdcs->rxp_ctx[rx_idx] = NULL;
623         resp_hdr = pdcs->resp_hdr[rx_idx];
624         resp_hdr_daddr = pdcs->resp_hdr_daddr[rx_idx];
625         dma_unmap_sg(dev, pdcs->dst_sg[rx_idx],
626                      sg_nents(pdcs->dst_sg[rx_idx]), DMA_FROM_DEVICE);
627
628         for (i = 0; i < num_frags; i++)
629                 pdcs->rxin = NEXTRXD(pdcs->rxin, pdcs->nrxpost);
630
631         spin_unlock(&pdcs->pdc_lock);
632
633         dev_dbg(dev, "PDC %u reclaimed %d rx descriptors",
634                 pdcs->pdc_idx, num_frags);
635
636         dev_dbg(dev,
637                 "PDC %u txin %u, txout %u, rxin %u, rxout %u, last_rx_curr %u\n",
638                 pdcs->pdc_idx, pdcs->txin, pdcs->txout, pdcs->rxin,
639                 pdcs->rxout, pdcs->last_rx_curr);
640
641         if (pdcs->pdc_resp_hdr_len == PDC_SPUM_RESP_HDR_LEN) {
642                 /*
643                  * For SPU-M, get length of response msg and rx overflow status.
644                  */
645                 rx_status = *((u32 *)resp_hdr);
646                 len = rx_status & RX_STATUS_LEN;
647                 dev_dbg(dev,
648                         "SPU response length %u bytes", len);
649                 if (unlikely(((rx_status & RX_STATUS_OVERFLOW) || (!len)))) {
650                         if (rx_status & RX_STATUS_OVERFLOW) {
651                                 dev_err_ratelimited(dev,
652                                                     "crypto receive overflow");
653                                 pdcs->rx_oflow++;
654                         } else {
655                                 dev_info_ratelimited(dev, "crypto rx len = 0");
656                         }
657                         return -EIO;
658                 }
659         }
660
661         dma_pool_free(pdcs->rx_buf_pool, resp_hdr, resp_hdr_daddr);
662
663         pdcs->pdc_replies++;
664         /* if we read one or more rx descriptors, claim success */
665         if (num_frags > 0)
666                 return PDC_SUCCESS;
667         else
668                 return -EIO;
669 }
670
671 /**
672  * pdc_tx_list_sg_add() - Add the buffers in a scatterlist to the transmit
673  * descriptors for a given SPU. The scatterlist buffers contain the data for a
674  * SPU request message.
675  * @spu_idx:   The index of the SPU to submit the request to, [0, max_spu)
676  * @sg:        Scatterlist whose buffers contain part of the SPU request
677  *
678  * If a scatterlist buffer is larger than PDC_DMA_BUF_MAX, multiple descriptors
679  * are written for that buffer, each <= PDC_DMA_BUF_MAX byte in length.
680  *
681  * Return: PDC_SUCCESS if successful
682  *         < 0 otherwise
683  */
684 static int pdc_tx_list_sg_add(struct pdc_state *pdcs, struct scatterlist *sg)
685 {
686         u32 flags = 0;
687         u32 eot;
688         u32 tx_avail;
689
690         /*
691          * Num descriptors needed. Conservatively assume we need a descriptor
692          * for every entry in sg.
693          */
694         u32 num_desc;
695         u32 desc_w = 0; /* Number of tx descriptors written */
696         u32 bufcnt;     /* Number of bytes of buffer pointed to by descriptor */
697         dma_addr_t databufptr;  /* DMA address to put in descriptor */
698
699         num_desc = (u32)sg_nents(sg);
700
701         /* check whether enough tx descriptors are available */
702         tx_avail = pdcs->ntxpost - NTXDACTIVE(pdcs->txin, pdcs->txout,
703                                               pdcs->ntxpost);
704         if (unlikely(num_desc > tx_avail)) {
705                 pdcs->txnobuf++;
706                 return -ENOSPC;
707         }
708
709         /* build tx descriptors */
710         if (pdcs->tx_msg_start == pdcs->txout) {
711                 /* Start of frame */
712                 pdcs->txin_numd[pdcs->tx_msg_start] = 0;
713                 pdcs->src_sg[pdcs->txout] = sg;
714                 flags = D64_CTRL1_SOF;
715         }
716
717         while (sg) {
718                 if (unlikely(pdcs->txout == (pdcs->ntxd - 1)))
719                         eot = D64_CTRL1_EOT;
720                 else
721                         eot = 0;
722
723                 /*
724                  * If sg buffer larger than PDC limit, split across
725                  * multiple descriptors
726                  */
727                 bufcnt = sg_dma_len(sg);
728                 databufptr = sg_dma_address(sg);
729                 while (bufcnt > PDC_DMA_BUF_MAX) {
730                         pdc_build_txd(pdcs, databufptr, PDC_DMA_BUF_MAX,
731                                       flags | eot);
732                         desc_w++;
733                         bufcnt -= PDC_DMA_BUF_MAX;
734                         databufptr += PDC_DMA_BUF_MAX;
735                         if (unlikely(pdcs->txout == (pdcs->ntxd - 1)))
736                                 eot = D64_CTRL1_EOT;
737                         else
738                                 eot = 0;
739                 }
740                 sg = sg_next(sg);
741                 if (!sg)
742                         /* Writing last descriptor for frame */
743                         flags |= (D64_CTRL1_EOF | D64_CTRL1_IOC);
744                 pdc_build_txd(pdcs, databufptr, bufcnt, flags | eot);
745                 desc_w++;
746                 /* Clear start of frame after first descriptor */
747                 flags &= ~D64_CTRL1_SOF;
748         }
749         pdcs->txin_numd[pdcs->tx_msg_start] += desc_w;
750
751         return PDC_SUCCESS;
752 }
753
754 /**
755  * pdc_tx_list_final() - Initiate DMA transfer of last frame written to tx
756  * ring.
757  * @pdcs:  PDC state for SPU to process the request
758  *
759  * Sets the index of the last descriptor written in both the rx and tx ring.
760  *
761  * Return: PDC_SUCCESS
762  */
763 static int pdc_tx_list_final(struct pdc_state *pdcs)
764 {
765         /*
766          * write barrier to ensure all register writes are complete
767          * before chip starts to process new request
768          */
769         wmb();
770         iowrite32(pdcs->rxout << 4, (void *)&pdcs->rxregs_64->ptr);
771         iowrite32(pdcs->txout << 4, (void *)&pdcs->txregs_64->ptr);
772         pdcs->pdc_requests++;
773
774         return PDC_SUCCESS;
775 }
776
777 /**
778  * pdc_rx_list_init() - Start a new receive descriptor list for a given PDC.
779  * @pdcs:   PDC state for SPU handling request
780  * @dst_sg: scatterlist providing rx buffers for response to be returned to
781  *          mailbox client
782  * @ctx:    Opaque context for this request
783  *
784  * Posts a single receive descriptor to hold the metadata that precedes a
785  * response. For example, with SPU-M, the metadata is a 32-byte DMA header and
786  * an 8-byte BCM header. Moves the msg_start descriptor indexes for both tx and
787  * rx to indicate the start of a new message.
788  *
789  * Return:  PDC_SUCCESS if successful
790  *          < 0 if an error (e.g., rx ring is full)
791  */
792 static int pdc_rx_list_init(struct pdc_state *pdcs, struct scatterlist *dst_sg,
793                             void *ctx)
794 {
795         u32 flags = 0;
796         u32 rx_avail;
797         u32 rx_pkt_cnt = 1;     /* Adding a single rx buffer */
798         dma_addr_t daddr;
799         void *vaddr;
800
801         rx_avail = pdcs->nrxpost - NRXDACTIVE(pdcs->rxin, pdcs->rxout,
802                                               pdcs->nrxpost);
803         if (unlikely(rx_pkt_cnt > rx_avail)) {
804                 pdcs->rxnobuf++;
805                 return -ENOSPC;
806         }
807
808         /* allocate a buffer for the dma rx status */
809         vaddr = dma_pool_zalloc(pdcs->rx_buf_pool, GFP_ATOMIC, &daddr);
810         if (!vaddr)
811                 return -ENOMEM;
812
813         /*
814          * Update msg_start indexes for both tx and rx to indicate the start
815          * of a new sequence of descriptor indexes that contain the fragments
816          * of the same message.
817          */
818         pdcs->rx_msg_start = pdcs->rxout;
819         pdcs->tx_msg_start = pdcs->txout;
820
821         /* This is always the first descriptor in the receive sequence */
822         flags = D64_CTRL1_SOF;
823         pdcs->rxin_numd[pdcs->rx_msg_start] = 1;
824
825         if (unlikely(pdcs->rxout == (pdcs->nrxd - 1)))
826                 flags |= D64_CTRL1_EOT;
827
828         pdcs->rxp_ctx[pdcs->rxout] = ctx;
829         pdcs->dst_sg[pdcs->rxout] = dst_sg;
830         pdcs->resp_hdr[pdcs->rxout] = vaddr;
831         pdcs->resp_hdr_daddr[pdcs->rxout] = daddr;
832         pdc_build_rxd(pdcs, daddr, pdcs->pdc_resp_hdr_len, flags);
833         return PDC_SUCCESS;
834 }
835
836 /**
837  * pdc_rx_list_sg_add() - Add the buffers in a scatterlist to the receive
838  * descriptors for a given SPU. The caller must have already DMA mapped the
839  * scatterlist.
840  * @spu_idx:    Indicates which SPU the buffers are for
841  * @sg:         Scatterlist whose buffers are added to the receive ring
842  *
843  * If a receive buffer in the scatterlist is larger than PDC_DMA_BUF_MAX,
844  * multiple receive descriptors are written, each with a buffer <=
845  * PDC_DMA_BUF_MAX.
846  *
847  * Return: PDC_SUCCESS if successful
848  *         < 0 otherwise (e.g., receive ring is full)
849  */
850 static int pdc_rx_list_sg_add(struct pdc_state *pdcs, struct scatterlist *sg)
851 {
852         u32 flags = 0;
853         u32 rx_avail;
854
855         /*
856          * Num descriptors needed. Conservatively assume we need a descriptor
857          * for every entry from our starting point in the scatterlist.
858          */
859         u32 num_desc;
860         u32 desc_w = 0; /* Number of tx descriptors written */
861         u32 bufcnt;     /* Number of bytes of buffer pointed to by descriptor */
862         dma_addr_t databufptr;  /* DMA address to put in descriptor */
863
864         num_desc = (u32)sg_nents(sg);
865
866         rx_avail = pdcs->nrxpost - NRXDACTIVE(pdcs->rxin, pdcs->rxout,
867                                               pdcs->nrxpost);
868         if (unlikely(num_desc > rx_avail)) {
869                 pdcs->rxnobuf++;
870                 return -ENOSPC;
871         }
872
873         while (sg) {
874                 if (unlikely(pdcs->rxout == (pdcs->nrxd - 1)))
875                         flags = D64_CTRL1_EOT;
876                 else
877                         flags = 0;
878
879                 /*
880                  * If sg buffer larger than PDC limit, split across
881                  * multiple descriptors
882                  */
883                 bufcnt = sg_dma_len(sg);
884                 databufptr = sg_dma_address(sg);
885                 while (bufcnt > PDC_DMA_BUF_MAX) {
886                         pdc_build_rxd(pdcs, databufptr, PDC_DMA_BUF_MAX, flags);
887                         desc_w++;
888                         bufcnt -= PDC_DMA_BUF_MAX;
889                         databufptr += PDC_DMA_BUF_MAX;
890                         if (unlikely(pdcs->rxout == (pdcs->nrxd - 1)))
891                                 flags = D64_CTRL1_EOT;
892                         else
893                                 flags = 0;
894                 }
895                 pdc_build_rxd(pdcs, databufptr, bufcnt, flags);
896                 desc_w++;
897                 sg = sg_next(sg);
898         }
899         pdcs->rxin_numd[pdcs->rx_msg_start] += desc_w;
900
901         return PDC_SUCCESS;
902 }
903
904 /**
905  * pdc_irq_handler() - Interrupt handler called in interrupt context.
906  * @irq:      Interrupt number that has fired
907  * @cookie:   PDC state for DMA engine that generated the interrupt
908  *
909  * We have to clear the device interrupt status flags here. So cache the
910  * status for later use in the thread function. Other than that, just return
911  * WAKE_THREAD to invoke the thread function.
912  *
913  * Return: IRQ_WAKE_THREAD if interrupt is ours
914  *         IRQ_NONE otherwise
915  */
916 static irqreturn_t pdc_irq_handler(int irq, void *cookie)
917 {
918         struct pdc_state *pdcs = cookie;
919         u32 intstatus = ioread32(pdcs->pdc_reg_vbase + PDC_INTSTATUS_OFFSET);
920
921         if (intstatus & PDC_XMTINTEN_0)
922                 set_bit(PDC_XMTINT_0, &pdcs->intstatus);
923         if (intstatus & PDC_RCVINTEN_0)
924                 set_bit(PDC_RCVINT_0, &pdcs->intstatus);
925
926         /* Clear interrupt flags in device */
927         iowrite32(intstatus, pdcs->pdc_reg_vbase + PDC_INTSTATUS_OFFSET);
928
929         /* Wakeup IRQ thread */
930         if (pdcs && (irq == pdcs->pdc_irq) && (intstatus & PDC_INTMASK))
931                 return IRQ_WAKE_THREAD;
932
933         return IRQ_NONE;
934 }
935
936 /**
937  * pdc_irq_thread() - Function invoked on deferred thread when a DMA tx has
938  * completed or data is available to receive.
939  * @irq:    Interrupt number
940  * @cookie: PDC state for PDC that generated the interrupt
941  *
942  * On DMA tx complete, notify the mailbox client. On DMA rx complete, process
943  * as many SPU response messages as are available and send each to the mailbox
944  * client.
945  *
946  * Return: IRQ_HANDLED if we recognized and handled the interrupt
947  *         IRQ_NONE otherwise
948  */
949 static irqreturn_t pdc_irq_thread(int irq, void *cookie)
950 {
951         struct pdc_state *pdcs = cookie;
952         struct mbox_controller *mbc;
953         struct mbox_chan *chan;
954         bool tx_int;
955         bool rx_int;
956         int rx_status;
957         struct brcm_message mssg;
958
959         tx_int = test_and_clear_bit(PDC_XMTINT_0, &pdcs->intstatus);
960         rx_int = test_and_clear_bit(PDC_RCVINT_0, &pdcs->intstatus);
961
962         if (pdcs && (tx_int || rx_int)) {
963                 dev_dbg(&pdcs->pdev->dev,
964                         "%s() got irq %d with tx_int %s, rx_int %s",
965                         __func__, irq,
966                         tx_int ? "set" : "clear", rx_int ? "set" : "clear");
967
968                 mbc = &pdcs->mbc;
969                 chan = &mbc->chans[0];
970
971                 if (tx_int) {
972                         dev_dbg(&pdcs->pdev->dev, "%s(): tx done", __func__);
973                         /* only one frame in flight at a time */
974                         mbox_chan_txdone(chan, PDC_SUCCESS);
975                 }
976                 if (rx_int) {
977                         while (1) {
978                                 /* Could be many frames ready */
979                                 memset(&mssg, 0, sizeof(mssg));
980                                 mssg.type = BRCM_MESSAGE_SPU;
981                                 rx_status = pdc_receive(pdcs, &mssg);
982                                 if (rx_status >= 0) {
983                                         dev_dbg(&pdcs->pdev->dev,
984                                                 "%s(): invoking client rx cb",
985                                                 __func__);
986                                         mbox_chan_received_data(chan, &mssg);
987                                 } else {
988                                         dev_dbg(&pdcs->pdev->dev,
989                                                 "%s(): no SPU response available",
990                                                 __func__);
991                                         break;
992                                 }
993                         }
994                 }
995                 return IRQ_HANDLED;
996         }
997         return IRQ_NONE;
998 }
999
1000 /**
1001  * pdc_ring_init() - Allocate DMA rings and initialize constant fields of
1002  * descriptors in one ringset.
1003  * @pdcs:    PDC instance state
1004  * @ringset: index of ringset being used
1005  *
1006  * Return: PDC_SUCCESS if ring initialized
1007  *         < 0 otherwise
1008  */
1009 static int pdc_ring_init(struct pdc_state *pdcs, int ringset)
1010 {
1011         int i;
1012         int err = PDC_SUCCESS;
1013         struct dma64 *dma_reg;
1014         struct device *dev = &pdcs->pdev->dev;
1015         struct pdc_ring_alloc tx;
1016         struct pdc_ring_alloc rx;
1017
1018         /* Allocate tx ring */
1019         tx.vbase = dma_pool_zalloc(pdcs->ring_pool, GFP_KERNEL, &tx.dmabase);
1020         if (!tx.vbase) {
1021                 err = -ENOMEM;
1022                 goto done;
1023         }
1024
1025         /* Allocate rx ring */
1026         rx.vbase = dma_pool_zalloc(pdcs->ring_pool, GFP_KERNEL, &rx.dmabase);
1027         if (!rx.vbase) {
1028                 err = -ENOMEM;
1029                 goto fail_dealloc;
1030         }
1031
1032         dev_dbg(dev, " - base DMA addr of tx ring      %pad", &tx.dmabase);
1033         dev_dbg(dev, " - base virtual addr of tx ring  %p", tx.vbase);
1034         dev_dbg(dev, " - base DMA addr of rx ring      %pad", &rx.dmabase);
1035         dev_dbg(dev, " - base virtual addr of rx ring  %p", rx.vbase);
1036
1037         /* lock after ring allocation to avoid scheduling while atomic */
1038         spin_lock(&pdcs->pdc_lock);
1039
1040         memcpy(&pdcs->tx_ring_alloc, &tx, sizeof(tx));
1041         memcpy(&pdcs->rx_ring_alloc, &rx, sizeof(rx));
1042
1043         pdcs->rxin = 0;
1044         pdcs->rx_msg_start = 0;
1045         pdcs->last_rx_curr = 0;
1046         pdcs->rxout = 0;
1047         pdcs->txin = 0;
1048         pdcs->tx_msg_start = 0;
1049         pdcs->txout = 0;
1050
1051         /* Set descriptor array base addresses */
1052         pdcs->txd_64 = (struct dma64dd *)pdcs->tx_ring_alloc.vbase;
1053         pdcs->rxd_64 = (struct dma64dd *)pdcs->rx_ring_alloc.vbase;
1054
1055         /* Tell device the base DMA address of each ring */
1056         dma_reg = &pdcs->regs->dmaregs[ringset];
1057         iowrite32(lower_32_bits(pdcs->tx_ring_alloc.dmabase),
1058                   (void *)&dma_reg->dmaxmt.addrlow);
1059         iowrite32(upper_32_bits(pdcs->tx_ring_alloc.dmabase),
1060                   (void *)&dma_reg->dmaxmt.addrhigh);
1061
1062         iowrite32(lower_32_bits(pdcs->rx_ring_alloc.dmabase),
1063                   (void *)&dma_reg->dmarcv.addrlow);
1064         iowrite32(upper_32_bits(pdcs->rx_ring_alloc.dmabase),
1065                   (void *)&dma_reg->dmarcv.addrhigh);
1066
1067         /* Initialize descriptors */
1068         for (i = 0; i < PDC_RING_ENTRIES; i++) {
1069                 /* Every tx descriptor can be used for start of frame. */
1070                 if (i != pdcs->ntxpost) {
1071                         iowrite32(D64_CTRL1_SOF | D64_CTRL1_EOF,
1072                                   (void *)&pdcs->txd_64[i].ctrl1);
1073                 } else {
1074                         /* Last descriptor in ringset. Set End of Table. */
1075                         iowrite32(D64_CTRL1_SOF | D64_CTRL1_EOF |
1076                                   D64_CTRL1_EOT,
1077                                   (void *)&pdcs->txd_64[i].ctrl1);
1078                 }
1079
1080                 /* Every rx descriptor can be used for start of frame */
1081                 if (i != pdcs->nrxpost) {
1082                         iowrite32(D64_CTRL1_SOF,
1083                                   (void *)&pdcs->rxd_64[i].ctrl1);
1084                 } else {
1085                         /* Last descriptor in ringset. Set End of Table. */
1086                         iowrite32(D64_CTRL1_SOF | D64_CTRL1_EOT,
1087                                   (void *)&pdcs->rxd_64[i].ctrl1);
1088                 }
1089         }
1090         spin_unlock(&pdcs->pdc_lock);
1091         return PDC_SUCCESS;
1092
1093 fail_dealloc:
1094         dma_pool_free(pdcs->ring_pool, tx.vbase, tx.dmabase);
1095 done:
1096         return err;
1097 }
1098
1099 static void pdc_ring_free(struct pdc_state *pdcs)
1100 {
1101         if (pdcs->tx_ring_alloc.vbase) {
1102                 dma_pool_free(pdcs->ring_pool, pdcs->tx_ring_alloc.vbase,
1103                               pdcs->tx_ring_alloc.dmabase);
1104                 pdcs->tx_ring_alloc.vbase = NULL;
1105         }
1106
1107         if (pdcs->rx_ring_alloc.vbase) {
1108                 dma_pool_free(pdcs->ring_pool, pdcs->rx_ring_alloc.vbase,
1109                               pdcs->rx_ring_alloc.dmabase);
1110                 pdcs->rx_ring_alloc.vbase = NULL;
1111         }
1112 }
1113
1114 /**
1115  * pdc_send_data() - mailbox send_data function
1116  * @chan:       The mailbox channel on which the data is sent. The channel
1117  *              corresponds to a DMA ringset.
1118  * @data:       The mailbox message to be sent. The message must be a
1119  *              brcm_message structure.
1120  *
1121  * This function is registered as the send_data function for the mailbox
1122  * controller. From the destination scatterlist in the mailbox message, it
1123  * creates a sequence of receive descriptors in the rx ring. From the source
1124  * scatterlist, it creates a sequence of transmit descriptors in the tx ring.
1125  * After creating the descriptors, it writes the rx ptr and tx ptr registers to
1126  * initiate the DMA transfer.
1127  *
1128  * This function does the DMA map and unmap of the src and dst scatterlists in
1129  * the mailbox message.
1130  *
1131  * Return: 0 if successful
1132  *         -ENOTSUPP if the mailbox message is a type this driver does not
1133  *                      support
1134  *         < 0 if an error
1135  */
1136 static int pdc_send_data(struct mbox_chan *chan, void *data)
1137 {
1138         struct pdc_state *pdcs = chan->con_priv;
1139         struct device *dev = &pdcs->pdev->dev;
1140         struct brcm_message *mssg = data;
1141         int err = PDC_SUCCESS;
1142         int src_nent;
1143         int dst_nent;
1144         int nent;
1145
1146         if (mssg->type != BRCM_MESSAGE_SPU)
1147                 return -ENOTSUPP;
1148
1149         src_nent = sg_nents(mssg->spu.src);
1150         if (src_nent) {
1151                 nent = dma_map_sg(dev, mssg->spu.src, src_nent, DMA_TO_DEVICE);
1152                 if (nent == 0)
1153                         return -EIO;
1154         }
1155
1156         dst_nent = sg_nents(mssg->spu.dst);
1157         if (dst_nent) {
1158                 nent = dma_map_sg(dev, mssg->spu.dst, dst_nent,
1159                                   DMA_FROM_DEVICE);
1160                 if (nent == 0) {
1161                         dma_unmap_sg(dev, mssg->spu.src, src_nent,
1162                                      DMA_TO_DEVICE);
1163                         return -EIO;
1164                 }
1165         }
1166
1167         spin_lock(&pdcs->pdc_lock);
1168
1169         /* Create rx descriptors to SPU catch response */
1170         err = pdc_rx_list_init(pdcs, mssg->spu.dst, mssg->ctx);
1171         err |= pdc_rx_list_sg_add(pdcs, mssg->spu.dst);
1172
1173         /* Create tx descriptors to submit SPU request */
1174         err |= pdc_tx_list_sg_add(pdcs, mssg->spu.src);
1175         err |= pdc_tx_list_final(pdcs); /* initiate transfer */
1176
1177         spin_unlock(&pdcs->pdc_lock);
1178
1179         if (err)
1180                 dev_err(&pdcs->pdev->dev,
1181                         "%s failed with error %d", __func__, err);
1182
1183         return err;
1184 }
1185
1186 static int pdc_startup(struct mbox_chan *chan)
1187 {
1188         return pdc_ring_init(chan->con_priv, PDC_RINGSET);
1189 }
1190
1191 static void pdc_shutdown(struct mbox_chan *chan)
1192 {
1193         struct pdc_state *pdcs = chan->con_priv;
1194
1195         if (!pdcs)
1196                 return;
1197
1198         dev_dbg(&pdcs->pdev->dev,
1199                 "Shutdown mailbox channel for PDC %u", pdcs->pdc_idx);
1200         pdc_ring_free(pdcs);
1201 }
1202
1203 /**
1204  * pdc_hw_init() - Use the given initialization parameters to initialize the
1205  * state for one of the PDCs.
1206  * @pdcs:  state of the PDC
1207  */
1208 static
1209 void pdc_hw_init(struct pdc_state *pdcs)
1210 {
1211         struct platform_device *pdev;
1212         struct device *dev;
1213         struct dma64 *dma_reg;
1214         int ringset = PDC_RINGSET;
1215
1216         pdev = pdcs->pdev;
1217         dev = &pdev->dev;
1218
1219         dev_dbg(dev, "PDC %u initial values:", pdcs->pdc_idx);
1220         dev_dbg(dev, "state structure:                   %p",
1221                 pdcs);
1222         dev_dbg(dev, " - base virtual addr of hw regs    %p",
1223                 pdcs->pdc_reg_vbase);
1224
1225         /* initialize data structures */
1226         pdcs->regs = (struct pdc_regs *)pdcs->pdc_reg_vbase;
1227         pdcs->txregs_64 = (struct dma64_regs *)
1228             (void *)(((u8 *)pdcs->pdc_reg_vbase) +
1229                      PDC_TXREGS_OFFSET + (sizeof(struct dma64) * ringset));
1230         pdcs->rxregs_64 = (struct dma64_regs *)
1231             (void *)(((u8 *)pdcs->pdc_reg_vbase) +
1232                      PDC_RXREGS_OFFSET + (sizeof(struct dma64) * ringset));
1233
1234         pdcs->ntxd = PDC_RING_ENTRIES;
1235         pdcs->nrxd = PDC_RING_ENTRIES;
1236         pdcs->ntxpost = PDC_RING_ENTRIES - 1;
1237         pdcs->nrxpost = PDC_RING_ENTRIES - 1;
1238         pdcs->regs->intmask = 0;
1239
1240         dma_reg = &pdcs->regs->dmaregs[ringset];
1241         iowrite32(0, (void *)&dma_reg->dmaxmt.ptr);
1242         iowrite32(0, (void *)&dma_reg->dmarcv.ptr);
1243
1244         iowrite32(PDC_TX_CTL, (void *)&dma_reg->dmaxmt.control);
1245
1246         iowrite32(PDC_RX_CTL + (pdcs->rx_status_len << 1),
1247                   (void *)&dma_reg->dmarcv.control);
1248
1249         if (pdcs->pdc_resp_hdr_len == PDC_SPU2_RESP_HDR_LEN)
1250                 iowrite32(PDC_CKSUM_CTRL,
1251                           pdcs->pdc_reg_vbase + PDC_CKSUM_CTRL_OFFSET);
1252 }
1253
1254 /**
1255  * pdc_rx_buf_pool_create() - Pool of receive buffers used to catch the metadata
1256  * header returned with each response message.
1257  * @pdcs: PDC state structure
1258  *
1259  * The metadata is not returned to the mailbox client. So the PDC driver
1260  * manages these buffers.
1261  *
1262  * Return: PDC_SUCCESS
1263  *         -ENOMEM if pool creation fails
1264  */
1265 static int pdc_rx_buf_pool_create(struct pdc_state *pdcs)
1266 {
1267         struct platform_device *pdev;
1268         struct device *dev;
1269
1270         pdev = pdcs->pdev;
1271         dev = &pdev->dev;
1272
1273         pdcs->pdc_resp_hdr_len = pdcs->rx_status_len;
1274         if (pdcs->use_bcm_hdr)
1275                 pdcs->pdc_resp_hdr_len += BCM_HDR_LEN;
1276
1277         pdcs->rx_buf_pool = dma_pool_create("pdc rx bufs", dev,
1278                                             pdcs->pdc_resp_hdr_len,
1279                                             RX_BUF_ALIGN, 0);
1280         if (!pdcs->rx_buf_pool)
1281                 return -ENOMEM;
1282
1283         return PDC_SUCCESS;
1284 }
1285
1286 /**
1287  * pdc_interrupts_init() - Initialize the interrupt configuration for a PDC and
1288  * specify a threaded IRQ handler for deferred handling of interrupts outside of
1289  * interrupt context.
1290  * @pdcs:   PDC state
1291  *
1292  * Set the interrupt mask for transmit and receive done.
1293  * Set the lazy interrupt frame count to generate an interrupt for just one pkt.
1294  *
1295  * Return:  PDC_SUCCESS
1296  *          <0 if threaded irq request fails
1297  */
1298 static int pdc_interrupts_init(struct pdc_state *pdcs)
1299 {
1300         struct platform_device *pdev = pdcs->pdev;
1301         struct device *dev = &pdev->dev;
1302         struct device_node *dn = pdev->dev.of_node;
1303         int err;
1304
1305         pdcs->intstatus = 0;
1306
1307         /* interrupt configuration */
1308         iowrite32(PDC_INTMASK, pdcs->pdc_reg_vbase + PDC_INTMASK_OFFSET);
1309         iowrite32(PDC_LAZY_INT, pdcs->pdc_reg_vbase + PDC_RCVLAZY0_OFFSET);
1310
1311         /* read irq from device tree */
1312         pdcs->pdc_irq = irq_of_parse_and_map(dn, 0);
1313         dev_dbg(dev, "pdc device %s irq %u for pdcs %p",
1314                 dev_name(dev), pdcs->pdc_irq, pdcs);
1315         err = devm_request_threaded_irq(dev, pdcs->pdc_irq,
1316                                         pdc_irq_handler,
1317                                         pdc_irq_thread, 0, dev_name(dev), pdcs);
1318         if (err) {
1319                 dev_err(dev, "threaded tx IRQ %u request failed with err %d\n",
1320                         pdcs->pdc_irq, err);
1321                 return err;
1322         }
1323         return PDC_SUCCESS;
1324 }
1325
1326 static const struct mbox_chan_ops pdc_mbox_chan_ops = {
1327         .send_data = pdc_send_data,
1328         .startup = pdc_startup,
1329         .shutdown = pdc_shutdown
1330 };
1331
1332 /**
1333  * pdc_mb_init() - Initialize the mailbox controller.
1334  * @pdcs:  PDC state
1335  *
1336  * Each PDC is a mailbox controller. Each ringset is a mailbox channel. Kernel
1337  * driver only uses one ringset and thus one mb channel. PDC uses the transmit
1338  * complete interrupt to determine when a mailbox message has successfully been
1339  * transmitted.
1340  *
1341  * Return: 0 on success
1342  *         < 0 if there is an allocation or registration failure
1343  */
1344 static int pdc_mb_init(struct pdc_state *pdcs)
1345 {
1346         struct device *dev = &pdcs->pdev->dev;
1347         struct mbox_controller *mbc;
1348         int chan_index;
1349         int err;
1350
1351         mbc = &pdcs->mbc;
1352         mbc->dev = dev;
1353         mbc->ops = &pdc_mbox_chan_ops;
1354         mbc->num_chans = 1;
1355         mbc->chans = devm_kcalloc(dev, mbc->num_chans, sizeof(*mbc->chans),
1356                                   GFP_KERNEL);
1357         if (!mbc->chans)
1358                 return -ENOMEM;
1359
1360         mbc->txdone_irq = true;
1361         mbc->txdone_poll = false;
1362         for (chan_index = 0; chan_index < mbc->num_chans; chan_index++)
1363                 mbc->chans[chan_index].con_priv = pdcs;
1364
1365         /* Register mailbox controller */
1366         err = mbox_controller_register(mbc);
1367         if (err) {
1368                 dev_crit(dev,
1369                          "Failed to register PDC mailbox controller. Error %d.",
1370                          err);
1371                 return err;
1372         }
1373         return 0;
1374 }
1375
1376 /**
1377  * pdc_dt_read() - Read application-specific data from device tree.
1378  * @pdev:  Platform device
1379  * @pdcs:  PDC state
1380  *
1381  * Reads the number of bytes of receive status that precede each received frame.
1382  * Reads whether transmit and received frames should be preceded by an 8-byte
1383  * BCM header.
1384  *
1385  * Return: 0 if successful
1386  *         -ENODEV if device not available
1387  */
1388 static int pdc_dt_read(struct platform_device *pdev, struct pdc_state *pdcs)
1389 {
1390         struct device *dev = &pdev->dev;
1391         struct device_node *dn = pdev->dev.of_node;
1392         int err;
1393
1394         err = of_property_read_u32(dn, "brcm,rx-status-len",
1395                                    &pdcs->rx_status_len);
1396         if (err < 0)
1397                 dev_err(dev,
1398                         "%s failed to get DMA receive status length from device tree",
1399                         __func__);
1400
1401         pdcs->use_bcm_hdr = of_property_read_bool(dn, "brcm,use-bcm-hdr");
1402
1403         return 0;
1404 }
1405
1406 /**
1407  * pdc_probe() - Probe function for PDC driver.
1408  * @pdev:   PDC platform device
1409  *
1410  * Reserve and map register regions defined in device tree.
1411  * Allocate and initialize tx and rx DMA rings.
1412  * Initialize a mailbox controller for each PDC.
1413  *
1414  * Return: 0 if successful
1415  *         < 0 if an error
1416  */
1417 static int pdc_probe(struct platform_device *pdev)
1418 {
1419         int err = 0;
1420         struct device *dev = &pdev->dev;
1421         struct resource *pdc_regs;
1422         struct pdc_state *pdcs;
1423
1424         /* PDC state for one SPU */
1425         pdcs = devm_kzalloc(dev, sizeof(*pdcs), GFP_KERNEL);
1426         if (!pdcs) {
1427                 err = -ENOMEM;
1428                 goto cleanup;
1429         }
1430
1431         spin_lock_init(&pdcs->pdc_lock);
1432         pdcs->pdev = pdev;
1433         platform_set_drvdata(pdev, pdcs);
1434         pdcs->pdc_idx = pdcg.num_spu;
1435         pdcg.num_spu++;
1436
1437         err = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32));
1438         if (err) {
1439                 dev_warn(dev, "PDC device cannot perform DMA. Error %d.", err);
1440                 goto cleanup;
1441         }
1442
1443         /* Create DMA pool for tx ring */
1444         pdcs->ring_pool = dma_pool_create("pdc rings", dev, PDC_RING_SIZE,
1445                                           RING_ALIGN, 0);
1446         if (!pdcs->ring_pool) {
1447                 err = -ENOMEM;
1448                 goto cleanup;
1449         }
1450
1451         err = pdc_dt_read(pdev, pdcs);
1452         if (err)
1453                 goto cleanup_ring_pool;
1454
1455         pdc_regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1456         if (!pdc_regs) {
1457                 err = -ENODEV;
1458                 goto cleanup_ring_pool;
1459         }
1460         dev_dbg(dev, "PDC register region res.start = %pa, res.end = %pa",
1461                 &pdc_regs->start, &pdc_regs->end);
1462
1463         pdcs->pdc_reg_vbase = devm_ioremap_resource(&pdev->dev, pdc_regs);
1464         if (IS_ERR(pdcs->pdc_reg_vbase)) {
1465                 err = PTR_ERR(pdcs->pdc_reg_vbase);
1466                 dev_err(&pdev->dev, "Failed to map registers: %d\n", err);
1467                 goto cleanup_ring_pool;
1468         }
1469
1470         /* create rx buffer pool after dt read to know how big buffers are */
1471         err = pdc_rx_buf_pool_create(pdcs);
1472         if (err)
1473                 goto cleanup_ring_pool;
1474
1475         pdc_hw_init(pdcs);
1476
1477         err = pdc_interrupts_init(pdcs);
1478         if (err)
1479                 goto cleanup_buf_pool;
1480
1481         /* Initialize mailbox controller */
1482         err = pdc_mb_init(pdcs);
1483         if (err)
1484                 goto cleanup_buf_pool;
1485
1486         pdcs->debugfs_stats = NULL;
1487         pdc_setup_debugfs(pdcs);
1488
1489         dev_dbg(dev, "pdc_probe() successful");
1490         return PDC_SUCCESS;
1491
1492 cleanup_buf_pool:
1493         dma_pool_destroy(pdcs->rx_buf_pool);
1494
1495 cleanup_ring_pool:
1496         dma_pool_destroy(pdcs->ring_pool);
1497
1498 cleanup:
1499         return err;
1500 }
1501
1502 static int pdc_remove(struct platform_device *pdev)
1503 {
1504         struct pdc_state *pdcs = platform_get_drvdata(pdev);
1505
1506         pdc_free_debugfs();
1507
1508         mbox_controller_unregister(&pdcs->mbc);
1509
1510         dma_pool_destroy(pdcs->rx_buf_pool);
1511         dma_pool_destroy(pdcs->ring_pool);
1512         return 0;
1513 }
1514
1515 static const struct of_device_id pdc_mbox_of_match[] = {
1516         {.compatible = "brcm,iproc-pdc-mbox"},
1517         { /* sentinel */ }
1518 };
1519 MODULE_DEVICE_TABLE(of, pdc_mbox_of_match);
1520
1521 static struct platform_driver pdc_mbox_driver = {
1522         .probe = pdc_probe,
1523         .remove = pdc_remove,
1524         .driver = {
1525                    .name = "brcm-iproc-pdc-mbox",
1526                    .of_match_table = of_match_ptr(pdc_mbox_of_match),
1527                    },
1528 };
1529 module_platform_driver(pdc_mbox_driver);
1530
1531 MODULE_AUTHOR("Rob Rice <rob.rice@broadcom.com>");
1532 MODULE_DESCRIPTION("Broadcom PDC mailbox driver");
1533 MODULE_LICENSE("GPL v2");