crypto: hifn_795x - Fix queue processing
[linux-block.git] / drivers / crypto / hifn_795x.c
1 /*
2  * 2007+ Copyright (c) Evgeniy Polyakov <johnpol@2ka.mipt.ru>
3  * All rights reserved.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 #include <linux/kernel.h>
21 #include <linux/module.h>
22 #include <linux/moduleparam.h>
23 #include <linux/mod_devicetable.h>
24 #include <linux/interrupt.h>
25 #include <linux/pci.h>
26 #include <linux/slab.h>
27 #include <linux/delay.h>
28 #include <linux/mm.h>
29 #include <linux/dma-mapping.h>
30 #include <linux/scatterlist.h>
31 #include <linux/highmem.h>
32 #include <linux/crypto.h>
33 #include <linux/hw_random.h>
34 #include <linux/ktime.h>
35
36 #include <crypto/algapi.h>
37 #include <crypto/des.h>
38
39 #include <asm/kmap_types.h>
40
41 #undef dprintk
42
43 #define HIFN_TEST
44 //#define HIFN_DEBUG
45
46 #ifdef HIFN_DEBUG
47 #define dprintk(f, a...)        printk(f, ##a)
48 #else
49 #define dprintk(f, a...)        do {} while (0)
50 #endif
51
52 static char hifn_pll_ref[sizeof("extNNN")] = "ext";
53 module_param_string(hifn_pll_ref, hifn_pll_ref, sizeof(hifn_pll_ref), 0444);
54 MODULE_PARM_DESC(hifn_pll_ref,
55                  "PLL reference clock (pci[freq] or ext[freq], default ext)");
56
57 static atomic_t hifn_dev_number;
58
59 #define ACRYPTO_OP_DECRYPT      0
60 #define ACRYPTO_OP_ENCRYPT      1
61 #define ACRYPTO_OP_HMAC         2
62 #define ACRYPTO_OP_RNG          3
63
64 #define ACRYPTO_MODE_ECB                0
65 #define ACRYPTO_MODE_CBC                1
66 #define ACRYPTO_MODE_CFB                2
67 #define ACRYPTO_MODE_OFB                3
68
69 #define ACRYPTO_TYPE_AES_128    0
70 #define ACRYPTO_TYPE_AES_192    1
71 #define ACRYPTO_TYPE_AES_256    2
72 #define ACRYPTO_TYPE_3DES       3
73 #define ACRYPTO_TYPE_DES        4
74
75 #define PCI_VENDOR_ID_HIFN              0x13A3
76 #define PCI_DEVICE_ID_HIFN_7955         0x0020
77 #define PCI_DEVICE_ID_HIFN_7956         0x001d
78
79 /* I/O region sizes */
80
81 #define HIFN_BAR0_SIZE                  0x1000
82 #define HIFN_BAR1_SIZE                  0x2000
83 #define HIFN_BAR2_SIZE                  0x8000
84
85 /* DMA registres */
86
87 #define HIFN_DMA_CRA                    0x0C    /* DMA Command Ring Address */
88 #define HIFN_DMA_SDRA                   0x1C    /* DMA Source Data Ring Address */
89 #define HIFN_DMA_RRA                    0x2C    /* DMA Result Ring Address */
90 #define HIFN_DMA_DDRA                   0x3C    /* DMA Destination Data Ring Address */
91 #define HIFN_DMA_STCTL                  0x40    /* DMA Status and Control */
92 #define HIFN_DMA_INTREN                 0x44    /* DMA Interrupt Enable */
93 #define HIFN_DMA_CFG1                   0x48    /* DMA Configuration #1 */
94 #define HIFN_DMA_CFG2                   0x6C    /* DMA Configuration #2 */
95 #define HIFN_CHIP_ID                    0x98    /* Chip ID */
96
97 /*
98  * Processing Unit Registers (offset from BASEREG0)
99  */
100 #define HIFN_0_PUDATA           0x00    /* Processing Unit Data */
101 #define HIFN_0_PUCTRL           0x04    /* Processing Unit Control */
102 #define HIFN_0_PUISR            0x08    /* Processing Unit Interrupt Status */
103 #define HIFN_0_PUCNFG           0x0c    /* Processing Unit Configuration */
104 #define HIFN_0_PUIER            0x10    /* Processing Unit Interrupt Enable */
105 #define HIFN_0_PUSTAT           0x14    /* Processing Unit Status/Chip ID */
106 #define HIFN_0_FIFOSTAT         0x18    /* FIFO Status */
107 #define HIFN_0_FIFOCNFG         0x1c    /* FIFO Configuration */
108 #define HIFN_0_SPACESIZE        0x20    /* Register space size */
109
110 /* Processing Unit Control Register (HIFN_0_PUCTRL) */
111 #define HIFN_PUCTRL_CLRSRCFIFO  0x0010  /* clear source fifo */
112 #define HIFN_PUCTRL_STOP        0x0008  /* stop pu */
113 #define HIFN_PUCTRL_LOCKRAM     0x0004  /* lock ram */
114 #define HIFN_PUCTRL_DMAENA      0x0002  /* enable dma */
115 #define HIFN_PUCTRL_RESET       0x0001  /* Reset processing unit */
116
117 /* Processing Unit Interrupt Status Register (HIFN_0_PUISR) */
118 #define HIFN_PUISR_CMDINVAL     0x8000  /* Invalid command interrupt */
119 #define HIFN_PUISR_DATAERR      0x4000  /* Data error interrupt */
120 #define HIFN_PUISR_SRCFIFO      0x2000  /* Source FIFO ready interrupt */
121 #define HIFN_PUISR_DSTFIFO      0x1000  /* Destination FIFO ready interrupt */
122 #define HIFN_PUISR_DSTOVER      0x0200  /* Destination overrun interrupt */
123 #define HIFN_PUISR_SRCCMD       0x0080  /* Source command interrupt */
124 #define HIFN_PUISR_SRCCTX       0x0040  /* Source context interrupt */
125 #define HIFN_PUISR_SRCDATA      0x0020  /* Source data interrupt */
126 #define HIFN_PUISR_DSTDATA      0x0010  /* Destination data interrupt */
127 #define HIFN_PUISR_DSTRESULT    0x0004  /* Destination result interrupt */
128
129 /* Processing Unit Configuration Register (HIFN_0_PUCNFG) */
130 #define HIFN_PUCNFG_DRAMMASK    0xe000  /* DRAM size mask */
131 #define HIFN_PUCNFG_DSZ_256K    0x0000  /* 256k dram */
132 #define HIFN_PUCNFG_DSZ_512K    0x2000  /* 512k dram */
133 #define HIFN_PUCNFG_DSZ_1M      0x4000  /* 1m dram */
134 #define HIFN_PUCNFG_DSZ_2M      0x6000  /* 2m dram */
135 #define HIFN_PUCNFG_DSZ_4M      0x8000  /* 4m dram */
136 #define HIFN_PUCNFG_DSZ_8M      0xa000  /* 8m dram */
137 #define HIFN_PUNCFG_DSZ_16M     0xc000  /* 16m dram */
138 #define HIFN_PUCNFG_DSZ_32M     0xe000  /* 32m dram */
139 #define HIFN_PUCNFG_DRAMREFRESH 0x1800  /* DRAM refresh rate mask */
140 #define HIFN_PUCNFG_DRFR_512    0x0000  /* 512 divisor of ECLK */
141 #define HIFN_PUCNFG_DRFR_256    0x0800  /* 256 divisor of ECLK */
142 #define HIFN_PUCNFG_DRFR_128    0x1000  /* 128 divisor of ECLK */
143 #define HIFN_PUCNFG_TCALLPHASES 0x0200  /* your guess is as good as mine... */
144 #define HIFN_PUCNFG_TCDRVTOTEM  0x0100  /* your guess is as good as mine... */
145 #define HIFN_PUCNFG_BIGENDIAN   0x0080  /* DMA big endian mode */
146 #define HIFN_PUCNFG_BUS32       0x0040  /* Bus width 32bits */
147 #define HIFN_PUCNFG_BUS16       0x0000  /* Bus width 16 bits */
148 #define HIFN_PUCNFG_CHIPID      0x0020  /* Allow chipid from PUSTAT */
149 #define HIFN_PUCNFG_DRAM        0x0010  /* Context RAM is DRAM */
150 #define HIFN_PUCNFG_SRAM        0x0000  /* Context RAM is SRAM */
151 #define HIFN_PUCNFG_COMPSING    0x0004  /* Enable single compression context */
152 #define HIFN_PUCNFG_ENCCNFG     0x0002  /* Encryption configuration */
153
154 /* Processing Unit Interrupt Enable Register (HIFN_0_PUIER) */
155 #define HIFN_PUIER_CMDINVAL     0x8000  /* Invalid command interrupt */
156 #define HIFN_PUIER_DATAERR      0x4000  /* Data error interrupt */
157 #define HIFN_PUIER_SRCFIFO      0x2000  /* Source FIFO ready interrupt */
158 #define HIFN_PUIER_DSTFIFO      0x1000  /* Destination FIFO ready interrupt */
159 #define HIFN_PUIER_DSTOVER      0x0200  /* Destination overrun interrupt */
160 #define HIFN_PUIER_SRCCMD       0x0080  /* Source command interrupt */
161 #define HIFN_PUIER_SRCCTX       0x0040  /* Source context interrupt */
162 #define HIFN_PUIER_SRCDATA      0x0020  /* Source data interrupt */
163 #define HIFN_PUIER_DSTDATA      0x0010  /* Destination data interrupt */
164 #define HIFN_PUIER_DSTRESULT    0x0004  /* Destination result interrupt */
165
166 /* Processing Unit Status Register/Chip ID (HIFN_0_PUSTAT) */
167 #define HIFN_PUSTAT_CMDINVAL    0x8000  /* Invalid command interrupt */
168 #define HIFN_PUSTAT_DATAERR     0x4000  /* Data error interrupt */
169 #define HIFN_PUSTAT_SRCFIFO     0x2000  /* Source FIFO ready interrupt */
170 #define HIFN_PUSTAT_DSTFIFO     0x1000  /* Destination FIFO ready interrupt */
171 #define HIFN_PUSTAT_DSTOVER     0x0200  /* Destination overrun interrupt */
172 #define HIFN_PUSTAT_SRCCMD      0x0080  /* Source command interrupt */
173 #define HIFN_PUSTAT_SRCCTX      0x0040  /* Source context interrupt */
174 #define HIFN_PUSTAT_SRCDATA     0x0020  /* Source data interrupt */
175 #define HIFN_PUSTAT_DSTDATA     0x0010  /* Destination data interrupt */
176 #define HIFN_PUSTAT_DSTRESULT   0x0004  /* Destination result interrupt */
177 #define HIFN_PUSTAT_CHIPREV     0x00ff  /* Chip revision mask */
178 #define HIFN_PUSTAT_CHIPENA     0xff00  /* Chip enabled mask */
179 #define HIFN_PUSTAT_ENA_2       0x1100  /* Level 2 enabled */
180 #define HIFN_PUSTAT_ENA_1       0x1000  /* Level 1 enabled */
181 #define HIFN_PUSTAT_ENA_0       0x3000  /* Level 0 enabled */
182 #define HIFN_PUSTAT_REV_2       0x0020  /* 7751 PT6/2 */
183 #define HIFN_PUSTAT_REV_3       0x0030  /* 7751 PT6/3 */
184
185 /* FIFO Status Register (HIFN_0_FIFOSTAT) */
186 #define HIFN_FIFOSTAT_SRC       0x7f00  /* Source FIFO available */
187 #define HIFN_FIFOSTAT_DST       0x007f  /* Destination FIFO available */
188
189 /* FIFO Configuration Register (HIFN_0_FIFOCNFG) */
190 #define HIFN_FIFOCNFG_THRESHOLD 0x0400  /* must be written as 1 */
191
192 /*
193  * DMA Interface Registers (offset from BASEREG1)
194  */
195 #define HIFN_1_DMA_CRAR         0x0c    /* DMA Command Ring Address */
196 #define HIFN_1_DMA_SRAR         0x1c    /* DMA Source Ring Address */
197 #define HIFN_1_DMA_RRAR         0x2c    /* DMA Result Ring Address */
198 #define HIFN_1_DMA_DRAR         0x3c    /* DMA Destination Ring Address */
199 #define HIFN_1_DMA_CSR          0x40    /* DMA Status and Control */
200 #define HIFN_1_DMA_IER          0x44    /* DMA Interrupt Enable */
201 #define HIFN_1_DMA_CNFG         0x48    /* DMA Configuration */
202 #define HIFN_1_PLL              0x4c    /* 795x: PLL config */
203 #define HIFN_1_7811_RNGENA      0x60    /* 7811: rng enable */
204 #define HIFN_1_7811_RNGCFG      0x64    /* 7811: rng config */
205 #define HIFN_1_7811_RNGDAT      0x68    /* 7811: rng data */
206 #define HIFN_1_7811_RNGSTS      0x6c    /* 7811: rng status */
207 #define HIFN_1_7811_MIPSRST     0x94    /* 7811: MIPS reset */
208 #define HIFN_1_REVID            0x98    /* Revision ID */
209 #define HIFN_1_UNLOCK_SECRET1   0xf4
210 #define HIFN_1_UNLOCK_SECRET2   0xfc
211 #define HIFN_1_PUB_RESET        0x204   /* Public/RNG Reset */
212 #define HIFN_1_PUB_BASE         0x300   /* Public Base Address */
213 #define HIFN_1_PUB_OPLEN        0x304   /* Public Operand Length */
214 #define HIFN_1_PUB_OP           0x308   /* Public Operand */
215 #define HIFN_1_PUB_STATUS       0x30c   /* Public Status */
216 #define HIFN_1_PUB_IEN          0x310   /* Public Interrupt enable */
217 #define HIFN_1_RNG_CONFIG       0x314   /* RNG config */
218 #define HIFN_1_RNG_DATA         0x318   /* RNG data */
219 #define HIFN_1_PUB_MEM          0x400   /* start of Public key memory */
220 #define HIFN_1_PUB_MEMEND       0xbff   /* end of Public key memory */
221
222 /* DMA Status and Control Register (HIFN_1_DMA_CSR) */
223 #define HIFN_DMACSR_D_CTRLMASK  0xc0000000      /* Destinition Ring Control */
224 #define HIFN_DMACSR_D_CTRL_NOP  0x00000000      /* Dest. Control: no-op */
225 #define HIFN_DMACSR_D_CTRL_DIS  0x40000000      /* Dest. Control: disable */
226 #define HIFN_DMACSR_D_CTRL_ENA  0x80000000      /* Dest. Control: enable */
227 #define HIFN_DMACSR_D_ABORT     0x20000000      /* Destinition Ring PCIAbort */
228 #define HIFN_DMACSR_D_DONE      0x10000000      /* Destinition Ring Done */
229 #define HIFN_DMACSR_D_LAST      0x08000000      /* Destinition Ring Last */
230 #define HIFN_DMACSR_D_WAIT      0x04000000      /* Destinition Ring Waiting */
231 #define HIFN_DMACSR_D_OVER      0x02000000      /* Destinition Ring Overflow */
232 #define HIFN_DMACSR_R_CTRL      0x00c00000      /* Result Ring Control */
233 #define HIFN_DMACSR_R_CTRL_NOP  0x00000000      /* Result Control: no-op */
234 #define HIFN_DMACSR_R_CTRL_DIS  0x00400000      /* Result Control: disable */
235 #define HIFN_DMACSR_R_CTRL_ENA  0x00800000      /* Result Control: enable */
236 #define HIFN_DMACSR_R_ABORT     0x00200000      /* Result Ring PCI Abort */
237 #define HIFN_DMACSR_R_DONE      0x00100000      /* Result Ring Done */
238 #define HIFN_DMACSR_R_LAST      0x00080000      /* Result Ring Last */
239 #define HIFN_DMACSR_R_WAIT      0x00040000      /* Result Ring Waiting */
240 #define HIFN_DMACSR_R_OVER      0x00020000      /* Result Ring Overflow */
241 #define HIFN_DMACSR_S_CTRL      0x0000c000      /* Source Ring Control */
242 #define HIFN_DMACSR_S_CTRL_NOP  0x00000000      /* Source Control: no-op */
243 #define HIFN_DMACSR_S_CTRL_DIS  0x00004000      /* Source Control: disable */
244 #define HIFN_DMACSR_S_CTRL_ENA  0x00008000      /* Source Control: enable */
245 #define HIFN_DMACSR_S_ABORT     0x00002000      /* Source Ring PCI Abort */
246 #define HIFN_DMACSR_S_DONE      0x00001000      /* Source Ring Done */
247 #define HIFN_DMACSR_S_LAST      0x00000800      /* Source Ring Last */
248 #define HIFN_DMACSR_S_WAIT      0x00000400      /* Source Ring Waiting */
249 #define HIFN_DMACSR_ILLW        0x00000200      /* Illegal write (7811 only) */
250 #define HIFN_DMACSR_ILLR        0x00000100      /* Illegal read (7811 only) */
251 #define HIFN_DMACSR_C_CTRL      0x000000c0      /* Command Ring Control */
252 #define HIFN_DMACSR_C_CTRL_NOP  0x00000000      /* Command Control: no-op */
253 #define HIFN_DMACSR_C_CTRL_DIS  0x00000040      /* Command Control: disable */
254 #define HIFN_DMACSR_C_CTRL_ENA  0x00000080      /* Command Control: enable */
255 #define HIFN_DMACSR_C_ABORT     0x00000020      /* Command Ring PCI Abort */
256 #define HIFN_DMACSR_C_DONE      0x00000010      /* Command Ring Done */
257 #define HIFN_DMACSR_C_LAST      0x00000008      /* Command Ring Last */
258 #define HIFN_DMACSR_C_WAIT      0x00000004      /* Command Ring Waiting */
259 #define HIFN_DMACSR_PUBDONE     0x00000002      /* Public op done (7951 only) */
260 #define HIFN_DMACSR_ENGINE      0x00000001      /* Command Ring Engine IRQ */
261
262 /* DMA Interrupt Enable Register (HIFN_1_DMA_IER) */
263 #define HIFN_DMAIER_D_ABORT     0x20000000      /* Destination Ring PCIAbort */
264 #define HIFN_DMAIER_D_DONE      0x10000000      /* Destination Ring Done */
265 #define HIFN_DMAIER_D_LAST      0x08000000      /* Destination Ring Last */
266 #define HIFN_DMAIER_D_WAIT      0x04000000      /* Destination Ring Waiting */
267 #define HIFN_DMAIER_D_OVER      0x02000000      /* Destination Ring Overflow */
268 #define HIFN_DMAIER_R_ABORT     0x00200000      /* Result Ring PCI Abort */
269 #define HIFN_DMAIER_R_DONE      0x00100000      /* Result Ring Done */
270 #define HIFN_DMAIER_R_LAST      0x00080000      /* Result Ring Last */
271 #define HIFN_DMAIER_R_WAIT      0x00040000      /* Result Ring Waiting */
272 #define HIFN_DMAIER_R_OVER      0x00020000      /* Result Ring Overflow */
273 #define HIFN_DMAIER_S_ABORT     0x00002000      /* Source Ring PCI Abort */
274 #define HIFN_DMAIER_S_DONE      0x00001000      /* Source Ring Done */
275 #define HIFN_DMAIER_S_LAST      0x00000800      /* Source Ring Last */
276 #define HIFN_DMAIER_S_WAIT      0x00000400      /* Source Ring Waiting */
277 #define HIFN_DMAIER_ILLW        0x00000200      /* Illegal write (7811 only) */
278 #define HIFN_DMAIER_ILLR        0x00000100      /* Illegal read (7811 only) */
279 #define HIFN_DMAIER_C_ABORT     0x00000020      /* Command Ring PCI Abort */
280 #define HIFN_DMAIER_C_DONE      0x00000010      /* Command Ring Done */
281 #define HIFN_DMAIER_C_LAST      0x00000008      /* Command Ring Last */
282 #define HIFN_DMAIER_C_WAIT      0x00000004      /* Command Ring Waiting */
283 #define HIFN_DMAIER_PUBDONE     0x00000002      /* public op done (7951 only) */
284 #define HIFN_DMAIER_ENGINE      0x00000001      /* Engine IRQ */
285
286 /* DMA Configuration Register (HIFN_1_DMA_CNFG) */
287 #define HIFN_DMACNFG_BIGENDIAN  0x10000000      /* big endian mode */
288 #define HIFN_DMACNFG_POLLFREQ   0x00ff0000      /* Poll frequency mask */
289 #define HIFN_DMACNFG_UNLOCK     0x00000800
290 #define HIFN_DMACNFG_POLLINVAL  0x00000700      /* Invalid Poll Scalar */
291 #define HIFN_DMACNFG_LAST       0x00000010      /* Host control LAST bit */
292 #define HIFN_DMACNFG_MODE       0x00000004      /* DMA mode */
293 #define HIFN_DMACNFG_DMARESET   0x00000002      /* DMA Reset # */
294 #define HIFN_DMACNFG_MSTRESET   0x00000001      /* Master Reset # */
295
296 /* PLL configuration register */
297 #define HIFN_PLL_REF_CLK_HBI    0x00000000      /* HBI reference clock */
298 #define HIFN_PLL_REF_CLK_PLL    0x00000001      /* PLL reference clock */
299 #define HIFN_PLL_BP             0x00000002      /* Reference clock bypass */
300 #define HIFN_PLL_PK_CLK_HBI     0x00000000      /* PK engine HBI clock */
301 #define HIFN_PLL_PK_CLK_PLL     0x00000008      /* PK engine PLL clock */
302 #define HIFN_PLL_PE_CLK_HBI     0x00000000      /* PE engine HBI clock */
303 #define HIFN_PLL_PE_CLK_PLL     0x00000010      /* PE engine PLL clock */
304 #define HIFN_PLL_RESERVED_1     0x00000400      /* Reserved bit, must be 1 */
305 #define HIFN_PLL_ND_SHIFT       11              /* Clock multiplier shift */
306 #define HIFN_PLL_ND_MULT_2      0x00000000      /* PLL clock multiplier 2 */
307 #define HIFN_PLL_ND_MULT_4      0x00000800      /* PLL clock multiplier 4 */
308 #define HIFN_PLL_ND_MULT_6      0x00001000      /* PLL clock multiplier 6 */
309 #define HIFN_PLL_ND_MULT_8      0x00001800      /* PLL clock multiplier 8 */
310 #define HIFN_PLL_ND_MULT_10     0x00002000      /* PLL clock multiplier 10 */
311 #define HIFN_PLL_ND_MULT_12     0x00002800      /* PLL clock multiplier 12 */
312 #define HIFN_PLL_IS_1_8         0x00000000      /* charge pump (mult. 1-8) */
313 #define HIFN_PLL_IS_9_12        0x00010000      /* charge pump (mult. 9-12) */
314
315 #define HIFN_PLL_FCK_MAX        266             /* Maximum PLL frequency */
316
317 /* Public key reset register (HIFN_1_PUB_RESET) */
318 #define HIFN_PUBRST_RESET       0x00000001      /* reset public/rng unit */
319
320 /* Public base address register (HIFN_1_PUB_BASE) */
321 #define HIFN_PUBBASE_ADDR       0x00003fff      /* base address */
322
323 /* Public operand length register (HIFN_1_PUB_OPLEN) */
324 #define HIFN_PUBOPLEN_MOD_M     0x0000007f      /* modulus length mask */
325 #define HIFN_PUBOPLEN_MOD_S     0               /* modulus length shift */
326 #define HIFN_PUBOPLEN_EXP_M     0x0003ff80      /* exponent length mask */
327 #define HIFN_PUBOPLEN_EXP_S     7               /* exponent lenght shift */
328 #define HIFN_PUBOPLEN_RED_M     0x003c0000      /* reducend length mask */
329 #define HIFN_PUBOPLEN_RED_S     18              /* reducend length shift */
330
331 /* Public operation register (HIFN_1_PUB_OP) */
332 #define HIFN_PUBOP_AOFFSET_M    0x0000007f      /* A offset mask */
333 #define HIFN_PUBOP_AOFFSET_S    0               /* A offset shift */
334 #define HIFN_PUBOP_BOFFSET_M    0x00000f80      /* B offset mask */
335 #define HIFN_PUBOP_BOFFSET_S    7               /* B offset shift */
336 #define HIFN_PUBOP_MOFFSET_M    0x0003f000      /* M offset mask */
337 #define HIFN_PUBOP_MOFFSET_S    12              /* M offset shift */
338 #define HIFN_PUBOP_OP_MASK      0x003c0000      /* Opcode: */
339 #define HIFN_PUBOP_OP_NOP       0x00000000      /*  NOP */
340 #define HIFN_PUBOP_OP_ADD       0x00040000      /*  ADD */
341 #define HIFN_PUBOP_OP_ADDC      0x00080000      /*  ADD w/carry */
342 #define HIFN_PUBOP_OP_SUB       0x000c0000      /*  SUB */
343 #define HIFN_PUBOP_OP_SUBC      0x00100000      /*  SUB w/carry */
344 #define HIFN_PUBOP_OP_MODADD    0x00140000      /*  Modular ADD */
345 #define HIFN_PUBOP_OP_MODSUB    0x00180000      /*  Modular SUB */
346 #define HIFN_PUBOP_OP_INCA      0x001c0000      /*  INC A */
347 #define HIFN_PUBOP_OP_DECA      0x00200000      /*  DEC A */
348 #define HIFN_PUBOP_OP_MULT      0x00240000      /*  MULT */
349 #define HIFN_PUBOP_OP_MODMULT   0x00280000      /*  Modular MULT */
350 #define HIFN_PUBOP_OP_MODRED    0x002c0000      /*  Modular RED */
351 #define HIFN_PUBOP_OP_MODEXP    0x00300000      /*  Modular EXP */
352
353 /* Public status register (HIFN_1_PUB_STATUS) */
354 #define HIFN_PUBSTS_DONE        0x00000001      /* operation done */
355 #define HIFN_PUBSTS_CARRY       0x00000002      /* carry */
356
357 /* Public interrupt enable register (HIFN_1_PUB_IEN) */
358 #define HIFN_PUBIEN_DONE        0x00000001      /* operation done interrupt */
359
360 /* Random number generator config register (HIFN_1_RNG_CONFIG) */
361 #define HIFN_RNGCFG_ENA         0x00000001      /* enable rng */
362
363 #define HIFN_NAMESIZE                   32
364 #define HIFN_MAX_RESULT_ORDER           5
365
366 #define HIFN_D_CMD_RSIZE                24*4
367 #define HIFN_D_SRC_RSIZE                80*4
368 #define HIFN_D_DST_RSIZE                80*4
369 #define HIFN_D_RES_RSIZE                24*4
370
371 #define HIFN_D_DST_DALIGN               4
372
373 #define HIFN_QUEUE_LENGTH               HIFN_D_CMD_RSIZE-1
374
375 #define AES_MIN_KEY_SIZE                16
376 #define AES_MAX_KEY_SIZE                32
377
378 #define HIFN_DES_KEY_LENGTH             8
379 #define HIFN_3DES_KEY_LENGTH            24
380 #define HIFN_MAX_CRYPT_KEY_LENGTH       AES_MAX_KEY_SIZE
381 #define HIFN_IV_LENGTH                  8
382 #define HIFN_AES_IV_LENGTH              16
383 #define HIFN_MAX_IV_LENGTH              HIFN_AES_IV_LENGTH
384
385 #define HIFN_MAC_KEY_LENGTH             64
386 #define HIFN_MD5_LENGTH                 16
387 #define HIFN_SHA1_LENGTH                20
388 #define HIFN_MAC_TRUNC_LENGTH           12
389
390 #define HIFN_MAX_COMMAND                (8 + 8 + 8 + 64 + 260)
391 #define HIFN_MAX_RESULT                 (8 + 4 + 4 + 20 + 4)
392 #define HIFN_USED_RESULT                12
393
394 struct hifn_desc
395 {
396         volatile __le32         l;
397         volatile __le32         p;
398 };
399
400 struct hifn_dma {
401         struct hifn_desc        cmdr[HIFN_D_CMD_RSIZE+1];
402         struct hifn_desc        srcr[HIFN_D_SRC_RSIZE+1];
403         struct hifn_desc        dstr[HIFN_D_DST_RSIZE+1];
404         struct hifn_desc        resr[HIFN_D_RES_RSIZE+1];
405
406         u8                      command_bufs[HIFN_D_CMD_RSIZE][HIFN_MAX_COMMAND];
407         u8                      result_bufs[HIFN_D_CMD_RSIZE][HIFN_MAX_RESULT];
408
409         u64                     test_src, test_dst;
410
411         /*
412          *  Our current positions for insertion and removal from the descriptor
413          *  rings.
414          */
415         volatile int            cmdi, srci, dsti, resi;
416         volatile int            cmdu, srcu, dstu, resu;
417         int                     cmdk, srck, dstk, resk;
418 };
419
420 #define HIFN_FLAG_CMD_BUSY      (1<<0)
421 #define HIFN_FLAG_SRC_BUSY      (1<<1)
422 #define HIFN_FLAG_DST_BUSY      (1<<2)
423 #define HIFN_FLAG_RES_BUSY      (1<<3)
424 #define HIFN_FLAG_OLD_KEY       (1<<4)
425
426 #define HIFN_DEFAULT_ACTIVE_NUM 5
427
428 struct hifn_device
429 {
430         char                    name[HIFN_NAMESIZE];
431
432         int                     irq;
433
434         struct pci_dev          *pdev;
435         void __iomem            *bar[3];
436
437         unsigned long           result_mem;
438         dma_addr_t              dst;
439
440         void                    *desc_virt;
441         dma_addr_t              desc_dma;
442
443         u32                     dmareg;
444
445         void                    *sa[HIFN_D_RES_RSIZE];
446
447         spinlock_t              lock;
448
449         void                    *priv;
450
451         u32                     flags;
452         int                     active, started;
453         struct delayed_work     work;
454         unsigned long           reset;
455         unsigned long           success;
456         unsigned long           prev_success;
457
458         u8                      snum;
459
460         struct tasklet_struct   tasklet;
461
462         struct crypto_queue     queue;
463         struct list_head        alg_list;
464
465         unsigned int            pk_clk_freq;
466
467 #ifdef CONFIG_CRYPTO_DEV_HIFN_795X_RNG
468         unsigned int            rng_wait_time;
469         ktime_t                 rngtime;
470         struct hwrng            rng;
471 #endif
472 };
473
474 #define HIFN_D_LENGTH                   0x0000ffff
475 #define HIFN_D_NOINVALID                0x01000000
476 #define HIFN_D_MASKDONEIRQ              0x02000000
477 #define HIFN_D_DESTOVER                 0x04000000
478 #define HIFN_D_OVER                     0x08000000
479 #define HIFN_D_LAST                     0x20000000
480 #define HIFN_D_JUMP                     0x40000000
481 #define HIFN_D_VALID                    0x80000000
482
483 struct hifn_base_command
484 {
485         volatile __le16         masks;
486         volatile __le16         session_num;
487         volatile __le16         total_source_count;
488         volatile __le16         total_dest_count;
489 };
490
491 #define HIFN_BASE_CMD_COMP              0x0100  /* enable compression engine */
492 #define HIFN_BASE_CMD_PAD               0x0200  /* enable padding engine */
493 #define HIFN_BASE_CMD_MAC               0x0400  /* enable MAC engine */
494 #define HIFN_BASE_CMD_CRYPT             0x0800  /* enable crypt engine */
495 #define HIFN_BASE_CMD_DECODE            0x2000
496 #define HIFN_BASE_CMD_SRCLEN_M          0xc000
497 #define HIFN_BASE_CMD_SRCLEN_S          14
498 #define HIFN_BASE_CMD_DSTLEN_M          0x3000
499 #define HIFN_BASE_CMD_DSTLEN_S          12
500 #define HIFN_BASE_CMD_LENMASK_HI        0x30000
501 #define HIFN_BASE_CMD_LENMASK_LO        0x0ffff
502
503 /*
504  * Structure to help build up the command data structure.
505  */
506 struct hifn_crypt_command
507 {
508         volatile __le16                 masks;
509         volatile __le16                 header_skip;
510         volatile __le16                 source_count;
511         volatile __le16                 reserved;
512 };
513
514 #define HIFN_CRYPT_CMD_ALG_MASK         0x0003          /* algorithm: */
515 #define HIFN_CRYPT_CMD_ALG_DES          0x0000          /*   DES */
516 #define HIFN_CRYPT_CMD_ALG_3DES         0x0001          /*   3DES */
517 #define HIFN_CRYPT_CMD_ALG_RC4          0x0002          /*   RC4 */
518 #define HIFN_CRYPT_CMD_ALG_AES          0x0003          /*   AES */
519 #define HIFN_CRYPT_CMD_MODE_MASK        0x0018          /* Encrypt mode: */
520 #define HIFN_CRYPT_CMD_MODE_ECB         0x0000          /*   ECB */
521 #define HIFN_CRYPT_CMD_MODE_CBC         0x0008          /*   CBC */
522 #define HIFN_CRYPT_CMD_MODE_CFB         0x0010          /*   CFB */
523 #define HIFN_CRYPT_CMD_MODE_OFB         0x0018          /*   OFB */
524 #define HIFN_CRYPT_CMD_CLR_CTX          0x0040          /* clear context */
525 #define HIFN_CRYPT_CMD_KSZ_MASK         0x0600          /* AES key size: */
526 #define HIFN_CRYPT_CMD_KSZ_128          0x0000          /*  128 bit */
527 #define HIFN_CRYPT_CMD_KSZ_192          0x0200          /*  192 bit */
528 #define HIFN_CRYPT_CMD_KSZ_256          0x0400          /*  256 bit */
529 #define HIFN_CRYPT_CMD_NEW_KEY          0x0800          /* expect new key */
530 #define HIFN_CRYPT_CMD_NEW_IV           0x1000          /* expect new iv */
531 #define HIFN_CRYPT_CMD_SRCLEN_M         0xc000
532 #define HIFN_CRYPT_CMD_SRCLEN_S         14
533
534 /*
535  * Structure to help build up the command data structure.
536  */
537 struct hifn_mac_command
538 {
539         volatile __le16         masks;
540         volatile __le16         header_skip;
541         volatile __le16         source_count;
542         volatile __le16         reserved;
543 };
544
545 #define HIFN_MAC_CMD_ALG_MASK           0x0001
546 #define HIFN_MAC_CMD_ALG_SHA1           0x0000
547 #define HIFN_MAC_CMD_ALG_MD5            0x0001
548 #define HIFN_MAC_CMD_MODE_MASK          0x000c
549 #define HIFN_MAC_CMD_MODE_HMAC          0x0000
550 #define HIFN_MAC_CMD_MODE_SSL_MAC       0x0004
551 #define HIFN_MAC_CMD_MODE_HASH          0x0008
552 #define HIFN_MAC_CMD_MODE_FULL          0x0004
553 #define HIFN_MAC_CMD_TRUNC              0x0010
554 #define HIFN_MAC_CMD_RESULT             0x0020
555 #define HIFN_MAC_CMD_APPEND             0x0040
556 #define HIFN_MAC_CMD_SRCLEN_M           0xc000
557 #define HIFN_MAC_CMD_SRCLEN_S           14
558
559 /*
560  * MAC POS IPsec initiates authentication after encryption on encodes
561  * and before decryption on decodes.
562  */
563 #define HIFN_MAC_CMD_POS_IPSEC          0x0200
564 #define HIFN_MAC_CMD_NEW_KEY            0x0800
565
566 struct hifn_comp_command
567 {
568         volatile __le16         masks;
569         volatile __le16         header_skip;
570         volatile __le16         source_count;
571         volatile __le16         reserved;
572 };
573
574 #define HIFN_COMP_CMD_SRCLEN_M          0xc000
575 #define HIFN_COMP_CMD_SRCLEN_S          14
576 #define HIFN_COMP_CMD_ONE               0x0100  /* must be one */
577 #define HIFN_COMP_CMD_CLEARHIST         0x0010  /* clear history */
578 #define HIFN_COMP_CMD_UPDATEHIST        0x0008  /* update history */
579 #define HIFN_COMP_CMD_LZS_STRIP0        0x0004  /* LZS: strip zero */
580 #define HIFN_COMP_CMD_MPPC_RESTART      0x0004  /* MPPC: restart */
581 #define HIFN_COMP_CMD_ALG_MASK          0x0001  /* compression mode: */
582 #define HIFN_COMP_CMD_ALG_MPPC          0x0001  /*   MPPC */
583 #define HIFN_COMP_CMD_ALG_LZS           0x0000  /*   LZS */
584
585 struct hifn_base_result
586 {
587         volatile __le16         flags;
588         volatile __le16         session;
589         volatile __le16         src_cnt;                /* 15:0 of source count */
590         volatile __le16         dst_cnt;                /* 15:0 of dest count */
591 };
592
593 #define HIFN_BASE_RES_DSTOVERRUN        0x0200  /* destination overrun */
594 #define HIFN_BASE_RES_SRCLEN_M          0xc000  /* 17:16 of source count */
595 #define HIFN_BASE_RES_SRCLEN_S          14
596 #define HIFN_BASE_RES_DSTLEN_M          0x3000  /* 17:16 of dest count */
597 #define HIFN_BASE_RES_DSTLEN_S          12
598
599 struct hifn_comp_result
600 {
601         volatile __le16         flags;
602         volatile __le16         crc;
603 };
604
605 #define HIFN_COMP_RES_LCB_M             0xff00  /* longitudinal check byte */
606 #define HIFN_COMP_RES_LCB_S             8
607 #define HIFN_COMP_RES_RESTART           0x0004  /* MPPC: restart */
608 #define HIFN_COMP_RES_ENDMARKER         0x0002  /* LZS: end marker seen */
609 #define HIFN_COMP_RES_SRC_NOTZERO       0x0001  /* source expired */
610
611 struct hifn_mac_result
612 {
613         volatile __le16         flags;
614         volatile __le16         reserved;
615         /* followed by 0, 6, 8, or 10 u16's of the MAC, then crypt */
616 };
617
618 #define HIFN_MAC_RES_MISCOMPARE         0x0002  /* compare failed */
619 #define HIFN_MAC_RES_SRC_NOTZERO        0x0001  /* source expired */
620
621 struct hifn_crypt_result
622 {
623         volatile __le16         flags;
624         volatile __le16         reserved;
625 };
626
627 #define HIFN_CRYPT_RES_SRC_NOTZERO      0x0001  /* source expired */
628
629 #ifndef HIFN_POLL_FREQUENCY
630 #define HIFN_POLL_FREQUENCY     0x1
631 #endif
632
633 #ifndef HIFN_POLL_SCALAR
634 #define HIFN_POLL_SCALAR        0x0
635 #endif
636
637 #define HIFN_MAX_SEGLEN         0xffff          /* maximum dma segment len */
638 #define HIFN_MAX_DMALEN         0x3ffff         /* maximum dma length */
639
640 struct hifn_crypto_alg
641 {
642         struct list_head        entry;
643         struct crypto_alg       alg;
644         struct hifn_device      *dev;
645 };
646
647 #define ASYNC_SCATTERLIST_CACHE 16
648
649 #define ASYNC_FLAGS_MISALIGNED  (1<<0)
650
651 struct ablkcipher_walk
652 {
653         struct scatterlist      cache[ASYNC_SCATTERLIST_CACHE];
654         u32                     flags;
655         int                     num;
656 };
657
658 struct hifn_context
659 {
660         u8                      key[HIFN_MAX_CRYPT_KEY_LENGTH];
661         struct hifn_device      *dev;
662         unsigned int            keysize;
663 };
664
665 struct hifn_request_context
666 {
667         u8                      *iv;
668         unsigned int            ivsize;
669         u8                      op, type, mode, unused;
670         struct ablkcipher_walk  walk;
671 };
672
673 #define crypto_alg_to_hifn(a)   container_of(a, struct hifn_crypto_alg, alg)
674
675 static inline u32 hifn_read_0(struct hifn_device *dev, u32 reg)
676 {
677         u32 ret;
678
679         ret = readl(dev->bar[0] + reg);
680
681         return ret;
682 }
683
684 static inline u32 hifn_read_1(struct hifn_device *dev, u32 reg)
685 {
686         u32 ret;
687
688         ret = readl(dev->bar[1] + reg);
689
690         return ret;
691 }
692
693 static inline void hifn_write_0(struct hifn_device *dev, u32 reg, u32 val)
694 {
695         writel((__force u32)cpu_to_le32(val), dev->bar[0] + reg);
696 }
697
698 static inline void hifn_write_1(struct hifn_device *dev, u32 reg, u32 val)
699 {
700         writel((__force u32)cpu_to_le32(val), dev->bar[1] + reg);
701 }
702
703 static void hifn_wait_puc(struct hifn_device *dev)
704 {
705         int i;
706         u32 ret;
707
708         for (i=10000; i > 0; --i) {
709                 ret = hifn_read_0(dev, HIFN_0_PUCTRL);
710                 if (!(ret & HIFN_PUCTRL_RESET))
711                         break;
712
713                 udelay(1);
714         }
715
716         if (!i)
717                 dprintk("%s: Failed to reset PUC unit.\n", dev->name);
718 }
719
720 static void hifn_reset_puc(struct hifn_device *dev)
721 {
722         hifn_write_0(dev, HIFN_0_PUCTRL, HIFN_PUCTRL_DMAENA);
723         hifn_wait_puc(dev);
724 }
725
726 static void hifn_stop_device(struct hifn_device *dev)
727 {
728         hifn_write_1(dev, HIFN_1_DMA_CSR,
729                 HIFN_DMACSR_D_CTRL_DIS | HIFN_DMACSR_R_CTRL_DIS |
730                 HIFN_DMACSR_S_CTRL_DIS | HIFN_DMACSR_C_CTRL_DIS);
731         hifn_write_0(dev, HIFN_0_PUIER, 0);
732         hifn_write_1(dev, HIFN_1_DMA_IER, 0);
733 }
734
735 static void hifn_reset_dma(struct hifn_device *dev, int full)
736 {
737         hifn_stop_device(dev);
738
739         /*
740          * Setting poll frequency and others to 0.
741          */
742         hifn_write_1(dev, HIFN_1_DMA_CNFG, HIFN_DMACNFG_MSTRESET |
743                         HIFN_DMACNFG_DMARESET | HIFN_DMACNFG_MODE);
744         mdelay(1);
745
746         /*
747          * Reset DMA.
748          */
749         if (full) {
750                 hifn_write_1(dev, HIFN_1_DMA_CNFG, HIFN_DMACNFG_MODE);
751                 mdelay(1);
752         } else {
753                 hifn_write_1(dev, HIFN_1_DMA_CNFG, HIFN_DMACNFG_MODE |
754                                 HIFN_DMACNFG_MSTRESET);
755                 hifn_reset_puc(dev);
756         }
757
758         hifn_write_1(dev, HIFN_1_DMA_CNFG, HIFN_DMACNFG_MSTRESET |
759                         HIFN_DMACNFG_DMARESET | HIFN_DMACNFG_MODE);
760
761         hifn_reset_puc(dev);
762 }
763
764 static u32 hifn_next_signature(u_int32_t a, u_int cnt)
765 {
766         int i;
767         u32 v;
768
769         for (i = 0; i < cnt; i++) {
770
771                 /* get the parity */
772                 v = a & 0x80080125;
773                 v ^= v >> 16;
774                 v ^= v >> 8;
775                 v ^= v >> 4;
776                 v ^= v >> 2;
777                 v ^= v >> 1;
778
779                 a = (v & 1) ^ (a << 1);
780         }
781
782         return a;
783 }
784
785 static struct pci2id {
786         u_short         pci_vendor;
787         u_short         pci_prod;
788         char            card_id[13];
789 } pci2id[] = {
790         {
791                 PCI_VENDOR_ID_HIFN,
792                 PCI_DEVICE_ID_HIFN_7955,
793                 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
794                   0x00, 0x00, 0x00, 0x00, 0x00 }
795         },
796         {
797                 PCI_VENDOR_ID_HIFN,
798                 PCI_DEVICE_ID_HIFN_7956,
799                 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
800                   0x00, 0x00, 0x00, 0x00, 0x00 }
801         }
802 };
803
804 #ifdef CONFIG_CRYPTO_DEV_HIFN_795X_RNG
805 static int hifn_rng_data_present(struct hwrng *rng, int wait)
806 {
807         struct hifn_device *dev = (struct hifn_device *)rng->priv;
808         s64 nsec;
809
810         nsec = ktime_to_ns(ktime_sub(ktime_get(), dev->rngtime));
811         nsec -= dev->rng_wait_time;
812         if (nsec <= 0)
813                 return 1;
814         if (!wait)
815                 return 0;
816         ndelay(nsec);
817         return 1;
818 }
819
820 static int hifn_rng_data_read(struct hwrng *rng, u32 *data)
821 {
822         struct hifn_device *dev = (struct hifn_device *)rng->priv;
823
824         *data = hifn_read_1(dev, HIFN_1_RNG_DATA);
825         dev->rngtime = ktime_get();
826         return 4;
827 }
828
829 static int hifn_register_rng(struct hifn_device *dev)
830 {
831         /*
832          * We must wait at least 256 Pk_clk cycles between two reads of the rng.
833          */
834         dev->rng_wait_time      = DIV_ROUND_UP(NSEC_PER_SEC, dev->pk_clk_freq) *
835                                   256;
836
837         dev->rng.name           = dev->name;
838         dev->rng.data_present   = hifn_rng_data_present,
839         dev->rng.data_read      = hifn_rng_data_read,
840         dev->rng.priv           = (unsigned long)dev;
841
842         return hwrng_register(&dev->rng);
843 }
844
845 static void hifn_unregister_rng(struct hifn_device *dev)
846 {
847         hwrng_unregister(&dev->rng);
848 }
849 #else
850 #define hifn_register_rng(dev)          0
851 #define hifn_unregister_rng(dev)
852 #endif
853
854 static int hifn_init_pubrng(struct hifn_device *dev)
855 {
856         int i;
857
858         hifn_write_1(dev, HIFN_1_PUB_RESET, hifn_read_1(dev, HIFN_1_PUB_RESET) |
859                         HIFN_PUBRST_RESET);
860
861         for (i=100; i > 0; --i) {
862                 mdelay(1);
863
864                 if ((hifn_read_1(dev, HIFN_1_PUB_RESET) & HIFN_PUBRST_RESET) == 0)
865                         break;
866         }
867
868         if (!i)
869                 dprintk("Chip %s: Failed to initialise public key engine.\n",
870                                 dev->name);
871         else {
872                 hifn_write_1(dev, HIFN_1_PUB_IEN, HIFN_PUBIEN_DONE);
873                 dev->dmareg |= HIFN_DMAIER_PUBDONE;
874                 hifn_write_1(dev, HIFN_1_DMA_IER, dev->dmareg);
875
876                 dprintk("Chip %s: Public key engine has been sucessfully "
877                                 "initialised.\n", dev->name);
878         }
879
880         /*
881          * Enable RNG engine.
882          */
883
884         hifn_write_1(dev, HIFN_1_RNG_CONFIG,
885                         hifn_read_1(dev, HIFN_1_RNG_CONFIG) | HIFN_RNGCFG_ENA);
886         dprintk("Chip %s: RNG engine has been successfully initialised.\n",
887                         dev->name);
888
889 #ifdef CONFIG_CRYPTO_DEV_HIFN_795X_RNG
890         /* First value must be discarded */
891         hifn_read_1(dev, HIFN_1_RNG_DATA);
892         dev->rngtime = ktime_get();
893 #endif
894         return 0;
895 }
896
897 static int hifn_enable_crypto(struct hifn_device *dev)
898 {
899         u32 dmacfg, addr;
900         char *offtbl = NULL;
901         int i;
902
903         for (i = 0; i < ARRAY_SIZE(pci2id); i++) {
904                 if (pci2id[i].pci_vendor == dev->pdev->vendor &&
905                                 pci2id[i].pci_prod == dev->pdev->device) {
906                         offtbl = pci2id[i].card_id;
907                         break;
908                 }
909         }
910
911         if (offtbl == NULL) {
912                 dprintk("Chip %s: Unknown card!\n", dev->name);
913                 return -ENODEV;
914         }
915
916         dmacfg = hifn_read_1(dev, HIFN_1_DMA_CNFG);
917
918         hifn_write_1(dev, HIFN_1_DMA_CNFG,
919                         HIFN_DMACNFG_UNLOCK | HIFN_DMACNFG_MSTRESET |
920                         HIFN_DMACNFG_DMARESET | HIFN_DMACNFG_MODE);
921         mdelay(1);
922         addr = hifn_read_1(dev, HIFN_1_UNLOCK_SECRET1);
923         mdelay(1);
924         hifn_write_1(dev, HIFN_1_UNLOCK_SECRET2, 0);
925         mdelay(1);
926
927         for (i=0; i<12; ++i) {
928                 addr = hifn_next_signature(addr, offtbl[i] + 0x101);
929                 hifn_write_1(dev, HIFN_1_UNLOCK_SECRET2, addr);
930
931                 mdelay(1);
932         }
933         hifn_write_1(dev, HIFN_1_DMA_CNFG, dmacfg);
934
935         dprintk("Chip %s: %s.\n", dev->name, pci_name(dev->pdev));
936
937         return 0;
938 }
939
940 static void hifn_init_dma(struct hifn_device *dev)
941 {
942         struct hifn_dma *dma = (struct hifn_dma *)dev->desc_virt;
943         u32 dptr = dev->desc_dma;
944         int i;
945
946         for (i=0; i<HIFN_D_CMD_RSIZE; ++i)
947                 dma->cmdr[i].p = __cpu_to_le32(dptr +
948                                 offsetof(struct hifn_dma, command_bufs[i][0]));
949         for (i=0; i<HIFN_D_RES_RSIZE; ++i)
950                 dma->resr[i].p = __cpu_to_le32(dptr +
951                                 offsetof(struct hifn_dma, result_bufs[i][0]));
952
953         /*
954          * Setup LAST descriptors.
955          */
956         dma->cmdr[HIFN_D_CMD_RSIZE].p = __cpu_to_le32(dptr +
957                         offsetof(struct hifn_dma, cmdr[0]));
958         dma->srcr[HIFN_D_SRC_RSIZE].p = __cpu_to_le32(dptr +
959                         offsetof(struct hifn_dma, srcr[0]));
960         dma->dstr[HIFN_D_DST_RSIZE].p = __cpu_to_le32(dptr +
961                         offsetof(struct hifn_dma, dstr[0]));
962         dma->resr[HIFN_D_RES_RSIZE].p = __cpu_to_le32(dptr +
963                         offsetof(struct hifn_dma, resr[0]));
964
965         dma->cmdu = dma->srcu = dma->dstu = dma->resu = 0;
966         dma->cmdi = dma->srci = dma->dsti = dma->resi = 0;
967         dma->cmdk = dma->srck = dma->dstk = dma->resk = 0;
968 }
969
970 /*
971  * Initialize the PLL. We need to know the frequency of the reference clock
972  * to calculate the optimal multiplier. For PCI we assume 66MHz, since that
973  * allows us to operate without the risk of overclocking the chip. If it
974  * actually uses 33MHz, the chip will operate at half the speed, this can be
975  * overriden by specifying the frequency as module parameter (pci33).
976  *
977  * Unfortunately the PCI clock is not very suitable since the HIFN needs a
978  * stable clock and the PCI clock frequency may vary, so the default is the
979  * external clock. There is no way to find out its frequency, we default to
980  * 66MHz since according to Mike Ham of HiFn, almost every board in existence
981  * has an external crystal populated at 66MHz.
982  */
983 static void hifn_init_pll(struct hifn_device *dev)
984 {
985         unsigned int freq, m;
986         u32 pllcfg;
987
988         pllcfg = HIFN_1_PLL | HIFN_PLL_RESERVED_1;
989
990         if (strncmp(hifn_pll_ref, "ext", 3) == 0)
991                 pllcfg |= HIFN_PLL_REF_CLK_PLL;
992         else
993                 pllcfg |= HIFN_PLL_REF_CLK_HBI;
994
995         if (hifn_pll_ref[3] != '\0')
996                 freq = simple_strtoul(hifn_pll_ref + 3, NULL, 10);
997         else {
998                 freq = 66;
999                 printk(KERN_INFO "hifn795x: assuming %uMHz clock speed, "
1000                                  "override with hifn_pll_ref=%.3s<frequency>\n",
1001                        freq, hifn_pll_ref);
1002         }
1003
1004         m = HIFN_PLL_FCK_MAX / freq;
1005
1006         pllcfg |= (m / 2 - 1) << HIFN_PLL_ND_SHIFT;
1007         if (m <= 8)
1008                 pllcfg |= HIFN_PLL_IS_1_8;
1009         else
1010                 pllcfg |= HIFN_PLL_IS_9_12;
1011
1012         /* Select clock source and enable clock bypass */
1013         hifn_write_1(dev, HIFN_1_PLL, pllcfg |
1014                      HIFN_PLL_PK_CLK_HBI | HIFN_PLL_PE_CLK_HBI | HIFN_PLL_BP);
1015
1016         /* Let the chip lock to the input clock */
1017         mdelay(10);
1018
1019         /* Disable clock bypass */
1020         hifn_write_1(dev, HIFN_1_PLL, pllcfg |
1021                      HIFN_PLL_PK_CLK_HBI | HIFN_PLL_PE_CLK_HBI);
1022
1023         /* Switch the engines to the PLL */
1024         hifn_write_1(dev, HIFN_1_PLL, pllcfg |
1025                      HIFN_PLL_PK_CLK_PLL | HIFN_PLL_PE_CLK_PLL);
1026
1027         /*
1028          * The Fpk_clk runs at half the total speed. Its frequency is needed to
1029          * calculate the minimum time between two reads of the rng. Since 33MHz
1030          * is actually 33.333... we overestimate the frequency here, resulting
1031          * in slightly larger intervals.
1032          */
1033         dev->pk_clk_freq = 1000000 * (freq + 1) * m / 2;
1034 }
1035
1036 static void hifn_init_registers(struct hifn_device *dev)
1037 {
1038         u32 dptr = dev->desc_dma;
1039
1040         /* Initialization magic... */
1041         hifn_write_0(dev, HIFN_0_PUCTRL, HIFN_PUCTRL_DMAENA);
1042         hifn_write_0(dev, HIFN_0_FIFOCNFG, HIFN_FIFOCNFG_THRESHOLD);
1043         hifn_write_0(dev, HIFN_0_PUIER, HIFN_PUIER_DSTOVER);
1044
1045         /* write all 4 ring address registers */
1046         hifn_write_1(dev, HIFN_1_DMA_CRAR, dptr +
1047                                 offsetof(struct hifn_dma, cmdr[0]));
1048         hifn_write_1(dev, HIFN_1_DMA_SRAR, dptr +
1049                                 offsetof(struct hifn_dma, srcr[0]));
1050         hifn_write_1(dev, HIFN_1_DMA_DRAR, dptr +
1051                                 offsetof(struct hifn_dma, dstr[0]));
1052         hifn_write_1(dev, HIFN_1_DMA_RRAR, dptr +
1053                                 offsetof(struct hifn_dma, resr[0]));
1054
1055         mdelay(2);
1056 #if 0
1057         hifn_write_1(dev, HIFN_1_DMA_CSR,
1058             HIFN_DMACSR_D_CTRL_DIS | HIFN_DMACSR_R_CTRL_DIS |
1059             HIFN_DMACSR_S_CTRL_DIS | HIFN_DMACSR_C_CTRL_DIS |
1060             HIFN_DMACSR_D_ABORT | HIFN_DMACSR_D_DONE | HIFN_DMACSR_D_LAST |
1061             HIFN_DMACSR_D_WAIT | HIFN_DMACSR_D_OVER |
1062             HIFN_DMACSR_R_ABORT | HIFN_DMACSR_R_DONE | HIFN_DMACSR_R_LAST |
1063             HIFN_DMACSR_R_WAIT | HIFN_DMACSR_R_OVER |
1064             HIFN_DMACSR_S_ABORT | HIFN_DMACSR_S_DONE | HIFN_DMACSR_S_LAST |
1065             HIFN_DMACSR_S_WAIT |
1066             HIFN_DMACSR_C_ABORT | HIFN_DMACSR_C_DONE | HIFN_DMACSR_C_LAST |
1067             HIFN_DMACSR_C_WAIT |
1068             HIFN_DMACSR_ENGINE |
1069             HIFN_DMACSR_PUBDONE);
1070 #else
1071         hifn_write_1(dev, HIFN_1_DMA_CSR,
1072             HIFN_DMACSR_C_CTRL_ENA | HIFN_DMACSR_S_CTRL_ENA |
1073             HIFN_DMACSR_D_CTRL_ENA | HIFN_DMACSR_R_CTRL_ENA |
1074             HIFN_DMACSR_D_ABORT | HIFN_DMACSR_D_DONE | HIFN_DMACSR_D_LAST |
1075             HIFN_DMACSR_D_WAIT | HIFN_DMACSR_D_OVER |
1076             HIFN_DMACSR_R_ABORT | HIFN_DMACSR_R_DONE | HIFN_DMACSR_R_LAST |
1077             HIFN_DMACSR_R_WAIT | HIFN_DMACSR_R_OVER |
1078             HIFN_DMACSR_S_ABORT | HIFN_DMACSR_S_DONE | HIFN_DMACSR_S_LAST |
1079             HIFN_DMACSR_S_WAIT |
1080             HIFN_DMACSR_C_ABORT | HIFN_DMACSR_C_DONE | HIFN_DMACSR_C_LAST |
1081             HIFN_DMACSR_C_WAIT |
1082             HIFN_DMACSR_ENGINE |
1083             HIFN_DMACSR_PUBDONE);
1084 #endif
1085         hifn_read_1(dev, HIFN_1_DMA_CSR);
1086
1087         dev->dmareg |= HIFN_DMAIER_R_DONE | HIFN_DMAIER_C_ABORT |
1088             HIFN_DMAIER_D_OVER | HIFN_DMAIER_R_OVER |
1089             HIFN_DMAIER_S_ABORT | HIFN_DMAIER_D_ABORT | HIFN_DMAIER_R_ABORT |
1090             HIFN_DMAIER_ENGINE;
1091         dev->dmareg &= ~HIFN_DMAIER_C_WAIT;
1092
1093         hifn_write_1(dev, HIFN_1_DMA_IER, dev->dmareg);
1094         hifn_read_1(dev, HIFN_1_DMA_IER);
1095 #if 0
1096         hifn_write_0(dev, HIFN_0_PUCNFG, HIFN_PUCNFG_ENCCNFG |
1097                     HIFN_PUCNFG_DRFR_128 | HIFN_PUCNFG_TCALLPHASES |
1098                     HIFN_PUCNFG_TCDRVTOTEM | HIFN_PUCNFG_BUS32 |
1099                     HIFN_PUCNFG_DRAM);
1100 #else
1101         hifn_write_0(dev, HIFN_0_PUCNFG, 0x10342);
1102 #endif
1103         hifn_init_pll(dev);
1104
1105         hifn_write_0(dev, HIFN_0_PUISR, HIFN_PUISR_DSTOVER);
1106         hifn_write_1(dev, HIFN_1_DMA_CNFG, HIFN_DMACNFG_MSTRESET |
1107             HIFN_DMACNFG_DMARESET | HIFN_DMACNFG_MODE | HIFN_DMACNFG_LAST |
1108             ((HIFN_POLL_FREQUENCY << 16 ) & HIFN_DMACNFG_POLLFREQ) |
1109             ((HIFN_POLL_SCALAR << 8) & HIFN_DMACNFG_POLLINVAL));
1110 }
1111
1112 static int hifn_setup_base_command(struct hifn_device *dev, u8 *buf,
1113                 unsigned dlen, unsigned slen, u16 mask, u8 snum)
1114 {
1115         struct hifn_base_command *base_cmd;
1116         u8 *buf_pos = buf;
1117
1118         base_cmd = (struct hifn_base_command *)buf_pos;
1119         base_cmd->masks = __cpu_to_le16(mask);
1120         base_cmd->total_source_count =
1121                 __cpu_to_le16(slen & HIFN_BASE_CMD_LENMASK_LO);
1122         base_cmd->total_dest_count =
1123                 __cpu_to_le16(dlen & HIFN_BASE_CMD_LENMASK_LO);
1124
1125         dlen >>= 16;
1126         slen >>= 16;
1127         base_cmd->session_num = __cpu_to_le16(snum |
1128             ((slen << HIFN_BASE_CMD_SRCLEN_S) & HIFN_BASE_CMD_SRCLEN_M) |
1129             ((dlen << HIFN_BASE_CMD_DSTLEN_S) & HIFN_BASE_CMD_DSTLEN_M));
1130
1131         return sizeof(struct hifn_base_command);
1132 }
1133
1134 static int hifn_setup_crypto_command(struct hifn_device *dev,
1135                 u8 *buf, unsigned dlen, unsigned slen,
1136                 u8 *key, int keylen, u8 *iv, int ivsize, u16 mode)
1137 {
1138         struct hifn_dma *dma = (struct hifn_dma *)dev->desc_virt;
1139         struct hifn_crypt_command *cry_cmd;
1140         u8 *buf_pos = buf;
1141         u16 cmd_len;
1142
1143         cry_cmd = (struct hifn_crypt_command *)buf_pos;
1144
1145         cry_cmd->source_count = __cpu_to_le16(dlen & 0xffff);
1146         dlen >>= 16;
1147         cry_cmd->masks = __cpu_to_le16(mode |
1148                         ((dlen << HIFN_CRYPT_CMD_SRCLEN_S) &
1149                          HIFN_CRYPT_CMD_SRCLEN_M));
1150         cry_cmd->header_skip = 0;
1151         cry_cmd->reserved = 0;
1152
1153         buf_pos += sizeof(struct hifn_crypt_command);
1154
1155         dma->cmdu++;
1156         if (dma->cmdu > 1) {
1157                 dev->dmareg |= HIFN_DMAIER_C_WAIT;
1158                 hifn_write_1(dev, HIFN_1_DMA_IER, dev->dmareg);
1159         }
1160
1161         if (keylen) {
1162                 memcpy(buf_pos, key, keylen);
1163                 buf_pos += keylen;
1164         }
1165         if (ivsize) {
1166                 memcpy(buf_pos, iv, ivsize);
1167                 buf_pos += ivsize;
1168         }
1169
1170         cmd_len = buf_pos - buf;
1171
1172         return cmd_len;
1173 }
1174
1175 static int hifn_setup_cmd_desc(struct hifn_device *dev,
1176                 struct hifn_context *ctx, struct hifn_request_context *rctx,
1177                 void *priv, unsigned int nbytes)
1178 {
1179         struct hifn_dma *dma = (struct hifn_dma *)dev->desc_virt;
1180         int cmd_len, sa_idx;
1181         u8 *buf, *buf_pos;
1182         u16 mask;
1183
1184         sa_idx = dma->cmdi;
1185         buf_pos = buf = dma->command_bufs[dma->cmdi];
1186
1187         mask = 0;
1188         switch (rctx->op) {
1189                 case ACRYPTO_OP_DECRYPT:
1190                         mask = HIFN_BASE_CMD_CRYPT | HIFN_BASE_CMD_DECODE;
1191                         break;
1192                 case ACRYPTO_OP_ENCRYPT:
1193                         mask = HIFN_BASE_CMD_CRYPT;
1194                         break;
1195                 case ACRYPTO_OP_HMAC:
1196                         mask = HIFN_BASE_CMD_MAC;
1197                         break;
1198                 default:
1199                         goto err_out;
1200         }
1201
1202         buf_pos += hifn_setup_base_command(dev, buf_pos, nbytes,
1203                         nbytes, mask, dev->snum);
1204
1205         if (rctx->op == ACRYPTO_OP_ENCRYPT || rctx->op == ACRYPTO_OP_DECRYPT) {
1206                 u16 md = 0;
1207
1208                 if (ctx->keysize)
1209                         md |= HIFN_CRYPT_CMD_NEW_KEY;
1210                 if (rctx->iv && rctx->mode != ACRYPTO_MODE_ECB)
1211                         md |= HIFN_CRYPT_CMD_NEW_IV;
1212
1213                 switch (rctx->mode) {
1214                         case ACRYPTO_MODE_ECB:
1215                                 md |= HIFN_CRYPT_CMD_MODE_ECB;
1216                                 break;
1217                         case ACRYPTO_MODE_CBC:
1218                                 md |= HIFN_CRYPT_CMD_MODE_CBC;
1219                                 break;
1220                         case ACRYPTO_MODE_CFB:
1221                                 md |= HIFN_CRYPT_CMD_MODE_CFB;
1222                                 break;
1223                         case ACRYPTO_MODE_OFB:
1224                                 md |= HIFN_CRYPT_CMD_MODE_OFB;
1225                                 break;
1226                         default:
1227                                 goto err_out;
1228                 }
1229
1230                 switch (rctx->type) {
1231                         case ACRYPTO_TYPE_AES_128:
1232                                 if (ctx->keysize != 16)
1233                                         goto err_out;
1234                                 md |= HIFN_CRYPT_CMD_KSZ_128 |
1235                                         HIFN_CRYPT_CMD_ALG_AES;
1236                                 break;
1237                         case ACRYPTO_TYPE_AES_192:
1238                                 if (ctx->keysize != 24)
1239                                         goto err_out;
1240                                 md |= HIFN_CRYPT_CMD_KSZ_192 |
1241                                         HIFN_CRYPT_CMD_ALG_AES;
1242                                 break;
1243                         case ACRYPTO_TYPE_AES_256:
1244                                 if (ctx->keysize != 32)
1245                                         goto err_out;
1246                                 md |= HIFN_CRYPT_CMD_KSZ_256 |
1247                                         HIFN_CRYPT_CMD_ALG_AES;
1248                                 break;
1249                         case ACRYPTO_TYPE_3DES:
1250                                 if (ctx->keysize != 24)
1251                                         goto err_out;
1252                                 md |= HIFN_CRYPT_CMD_ALG_3DES;
1253                                 break;
1254                         case ACRYPTO_TYPE_DES:
1255                                 if (ctx->keysize != 8)
1256                                         goto err_out;
1257                                 md |= HIFN_CRYPT_CMD_ALG_DES;
1258                                 break;
1259                         default:
1260                                 goto err_out;
1261                 }
1262
1263                 buf_pos += hifn_setup_crypto_command(dev, buf_pos,
1264                                 nbytes, nbytes, ctx->key, ctx->keysize,
1265                                 rctx->iv, rctx->ivsize, md);
1266         }
1267
1268         dev->sa[sa_idx] = priv;
1269
1270         cmd_len = buf_pos - buf;
1271         dma->cmdr[dma->cmdi].l = __cpu_to_le32(cmd_len | HIFN_D_VALID |
1272                         HIFN_D_LAST | HIFN_D_MASKDONEIRQ);
1273
1274         if (++dma->cmdi == HIFN_D_CMD_RSIZE) {
1275                 dma->cmdr[dma->cmdi].l = __cpu_to_le32(
1276                         HIFN_D_VALID | HIFN_D_LAST |
1277                         HIFN_D_MASKDONEIRQ | HIFN_D_JUMP);
1278                 dma->cmdi = 0;
1279         } else
1280                 dma->cmdr[dma->cmdi-1].l |= __cpu_to_le32(HIFN_D_VALID);
1281
1282         if (!(dev->flags & HIFN_FLAG_CMD_BUSY)) {
1283                 hifn_write_1(dev, HIFN_1_DMA_CSR, HIFN_DMACSR_C_CTRL_ENA);
1284                 dev->flags |= HIFN_FLAG_CMD_BUSY;
1285         }
1286         return 0;
1287
1288 err_out:
1289         return -EINVAL;
1290 }
1291
1292 static int hifn_setup_src_desc(struct hifn_device *dev, struct page *page,
1293                 unsigned int offset, unsigned int size, int last)
1294 {
1295         struct hifn_dma *dma = (struct hifn_dma *)dev->desc_virt;
1296         int idx;
1297         dma_addr_t addr;
1298
1299         addr = pci_map_page(dev->pdev, page, offset, size, PCI_DMA_TODEVICE);
1300
1301         idx = dma->srci;
1302
1303         dma->srcr[idx].p = __cpu_to_le32(addr);
1304         dma->srcr[idx].l = __cpu_to_le32(size | HIFN_D_VALID |
1305                         HIFN_D_MASKDONEIRQ | (last ? HIFN_D_LAST : 0));
1306
1307         if (++idx == HIFN_D_SRC_RSIZE) {
1308                 dma->srcr[idx].l = __cpu_to_le32(HIFN_D_VALID |
1309                                 HIFN_D_JUMP | HIFN_D_MASKDONEIRQ |
1310                                 (last ? HIFN_D_LAST : 0));
1311                 idx = 0;
1312         }
1313
1314         dma->srci = idx;
1315         dma->srcu++;
1316
1317         if (!(dev->flags & HIFN_FLAG_SRC_BUSY)) {
1318                 hifn_write_1(dev, HIFN_1_DMA_CSR, HIFN_DMACSR_S_CTRL_ENA);
1319                 dev->flags |= HIFN_FLAG_SRC_BUSY;
1320         }
1321
1322         return size;
1323 }
1324
1325 static void hifn_setup_res_desc(struct hifn_device *dev)
1326 {
1327         struct hifn_dma *dma = (struct hifn_dma *)dev->desc_virt;
1328
1329         dma->resr[dma->resi].l = __cpu_to_le32(HIFN_USED_RESULT |
1330                         HIFN_D_VALID | HIFN_D_LAST);
1331         /*
1332          * dma->resr[dma->resi].l = __cpu_to_le32(HIFN_MAX_RESULT | HIFN_D_VALID |
1333          *                                      HIFN_D_LAST);
1334          */
1335
1336         if (++dma->resi == HIFN_D_RES_RSIZE) {
1337                 dma->resr[HIFN_D_RES_RSIZE].l = __cpu_to_le32(HIFN_D_VALID |
1338                                 HIFN_D_JUMP | HIFN_D_MASKDONEIRQ | HIFN_D_LAST);
1339                 dma->resi = 0;
1340         }
1341
1342         dma->resu++;
1343
1344         if (!(dev->flags & HIFN_FLAG_RES_BUSY)) {
1345                 hifn_write_1(dev, HIFN_1_DMA_CSR, HIFN_DMACSR_R_CTRL_ENA);
1346                 dev->flags |= HIFN_FLAG_RES_BUSY;
1347         }
1348 }
1349
1350 static void hifn_setup_dst_desc(struct hifn_device *dev, struct page *page,
1351                 unsigned offset, unsigned size, int last)
1352 {
1353         struct hifn_dma *dma = (struct hifn_dma *)dev->desc_virt;
1354         int idx;
1355         dma_addr_t addr;
1356
1357         addr = pci_map_page(dev->pdev, page, offset, size, PCI_DMA_FROMDEVICE);
1358
1359         idx = dma->dsti;
1360         dma->dstr[idx].p = __cpu_to_le32(addr);
1361         dma->dstr[idx].l = __cpu_to_le32(size | HIFN_D_VALID |
1362                         HIFN_D_MASKDONEIRQ | (last ? HIFN_D_LAST : 0));
1363
1364         if (++idx == HIFN_D_DST_RSIZE) {
1365                 dma->dstr[idx].l = __cpu_to_le32(HIFN_D_VALID |
1366                                 HIFN_D_JUMP | HIFN_D_MASKDONEIRQ |
1367                                 (last ? HIFN_D_LAST : 0));
1368                 idx = 0;
1369         }
1370         dma->dsti = idx;
1371         dma->dstu++;
1372
1373         if (!(dev->flags & HIFN_FLAG_DST_BUSY)) {
1374                 hifn_write_1(dev, HIFN_1_DMA_CSR, HIFN_DMACSR_D_CTRL_ENA);
1375                 dev->flags |= HIFN_FLAG_DST_BUSY;
1376         }
1377 }
1378
1379 static int hifn_setup_dma(struct hifn_device *dev,
1380                 struct hifn_context *ctx, struct hifn_request_context *rctx,
1381                 struct scatterlist *src, struct scatterlist *dst,
1382                 unsigned int nbytes, void *priv)
1383 {
1384         struct scatterlist *t;
1385         struct page *spage, *dpage;
1386         unsigned int soff, doff;
1387         unsigned int n, len;
1388
1389         n = nbytes;
1390         while (n) {
1391                 spage = sg_page(src);
1392                 soff = src->offset;
1393                 len = min(src->length, n);
1394
1395                 dprintk("%s: spage: %p, soffset: %u, nbytes: %u, "
1396                         "priv: %p, rctx: %p.\n",
1397                         dev->name, spage, soff, nbytes, priv, rctx);
1398                 hifn_setup_src_desc(dev, spage, soff, len, n - len == 0);
1399
1400                 src++;
1401                 n -= len;
1402         }
1403
1404         t = &rctx->walk.cache[0];
1405         n = nbytes;
1406         while (n) {
1407                 if (t->length && rctx->walk.flags & ASYNC_FLAGS_MISALIGNED) {
1408                         dpage = sg_page(t);
1409                         doff = 0;
1410                         len = t->length;
1411                 } else {
1412                         dpage = sg_page(dst);
1413                         doff = dst->offset;
1414                         len = dst->length;
1415                 }
1416                 len = min(len, n);
1417
1418                 dprintk("%s: dpage: %p, doffset: %u, nbytes: %u, "
1419                         "priv: %p, rctx: %p.\n",
1420                         dev->name, dpage, doff, nbytes, priv, rctx);
1421                 hifn_setup_dst_desc(dev, dpage, doff, len, n - len == 0);
1422
1423                 dst++;
1424                 t++;
1425                 n -= len;
1426         }
1427
1428         hifn_setup_cmd_desc(dev, ctx, rctx, priv, nbytes);
1429         hifn_setup_res_desc(dev);
1430         return 0;
1431 }
1432
1433 static int ablkcipher_walk_init(struct ablkcipher_walk *w,
1434                 int num, gfp_t gfp_flags)
1435 {
1436         int i;
1437
1438         num = min(ASYNC_SCATTERLIST_CACHE, num);
1439         sg_init_table(w->cache, num);
1440
1441         w->num = 0;
1442         for (i=0; i<num; ++i) {
1443                 struct page *page = alloc_page(gfp_flags);
1444                 struct scatterlist *s;
1445
1446                 if (!page)
1447                         break;
1448
1449                 s = &w->cache[i];
1450
1451                 sg_set_page(s, page, PAGE_SIZE, 0);
1452                 w->num++;
1453         }
1454
1455         return i;
1456 }
1457
1458 static void ablkcipher_walk_exit(struct ablkcipher_walk *w)
1459 {
1460         int i;
1461
1462         for (i=0; i<w->num; ++i) {
1463                 struct scatterlist *s = &w->cache[i];
1464
1465                 __free_page(sg_page(s));
1466
1467                 s->length = 0;
1468         }
1469
1470         w->num = 0;
1471 }
1472
1473 static int ablkcipher_add(unsigned int *drestp, struct scatterlist *dst,
1474                 unsigned int size, unsigned int *nbytesp)
1475 {
1476         unsigned int copy, drest = *drestp, nbytes = *nbytesp;
1477         int idx = 0;
1478
1479         if (drest < size || size > nbytes)
1480                 return -EINVAL;
1481
1482         while (size) {
1483                 copy = min(drest, min(size, dst->length));
1484
1485                 size -= copy;
1486                 drest -= copy;
1487                 nbytes -= copy;
1488
1489                 dprintk("%s: copy: %u, size: %u, drest: %u, nbytes: %u.\n",
1490                                 __func__, copy, size, drest, nbytes);
1491
1492                 dst++;
1493                 idx++;
1494         }
1495
1496         *nbytesp = nbytes;
1497         *drestp = drest;
1498
1499         return idx;
1500 }
1501
1502 static int ablkcipher_walk(struct ablkcipher_request *req,
1503                 struct ablkcipher_walk *w)
1504 {
1505         struct scatterlist *dst, *t;
1506         unsigned int nbytes = req->nbytes, offset, copy, diff;
1507         int idx, tidx, err;
1508
1509         tidx = idx = 0;
1510         offset = 0;
1511         while (nbytes) {
1512                 if (idx >= w->num && (w->flags & ASYNC_FLAGS_MISALIGNED))
1513                         return -EINVAL;
1514
1515                 dst = &req->dst[idx];
1516
1517                 dprintk("\n%s: dlen: %u, doff: %u, offset: %u, nbytes: %u.\n",
1518                         __func__, dst->length, dst->offset, offset, nbytes);
1519
1520                 if (!IS_ALIGNED(dst->offset, HIFN_D_DST_DALIGN) ||
1521                     !IS_ALIGNED(dst->length, HIFN_D_DST_DALIGN) ||
1522                     offset) {
1523                         unsigned slen = min(dst->length - offset, nbytes);
1524                         unsigned dlen = PAGE_SIZE;
1525
1526                         t = &w->cache[idx];
1527
1528                         err = ablkcipher_add(&dlen, dst, slen, &nbytes);
1529                         if (err < 0)
1530                                 return err;
1531
1532                         idx += err;
1533
1534                         copy = slen & ~(HIFN_D_DST_DALIGN - 1);
1535                         diff = slen & (HIFN_D_DST_DALIGN - 1);
1536
1537                         if (dlen < nbytes) {
1538                                 /*
1539                                  * Destination page does not have enough space
1540                                  * to put there additional blocksized chunk,
1541                                  * so we mark that page as containing only
1542                                  * blocksize aligned chunks:
1543                                  *      t->length = (slen & ~(HIFN_D_DST_DALIGN - 1));
1544                                  * and increase number of bytes to be processed
1545                                  * in next chunk:
1546                                  *      nbytes += diff;
1547                                  */
1548                                 nbytes += diff;
1549
1550                                 /*
1551                                  * Temporary of course...
1552                                  * Kick author if you will catch this one.
1553                                  */
1554                                 printk(KERN_ERR "%s: dlen: %u, nbytes: %u,"
1555                                         "slen: %u, offset: %u.\n",
1556                                         __func__, dlen, nbytes, slen, offset);
1557                                 printk(KERN_ERR "%s: please contact author to fix this "
1558                                         "issue, generally you should not catch "
1559                                         "this path under any condition but who "
1560                                         "knows how did you use crypto code.\n"
1561                                         "Thank you.\n", __func__);
1562                                 BUG();
1563                         } else {
1564                                 copy += diff + nbytes;
1565
1566                                 dst = &req->dst[idx];
1567
1568                                 err = ablkcipher_add(&dlen, dst, nbytes, &nbytes);
1569                                 if (err < 0)
1570                                         return err;
1571
1572                                 idx += err;
1573                         }
1574
1575                         t->length = copy;
1576                         t->offset = offset;
1577                 } else {
1578                         nbytes -= min(dst->length, nbytes);
1579                         idx++;
1580                 }
1581
1582                 tidx++;
1583         }
1584
1585         return tidx;
1586 }
1587
1588 static int hifn_setup_session(struct ablkcipher_request *req)
1589 {
1590         struct hifn_context *ctx = crypto_tfm_ctx(req->base.tfm);
1591         struct hifn_request_context *rctx = ablkcipher_request_ctx(req);
1592         struct hifn_device *dev = ctx->dev;
1593         unsigned long dlen, flags;
1594         unsigned int nbytes = req->nbytes, idx = 0;
1595         int err = -EINVAL, sg_num;
1596         struct scatterlist *dst;
1597
1598         if (rctx->iv && !rctx->ivsize && rctx->mode != ACRYPTO_MODE_ECB)
1599                 goto err_out_exit;
1600
1601         rctx->walk.flags = 0;
1602
1603         while (nbytes) {
1604                 dst = &req->dst[idx];
1605                 dlen = min(dst->length, nbytes);
1606
1607                 if (!IS_ALIGNED(dst->offset, HIFN_D_DST_DALIGN) ||
1608                     !IS_ALIGNED(dlen, HIFN_D_DST_DALIGN))
1609                         rctx->walk.flags |= ASYNC_FLAGS_MISALIGNED;
1610
1611                 nbytes -= dlen;
1612                 idx++;
1613         }
1614
1615         if (rctx->walk.flags & ASYNC_FLAGS_MISALIGNED) {
1616                 err = ablkcipher_walk_init(&rctx->walk, idx, GFP_ATOMIC);
1617                 if (err < 0)
1618                         return err;
1619         }
1620
1621         sg_num = ablkcipher_walk(req, &rctx->walk);
1622         if (sg_num < 0) {
1623                 err = sg_num;
1624                 goto err_out_exit;
1625         }
1626
1627         spin_lock_irqsave(&dev->lock, flags);
1628         if (dev->started + sg_num > HIFN_QUEUE_LENGTH) {
1629                 err = -EAGAIN;
1630                 goto err_out;
1631         }
1632
1633         dev->snum++;
1634         dev->started++;
1635
1636         err = hifn_setup_dma(dev, ctx, rctx, req->src, req->dst, req->nbytes, req);
1637         if (err)
1638                 goto err_out;
1639
1640         dev->active = HIFN_DEFAULT_ACTIVE_NUM;
1641         spin_unlock_irqrestore(&dev->lock, flags);
1642
1643         return 0;
1644
1645 err_out:
1646         spin_unlock_irqrestore(&dev->lock, flags);
1647 err_out_exit:
1648         if (err)
1649                 dprintk("%s: iv: %p [%d], key: %p [%d], mode: %u, op: %u, "
1650                                 "type: %u, err: %d.\n",
1651                         dev->name, rctx->iv, rctx->ivsize,
1652                         ctx->key, ctx->keysize,
1653                         rctx->mode, rctx->op, rctx->type, err);
1654
1655         return err;
1656 }
1657
1658 static int hifn_test(struct hifn_device *dev, int encdec, u8 snum)
1659 {
1660         int n, err;
1661         u8 src[16];
1662         struct hifn_context ctx;
1663         struct hifn_request_context rctx;
1664         u8 fips_aes_ecb_from_zero[16] = {
1665                 0x66, 0xE9, 0x4B, 0xD4,
1666                 0xEF, 0x8A, 0x2C, 0x3B,
1667                 0x88, 0x4C, 0xFA, 0x59,
1668                 0xCA, 0x34, 0x2B, 0x2E};
1669         struct scatterlist sg;
1670
1671         memset(src, 0, sizeof(src));
1672         memset(ctx.key, 0, sizeof(ctx.key));
1673
1674         ctx.dev = dev;
1675         ctx.keysize = 16;
1676         rctx.ivsize = 0;
1677         rctx.iv = NULL;
1678         rctx.op = (encdec)?ACRYPTO_OP_ENCRYPT:ACRYPTO_OP_DECRYPT;
1679         rctx.mode = ACRYPTO_MODE_ECB;
1680         rctx.type = ACRYPTO_TYPE_AES_128;
1681         rctx.walk.cache[0].length = 0;
1682
1683         sg_init_one(&sg, &src, sizeof(src));
1684
1685         err = hifn_setup_dma(dev, &ctx, &rctx, &sg, &sg, sizeof(src), NULL);
1686         if (err)
1687                 goto err_out;
1688
1689         msleep(200);
1690
1691         dprintk("%s: decoded: ", dev->name);
1692         for (n=0; n<sizeof(src); ++n)
1693                 dprintk("%02x ", src[n]);
1694         dprintk("\n");
1695         dprintk("%s: FIPS   : ", dev->name);
1696         for (n=0; n<sizeof(fips_aes_ecb_from_zero); ++n)
1697                 dprintk("%02x ", fips_aes_ecb_from_zero[n]);
1698         dprintk("\n");
1699
1700         if (!memcmp(src, fips_aes_ecb_from_zero, sizeof(fips_aes_ecb_from_zero))) {
1701                 printk(KERN_INFO "%s: AES 128 ECB test has been successfully "
1702                                 "passed.\n", dev->name);
1703                 return 0;
1704         }
1705
1706 err_out:
1707         printk(KERN_INFO "%s: AES 128 ECB test has been failed.\n", dev->name);
1708         return -1;
1709 }
1710
1711 static int hifn_start_device(struct hifn_device *dev)
1712 {
1713         int err;
1714
1715         hifn_reset_dma(dev, 1);
1716
1717         err = hifn_enable_crypto(dev);
1718         if (err)
1719                 return err;
1720
1721         hifn_reset_puc(dev);
1722
1723         hifn_init_dma(dev);
1724
1725         hifn_init_registers(dev);
1726
1727         hifn_init_pubrng(dev);
1728
1729         return 0;
1730 }
1731
1732 static int ablkcipher_get(void *saddr, unsigned int *srestp, unsigned int offset,
1733                 struct scatterlist *dst, unsigned int size, unsigned int *nbytesp)
1734 {
1735         unsigned int srest = *srestp, nbytes = *nbytesp, copy;
1736         void *daddr;
1737         int idx = 0;
1738
1739         if (srest < size || size > nbytes)
1740                 return -EINVAL;
1741
1742         while (size) {
1743                 copy = min(srest, min(dst->length, size));
1744
1745                 daddr = kmap_atomic(sg_page(dst), KM_IRQ0);
1746                 memcpy(daddr + dst->offset + offset, saddr, copy);
1747                 kunmap_atomic(daddr, KM_IRQ0);
1748
1749                 nbytes -= copy;
1750                 size -= copy;
1751                 srest -= copy;
1752                 saddr += copy;
1753                 offset = 0;
1754
1755                 dprintk("%s: copy: %u, size: %u, srest: %u, nbytes: %u.\n",
1756                                 __func__, copy, size, srest, nbytes);
1757
1758                 dst++;
1759                 idx++;
1760         }
1761
1762         *nbytesp = nbytes;
1763         *srestp = srest;
1764
1765         return idx;
1766 }
1767
1768 static void hifn_process_ready(struct ablkcipher_request *req, int error)
1769 {
1770         struct hifn_context *ctx = crypto_tfm_ctx(req->base.tfm);
1771         struct hifn_request_context *rctx = ablkcipher_request_ctx(req);
1772         struct hifn_device *dev;
1773
1774         dprintk("%s: req: %p, ctx: %p rctx: %p.\n", __func__, req, ctx, rctx);
1775
1776         dev = ctx->dev;
1777         dprintk("%s: req: %p, started: %d.\n", __func__, req, dev->started);
1778
1779         if (--dev->started < 0)
1780                 BUG();
1781
1782         if (rctx->walk.flags & ASYNC_FLAGS_MISALIGNED) {
1783                 unsigned int nbytes = req->nbytes;
1784                 int idx = 0, err;
1785                 struct scatterlist *dst, *t;
1786                 void *saddr;
1787
1788                 while (nbytes) {
1789                         t = &rctx->walk.cache[idx];
1790                         dst = &req->dst[idx];
1791
1792                         dprintk("\n%s: sg_page(t): %p, t->length: %u, "
1793                                 "sg_page(dst): %p, dst->length: %u, "
1794                                 "nbytes: %u.\n",
1795                                 __func__, sg_page(t), t->length,
1796                                 sg_page(dst), dst->length, nbytes);
1797
1798                         if (!t->length) {
1799                                 nbytes -= min(dst->length, nbytes);
1800                                 idx++;
1801                                 continue;
1802                         }
1803
1804                         saddr = kmap_atomic(sg_page(t), KM_IRQ1);
1805
1806                         err = ablkcipher_get(saddr, &t->length, t->offset,
1807                                         dst, nbytes, &nbytes);
1808                         if (err < 0) {
1809                                 kunmap_atomic(saddr, KM_IRQ1);
1810                                 break;
1811                         }
1812
1813                         idx += err;
1814                         kunmap_atomic(saddr, KM_IRQ1);
1815                 }
1816
1817                 ablkcipher_walk_exit(&rctx->walk);
1818         }
1819
1820         req->base.complete(&req->base, error);
1821 }
1822
1823 static void hifn_check_for_completion(struct hifn_device *dev, int error)
1824 {
1825         int i;
1826         struct hifn_dma *dma = (struct hifn_dma *)dev->desc_virt;
1827
1828         for (i=0; i<HIFN_D_RES_RSIZE; ++i) {
1829                 struct hifn_desc *d = &dma->resr[i];
1830
1831                 if (!(d->l & __cpu_to_le32(HIFN_D_VALID)) && dev->sa[i]) {
1832                         dev->success++;
1833                         dev->reset = 0;
1834                         hifn_process_ready(dev->sa[i], error);
1835                         dev->sa[i] = NULL;
1836                 }
1837
1838                 if (d->l & __cpu_to_le32(HIFN_D_DESTOVER | HIFN_D_OVER))
1839                         if (printk_ratelimit())
1840                                 printk("%s: overflow detected [d: %u, o: %u] "
1841                                                 "at %d resr: l: %08x, p: %08x.\n",
1842                                         dev->name,
1843                                         !!(d->l & __cpu_to_le32(HIFN_D_DESTOVER)),
1844                                         !!(d->l & __cpu_to_le32(HIFN_D_OVER)),
1845                                         i, d->l, d->p);
1846         }
1847 }
1848
1849 static void hifn_clear_rings(struct hifn_device *dev)
1850 {
1851         struct hifn_dma *dma = (struct hifn_dma *)dev->desc_virt;
1852         int i, u;
1853
1854         dprintk("%s: ring cleanup 1: i: %d.%d.%d.%d, u: %d.%d.%d.%d, "
1855                         "k: %d.%d.%d.%d.\n",
1856                         dev->name,
1857                         dma->cmdi, dma->srci, dma->dsti, dma->resi,
1858                         dma->cmdu, dma->srcu, dma->dstu, dma->resu,
1859                         dma->cmdk, dma->srck, dma->dstk, dma->resk);
1860
1861         i = dma->resk; u = dma->resu;
1862         while (u != 0) {
1863                 if (dma->resr[i].l & __cpu_to_le32(HIFN_D_VALID))
1864                         break;
1865
1866                 if (i != HIFN_D_RES_RSIZE)
1867                         u--;
1868
1869                 if (++i == (HIFN_D_RES_RSIZE + 1))
1870                         i = 0;
1871         }
1872         dma->resk = i; dma->resu = u;
1873
1874         i = dma->srck; u = dma->srcu;
1875         while (u != 0) {
1876                 if (i == HIFN_D_SRC_RSIZE)
1877                         i = 0;
1878                 if (dma->srcr[i].l & __cpu_to_le32(HIFN_D_VALID))
1879                         break;
1880                 i++, u--;
1881         }
1882         dma->srck = i; dma->srcu = u;
1883
1884         i = dma->cmdk; u = dma->cmdu;
1885         while (u != 0) {
1886                 if (dma->cmdr[i].l & __cpu_to_le32(HIFN_D_VALID))
1887                         break;
1888                 if (i != HIFN_D_CMD_RSIZE)
1889                         u--;
1890                 if (++i == (HIFN_D_CMD_RSIZE + 1))
1891                         i = 0;
1892         }
1893         dma->cmdk = i; dma->cmdu = u;
1894
1895         i = dma->dstk; u = dma->dstu;
1896         while (u != 0) {
1897                 if (i == HIFN_D_DST_RSIZE)
1898                         i = 0;
1899                 if (dma->dstr[i].l & __cpu_to_le32(HIFN_D_VALID))
1900                         break;
1901                 i++, u--;
1902         }
1903         dma->dstk = i; dma->dstu = u;
1904
1905         dprintk("%s: ring cleanup 2: i: %d.%d.%d.%d, u: %d.%d.%d.%d, "
1906                         "k: %d.%d.%d.%d.\n",
1907                         dev->name,
1908                         dma->cmdi, dma->srci, dma->dsti, dma->resi,
1909                         dma->cmdu, dma->srcu, dma->dstu, dma->resu,
1910                         dma->cmdk, dma->srck, dma->dstk, dma->resk);
1911 }
1912
1913 static void hifn_work(struct work_struct *work)
1914 {
1915         struct delayed_work *dw = container_of(work, struct delayed_work, work);
1916         struct hifn_device *dev = container_of(dw, struct hifn_device, work);
1917         unsigned long flags;
1918         int reset = 0;
1919         u32 r = 0;
1920
1921         spin_lock_irqsave(&dev->lock, flags);
1922         if (dev->active == 0) {
1923                 struct hifn_dma *dma = (struct hifn_dma *)dev->desc_virt;
1924
1925                 if (dma->cmdu == 0 && (dev->flags & HIFN_FLAG_CMD_BUSY)) {
1926                         dev->flags &= ~HIFN_FLAG_CMD_BUSY;
1927                         r |= HIFN_DMACSR_C_CTRL_DIS;
1928                 }
1929                 if (dma->srcu == 0 && (dev->flags & HIFN_FLAG_SRC_BUSY)) {
1930                         dev->flags &= ~HIFN_FLAG_SRC_BUSY;
1931                         r |= HIFN_DMACSR_S_CTRL_DIS;
1932                 }
1933                 if (dma->dstu == 0 && (dev->flags & HIFN_FLAG_DST_BUSY)) {
1934                         dev->flags &= ~HIFN_FLAG_DST_BUSY;
1935                         r |= HIFN_DMACSR_D_CTRL_DIS;
1936                 }
1937                 if (dma->resu == 0 && (dev->flags & HIFN_FLAG_RES_BUSY)) {
1938                         dev->flags &= ~HIFN_FLAG_RES_BUSY;
1939                         r |= HIFN_DMACSR_R_CTRL_DIS;
1940                 }
1941                 if (r)
1942                         hifn_write_1(dev, HIFN_1_DMA_CSR, r);
1943         } else
1944                 dev->active--;
1945
1946         if (dev->prev_success == dev->success && dev->started)
1947                 reset = 1;
1948         dev->prev_success = dev->success;
1949         spin_unlock_irqrestore(&dev->lock, flags);
1950
1951         if (reset) {
1952                 dprintk("%s: r: %08x, active: %d, started: %d, "
1953                                 "success: %lu: reset: %d.\n",
1954                         dev->name, r, dev->active, dev->started,
1955                         dev->success, reset);
1956
1957                 if (++dev->reset >= 5) {
1958                         dprintk("%s: really hard reset.\n", dev->name);
1959                         hifn_reset_dma(dev, 1);
1960                         hifn_stop_device(dev);
1961                         hifn_start_device(dev);
1962                         dev->reset = 0;
1963                 }
1964
1965                 spin_lock_irqsave(&dev->lock, flags);
1966                 hifn_check_for_completion(dev, -EBUSY);
1967                 hifn_clear_rings(dev);
1968                 dev->started = 0;
1969                 spin_unlock_irqrestore(&dev->lock, flags);
1970         }
1971
1972         schedule_delayed_work(&dev->work, HZ);
1973 }
1974
1975 static irqreturn_t hifn_interrupt(int irq, void *data)
1976 {
1977         struct hifn_device *dev = (struct hifn_device *)data;
1978         struct hifn_dma *dma = (struct hifn_dma *)dev->desc_virt;
1979         u32 dmacsr, restart;
1980
1981         dmacsr = hifn_read_1(dev, HIFN_1_DMA_CSR);
1982
1983         dprintk("%s: 1 dmacsr: %08x, dmareg: %08x, res: %08x [%d], "
1984                         "i: %d.%d.%d.%d, u: %d.%d.%d.%d.\n",
1985                 dev->name, dmacsr, dev->dmareg, dmacsr & dev->dmareg, dma->cmdi,
1986                 dma->cmdu, dma->srcu, dma->dstu, dma->resu,
1987                 dma->cmdi, dma->srci, dma->dsti, dma->resi);
1988
1989         if ((dmacsr & dev->dmareg) == 0)
1990                 return IRQ_NONE;
1991
1992         hifn_write_1(dev, HIFN_1_DMA_CSR, dmacsr & dev->dmareg);
1993
1994         if (dmacsr & HIFN_DMACSR_ENGINE)
1995                 hifn_write_0(dev, HIFN_0_PUISR, hifn_read_0(dev, HIFN_0_PUISR));
1996         if (dmacsr & HIFN_DMACSR_PUBDONE)
1997                 hifn_write_1(dev, HIFN_1_PUB_STATUS,
1998                         hifn_read_1(dev, HIFN_1_PUB_STATUS) | HIFN_PUBSTS_DONE);
1999
2000         restart = dmacsr & (HIFN_DMACSR_R_OVER | HIFN_DMACSR_D_OVER);
2001         if (restart) {
2002                 u32 puisr = hifn_read_0(dev, HIFN_0_PUISR);
2003
2004                 if (printk_ratelimit())
2005                         printk("%s: overflow: r: %d, d: %d, puisr: %08x, d: %u.\n",
2006                                 dev->name, !!(dmacsr & HIFN_DMACSR_R_OVER),
2007                                 !!(dmacsr & HIFN_DMACSR_D_OVER),
2008                                 puisr, !!(puisr & HIFN_PUISR_DSTOVER));
2009                 if (!!(puisr & HIFN_PUISR_DSTOVER))
2010                         hifn_write_0(dev, HIFN_0_PUISR, HIFN_PUISR_DSTOVER);
2011                 hifn_write_1(dev, HIFN_1_DMA_CSR, dmacsr & (HIFN_DMACSR_R_OVER |
2012                                         HIFN_DMACSR_D_OVER));
2013         }
2014
2015         restart = dmacsr & (HIFN_DMACSR_C_ABORT | HIFN_DMACSR_S_ABORT |
2016                         HIFN_DMACSR_D_ABORT | HIFN_DMACSR_R_ABORT);
2017         if (restart) {
2018                 if (printk_ratelimit())
2019                         printk("%s: abort: c: %d, s: %d, d: %d, r: %d.\n",
2020                                 dev->name, !!(dmacsr & HIFN_DMACSR_C_ABORT),
2021                                 !!(dmacsr & HIFN_DMACSR_S_ABORT),
2022                                 !!(dmacsr & HIFN_DMACSR_D_ABORT),
2023                                 !!(dmacsr & HIFN_DMACSR_R_ABORT));
2024                 hifn_reset_dma(dev, 1);
2025                 hifn_init_dma(dev);
2026                 hifn_init_registers(dev);
2027         }
2028
2029         if ((dmacsr & HIFN_DMACSR_C_WAIT) && (dma->cmdu == 0)) {
2030                 dprintk("%s: wait on command.\n", dev->name);
2031                 dev->dmareg &= ~(HIFN_DMAIER_C_WAIT);
2032                 hifn_write_1(dev, HIFN_1_DMA_IER, dev->dmareg);
2033         }
2034
2035         tasklet_schedule(&dev->tasklet);
2036         hifn_clear_rings(dev);
2037
2038         return IRQ_HANDLED;
2039 }
2040
2041 static void hifn_flush(struct hifn_device *dev)
2042 {
2043         unsigned long flags;
2044         struct crypto_async_request *async_req;
2045         struct hifn_context *ctx;
2046         struct ablkcipher_request *req;
2047         struct hifn_dma *dma = (struct hifn_dma *)dev->desc_virt;
2048         int i;
2049
2050         spin_lock_irqsave(&dev->lock, flags);
2051         for (i=0; i<HIFN_D_RES_RSIZE; ++i) {
2052                 struct hifn_desc *d = &dma->resr[i];
2053
2054                 if (dev->sa[i]) {
2055                         hifn_process_ready(dev->sa[i],
2056                                 (d->l & __cpu_to_le32(HIFN_D_VALID))?-ENODEV:0);
2057                 }
2058         }
2059
2060         while ((async_req = crypto_dequeue_request(&dev->queue))) {
2061                 ctx = crypto_tfm_ctx(async_req->tfm);
2062                 req = container_of(async_req, struct ablkcipher_request, base);
2063
2064                 hifn_process_ready(req, -ENODEV);
2065         }
2066         spin_unlock_irqrestore(&dev->lock, flags);
2067 }
2068
2069 static int hifn_setkey(struct crypto_ablkcipher *cipher, const u8 *key,
2070                 unsigned int len)
2071 {
2072         struct crypto_tfm *tfm = crypto_ablkcipher_tfm(cipher);
2073         struct hifn_context *ctx = crypto_tfm_ctx(tfm);
2074         struct hifn_device *dev = ctx->dev;
2075
2076         if (len > HIFN_MAX_CRYPT_KEY_LENGTH) {
2077                 crypto_ablkcipher_set_flags(cipher, CRYPTO_TFM_RES_BAD_KEY_LEN);
2078                 return -1;
2079         }
2080
2081         if (len == HIFN_DES_KEY_LENGTH) {
2082                 u32 tmp[DES_EXPKEY_WORDS];
2083                 int ret = des_ekey(tmp, key);
2084                 
2085                 if (unlikely(ret == 0) && (tfm->crt_flags & CRYPTO_TFM_REQ_WEAK_KEY)) {
2086                         tfm->crt_flags |= CRYPTO_TFM_RES_WEAK_KEY;
2087                         return -EINVAL;
2088                 }
2089         }
2090
2091         dev->flags &= ~HIFN_FLAG_OLD_KEY;
2092
2093         memcpy(ctx->key, key, len);
2094         ctx->keysize = len;
2095
2096         return 0;
2097 }
2098
2099 static int hifn_handle_req(struct ablkcipher_request *req)
2100 {
2101         struct hifn_context *ctx = crypto_tfm_ctx(req->base.tfm);
2102         struct hifn_device *dev = ctx->dev;
2103         int err = -EAGAIN;
2104
2105         if (dev->started + DIV_ROUND_UP(req->nbytes, PAGE_SIZE) <= HIFN_QUEUE_LENGTH)
2106                 err = hifn_setup_session(req);
2107
2108         if (err == -EAGAIN) {
2109                 unsigned long flags;
2110
2111                 spin_lock_irqsave(&dev->lock, flags);
2112                 err = ablkcipher_enqueue_request(&dev->queue, req);
2113                 spin_unlock_irqrestore(&dev->lock, flags);
2114         }
2115
2116         return err;
2117 }
2118
2119 static int hifn_setup_crypto_req(struct ablkcipher_request *req, u8 op,
2120                 u8 type, u8 mode)
2121 {
2122         struct hifn_context *ctx = crypto_tfm_ctx(req->base.tfm);
2123         struct hifn_request_context *rctx = ablkcipher_request_ctx(req);
2124         unsigned ivsize;
2125
2126         ivsize = crypto_ablkcipher_ivsize(crypto_ablkcipher_reqtfm(req));
2127
2128         if (req->info && mode != ACRYPTO_MODE_ECB) {
2129                 if (type == ACRYPTO_TYPE_AES_128)
2130                         ivsize = HIFN_AES_IV_LENGTH;
2131                 else if (type == ACRYPTO_TYPE_DES)
2132                         ivsize = HIFN_DES_KEY_LENGTH;
2133                 else if (type == ACRYPTO_TYPE_3DES)
2134                         ivsize = HIFN_3DES_KEY_LENGTH;
2135         }
2136
2137         if (ctx->keysize != 16 && type == ACRYPTO_TYPE_AES_128) {
2138                 if (ctx->keysize == 24)
2139                         type = ACRYPTO_TYPE_AES_192;
2140                 else if (ctx->keysize == 32)
2141                         type = ACRYPTO_TYPE_AES_256;
2142         }
2143
2144         rctx->op = op;
2145         rctx->mode = mode;
2146         rctx->type = type;
2147         rctx->iv = req->info;
2148         rctx->ivsize = ivsize;
2149
2150         /*
2151          * HEAVY TODO: needs to kick Herbert XU to write documentation.
2152          * HEAVY TODO: needs to kick Herbert XU to write documentation.
2153          * HEAVY TODO: needs to kick Herbert XU to write documentation.
2154          */
2155
2156         return hifn_handle_req(req);
2157 }
2158
2159 static int hifn_process_queue(struct hifn_device *dev)
2160 {
2161         struct crypto_async_request *async_req, *backlog;
2162         struct hifn_context *ctx;
2163         struct ablkcipher_request *req;
2164         unsigned long flags;
2165         int err = 0;
2166
2167         while (dev->started < HIFN_QUEUE_LENGTH) {
2168                 spin_lock_irqsave(&dev->lock, flags);
2169                 backlog = crypto_get_backlog(&dev->queue);
2170                 async_req = crypto_dequeue_request(&dev->queue);
2171                 spin_unlock_irqrestore(&dev->lock, flags);
2172
2173                 if (!async_req)
2174                         break;
2175
2176                 if (backlog)
2177                         backlog->complete(backlog, -EINPROGRESS);
2178
2179                 ctx = crypto_tfm_ctx(async_req->tfm);
2180                 req = container_of(async_req, struct ablkcipher_request, base);
2181
2182                 err = hifn_handle_req(req);
2183                 if (err)
2184                         break;
2185         }
2186
2187         return err;
2188 }
2189
2190 static int hifn_setup_crypto(struct ablkcipher_request *req, u8 op,
2191                 u8 type, u8 mode)
2192 {
2193         int err;
2194         struct hifn_context *ctx = crypto_tfm_ctx(req->base.tfm);
2195         struct hifn_device *dev = ctx->dev;
2196
2197         err = hifn_setup_crypto_req(req, op, type, mode);
2198         if (err)
2199                 return err;
2200
2201         if (dev->started < HIFN_QUEUE_LENGTH && dev->queue.qlen)
2202                 hifn_process_queue(dev);
2203
2204         return -EINPROGRESS;
2205 }
2206
2207 /*
2208  * AES ecryption functions.
2209  */
2210 static inline int hifn_encrypt_aes_ecb(struct ablkcipher_request *req)
2211 {
2212         return hifn_setup_crypto(req, ACRYPTO_OP_ENCRYPT,
2213                         ACRYPTO_TYPE_AES_128, ACRYPTO_MODE_ECB);
2214 }
2215 static inline int hifn_encrypt_aes_cbc(struct ablkcipher_request *req)
2216 {
2217         return hifn_setup_crypto(req, ACRYPTO_OP_ENCRYPT,
2218                         ACRYPTO_TYPE_AES_128, ACRYPTO_MODE_CBC);
2219 }
2220 static inline int hifn_encrypt_aes_cfb(struct ablkcipher_request *req)
2221 {
2222         return hifn_setup_crypto(req, ACRYPTO_OP_ENCRYPT,
2223                         ACRYPTO_TYPE_AES_128, ACRYPTO_MODE_CFB);
2224 }
2225 static inline int hifn_encrypt_aes_ofb(struct ablkcipher_request *req)
2226 {
2227         return hifn_setup_crypto(req, ACRYPTO_OP_ENCRYPT,
2228                         ACRYPTO_TYPE_AES_128, ACRYPTO_MODE_OFB);
2229 }
2230
2231 /*
2232  * AES decryption functions.
2233  */
2234 static inline int hifn_decrypt_aes_ecb(struct ablkcipher_request *req)
2235 {
2236         return hifn_setup_crypto(req, ACRYPTO_OP_DECRYPT,
2237                         ACRYPTO_TYPE_AES_128, ACRYPTO_MODE_ECB);
2238 }
2239 static inline int hifn_decrypt_aes_cbc(struct ablkcipher_request *req)
2240 {
2241         return hifn_setup_crypto(req, ACRYPTO_OP_DECRYPT,
2242                         ACRYPTO_TYPE_AES_128, ACRYPTO_MODE_CBC);
2243 }
2244 static inline int hifn_decrypt_aes_cfb(struct ablkcipher_request *req)
2245 {
2246         return hifn_setup_crypto(req, ACRYPTO_OP_DECRYPT,
2247                         ACRYPTO_TYPE_AES_128, ACRYPTO_MODE_CFB);
2248 }
2249 static inline int hifn_decrypt_aes_ofb(struct ablkcipher_request *req)
2250 {
2251         return hifn_setup_crypto(req, ACRYPTO_OP_DECRYPT,
2252                         ACRYPTO_TYPE_AES_128, ACRYPTO_MODE_OFB);
2253 }
2254
2255 /*
2256  * DES ecryption functions.
2257  */
2258 static inline int hifn_encrypt_des_ecb(struct ablkcipher_request *req)
2259 {
2260         return hifn_setup_crypto(req, ACRYPTO_OP_ENCRYPT,
2261                         ACRYPTO_TYPE_DES, ACRYPTO_MODE_ECB);
2262 }
2263 static inline int hifn_encrypt_des_cbc(struct ablkcipher_request *req)
2264 {
2265         return hifn_setup_crypto(req, ACRYPTO_OP_ENCRYPT,
2266                         ACRYPTO_TYPE_DES, ACRYPTO_MODE_CBC);
2267 }
2268 static inline int hifn_encrypt_des_cfb(struct ablkcipher_request *req)
2269 {
2270         return hifn_setup_crypto(req, ACRYPTO_OP_ENCRYPT,
2271                         ACRYPTO_TYPE_DES, ACRYPTO_MODE_CFB);
2272 }
2273 static inline int hifn_encrypt_des_ofb(struct ablkcipher_request *req)
2274 {
2275         return hifn_setup_crypto(req, ACRYPTO_OP_ENCRYPT,
2276                         ACRYPTO_TYPE_DES, ACRYPTO_MODE_OFB);
2277 }
2278
2279 /*
2280  * DES decryption functions.
2281  */
2282 static inline int hifn_decrypt_des_ecb(struct ablkcipher_request *req)
2283 {
2284         return hifn_setup_crypto(req, ACRYPTO_OP_DECRYPT,
2285                         ACRYPTO_TYPE_DES, ACRYPTO_MODE_ECB);
2286 }
2287 static inline int hifn_decrypt_des_cbc(struct ablkcipher_request *req)
2288 {
2289         return hifn_setup_crypto(req, ACRYPTO_OP_DECRYPT,
2290                         ACRYPTO_TYPE_DES, ACRYPTO_MODE_CBC);
2291 }
2292 static inline int hifn_decrypt_des_cfb(struct ablkcipher_request *req)
2293 {
2294         return hifn_setup_crypto(req, ACRYPTO_OP_DECRYPT,
2295                         ACRYPTO_TYPE_DES, ACRYPTO_MODE_CFB);
2296 }
2297 static inline int hifn_decrypt_des_ofb(struct ablkcipher_request *req)
2298 {
2299         return hifn_setup_crypto(req, ACRYPTO_OP_DECRYPT,
2300                         ACRYPTO_TYPE_DES, ACRYPTO_MODE_OFB);
2301 }
2302
2303 /*
2304  * 3DES ecryption functions.
2305  */
2306 static inline int hifn_encrypt_3des_ecb(struct ablkcipher_request *req)
2307 {
2308         return hifn_setup_crypto(req, ACRYPTO_OP_ENCRYPT,
2309                         ACRYPTO_TYPE_3DES, ACRYPTO_MODE_ECB);
2310 }
2311 static inline int hifn_encrypt_3des_cbc(struct ablkcipher_request *req)
2312 {
2313         return hifn_setup_crypto(req, ACRYPTO_OP_ENCRYPT,
2314                         ACRYPTO_TYPE_3DES, ACRYPTO_MODE_CBC);
2315 }
2316 static inline int hifn_encrypt_3des_cfb(struct ablkcipher_request *req)
2317 {
2318         return hifn_setup_crypto(req, ACRYPTO_OP_ENCRYPT,
2319                         ACRYPTO_TYPE_3DES, ACRYPTO_MODE_CFB);
2320 }
2321 static inline int hifn_encrypt_3des_ofb(struct ablkcipher_request *req)
2322 {
2323         return hifn_setup_crypto(req, ACRYPTO_OP_ENCRYPT,
2324                         ACRYPTO_TYPE_3DES, ACRYPTO_MODE_OFB);
2325 }
2326
2327 /*
2328  * 3DES decryption functions.
2329  */
2330 static inline int hifn_decrypt_3des_ecb(struct ablkcipher_request *req)
2331 {
2332         return hifn_setup_crypto(req, ACRYPTO_OP_DECRYPT,
2333                         ACRYPTO_TYPE_3DES, ACRYPTO_MODE_ECB);
2334 }
2335 static inline int hifn_decrypt_3des_cbc(struct ablkcipher_request *req)
2336 {
2337         return hifn_setup_crypto(req, ACRYPTO_OP_DECRYPT,
2338                         ACRYPTO_TYPE_3DES, ACRYPTO_MODE_CBC);
2339 }
2340 static inline int hifn_decrypt_3des_cfb(struct ablkcipher_request *req)
2341 {
2342         return hifn_setup_crypto(req, ACRYPTO_OP_DECRYPT,
2343                         ACRYPTO_TYPE_3DES, ACRYPTO_MODE_CFB);
2344 }
2345 static inline int hifn_decrypt_3des_ofb(struct ablkcipher_request *req)
2346 {
2347         return hifn_setup_crypto(req, ACRYPTO_OP_DECRYPT,
2348                         ACRYPTO_TYPE_3DES, ACRYPTO_MODE_OFB);
2349 }
2350
2351 struct hifn_alg_template
2352 {
2353         char name[CRYPTO_MAX_ALG_NAME];
2354         char drv_name[CRYPTO_MAX_ALG_NAME];
2355         unsigned int bsize;
2356         struct ablkcipher_alg ablkcipher;
2357 };
2358
2359 static struct hifn_alg_template hifn_alg_templates[] = {
2360         /*
2361          * 3DES ECB, CBC, CFB and OFB modes.
2362          */
2363         {
2364                 .name = "cfb(des3_ede)", .drv_name = "cfb-3des", .bsize = 8,
2365                 .ablkcipher = {
2366                         .min_keysize    =       HIFN_3DES_KEY_LENGTH,
2367                         .max_keysize    =       HIFN_3DES_KEY_LENGTH,
2368                         .setkey         =       hifn_setkey,
2369                         .encrypt        =       hifn_encrypt_3des_cfb,
2370                         .decrypt        =       hifn_decrypt_3des_cfb,
2371                 },
2372         },
2373         {
2374                 .name = "ofb(des3_ede)", .drv_name = "ofb-3des", .bsize = 8,
2375                 .ablkcipher = {
2376                         .min_keysize    =       HIFN_3DES_KEY_LENGTH,
2377                         .max_keysize    =       HIFN_3DES_KEY_LENGTH,
2378                         .setkey         =       hifn_setkey,
2379                         .encrypt        =       hifn_encrypt_3des_ofb,
2380                         .decrypt        =       hifn_decrypt_3des_ofb,
2381                 },
2382         },
2383         {
2384                 .name = "cbc(des3_ede)", .drv_name = "cbc-3des", .bsize = 8,
2385                 .ablkcipher = {
2386                         .ivsize         =       HIFN_IV_LENGTH,
2387                         .min_keysize    =       HIFN_3DES_KEY_LENGTH,
2388                         .max_keysize    =       HIFN_3DES_KEY_LENGTH,
2389                         .setkey         =       hifn_setkey,
2390                         .encrypt        =       hifn_encrypt_3des_cbc,
2391                         .decrypt        =       hifn_decrypt_3des_cbc,
2392                 },
2393         },
2394         {
2395                 .name = "ecb(des3_ede)", .drv_name = "ecb-3des", .bsize = 8,
2396                 .ablkcipher = {
2397                         .min_keysize    =       HIFN_3DES_KEY_LENGTH,
2398                         .max_keysize    =       HIFN_3DES_KEY_LENGTH,
2399                         .setkey         =       hifn_setkey,
2400                         .encrypt        =       hifn_encrypt_3des_ecb,
2401                         .decrypt        =       hifn_decrypt_3des_ecb,
2402                 },
2403         },
2404
2405         /*
2406          * DES ECB, CBC, CFB and OFB modes.
2407          */
2408         {
2409                 .name = "cfb(des)", .drv_name = "cfb-des", .bsize = 8,
2410                 .ablkcipher = {
2411                         .min_keysize    =       HIFN_DES_KEY_LENGTH,
2412                         .max_keysize    =       HIFN_DES_KEY_LENGTH,
2413                         .setkey         =       hifn_setkey,
2414                         .encrypt        =       hifn_encrypt_des_cfb,
2415                         .decrypt        =       hifn_decrypt_des_cfb,
2416                 },
2417         },
2418         {
2419                 .name = "ofb(des)", .drv_name = "ofb-des", .bsize = 8,
2420                 .ablkcipher = {
2421                         .min_keysize    =       HIFN_DES_KEY_LENGTH,
2422                         .max_keysize    =       HIFN_DES_KEY_LENGTH,
2423                         .setkey         =       hifn_setkey,
2424                         .encrypt        =       hifn_encrypt_des_ofb,
2425                         .decrypt        =       hifn_decrypt_des_ofb,
2426                 },
2427         },
2428         {
2429                 .name = "cbc(des)", .drv_name = "cbc-des", .bsize = 8,
2430                 .ablkcipher = {
2431                         .ivsize         =       HIFN_IV_LENGTH,
2432                         .min_keysize    =       HIFN_DES_KEY_LENGTH,
2433                         .max_keysize    =       HIFN_DES_KEY_LENGTH,
2434                         .setkey         =       hifn_setkey,
2435                         .encrypt        =       hifn_encrypt_des_cbc,
2436                         .decrypt        =       hifn_decrypt_des_cbc,
2437                 },
2438         },
2439         {
2440                 .name = "ecb(des)", .drv_name = "ecb-des", .bsize = 8,
2441                 .ablkcipher = {
2442                         .min_keysize    =       HIFN_DES_KEY_LENGTH,
2443                         .max_keysize    =       HIFN_DES_KEY_LENGTH,
2444                         .setkey         =       hifn_setkey,
2445                         .encrypt        =       hifn_encrypt_des_ecb,
2446                         .decrypt        =       hifn_decrypt_des_ecb,
2447                 },
2448         },
2449
2450         /*
2451          * AES ECB, CBC, CFB and OFB modes.
2452          */
2453         {
2454                 .name = "ecb(aes)", .drv_name = "ecb-aes", .bsize = 16,
2455                 .ablkcipher = {
2456                         .min_keysize    =       AES_MIN_KEY_SIZE,
2457                         .max_keysize    =       AES_MAX_KEY_SIZE,
2458                         .setkey         =       hifn_setkey,
2459                         .encrypt        =       hifn_encrypt_aes_ecb,
2460                         .decrypt        =       hifn_decrypt_aes_ecb,
2461                 },
2462         },
2463         {
2464                 .name = "cbc(aes)", .drv_name = "cbc-aes", .bsize = 16,
2465                 .ablkcipher = {
2466                         .ivsize         =       HIFN_AES_IV_LENGTH,
2467                         .min_keysize    =       AES_MIN_KEY_SIZE,
2468                         .max_keysize    =       AES_MAX_KEY_SIZE,
2469                         .setkey         =       hifn_setkey,
2470                         .encrypt        =       hifn_encrypt_aes_cbc,
2471                         .decrypt        =       hifn_decrypt_aes_cbc,
2472                 },
2473         },
2474         {
2475                 .name = "cfb(aes)", .drv_name = "cfb-aes", .bsize = 16,
2476                 .ablkcipher = {
2477                         .min_keysize    =       AES_MIN_KEY_SIZE,
2478                         .max_keysize    =       AES_MAX_KEY_SIZE,
2479                         .setkey         =       hifn_setkey,
2480                         .encrypt        =       hifn_encrypt_aes_cfb,
2481                         .decrypt        =       hifn_decrypt_aes_cfb,
2482                 },
2483         },
2484         {
2485                 .name = "ofb(aes)", .drv_name = "ofb-aes", .bsize = 16,
2486                 .ablkcipher = {
2487                         .min_keysize    =       AES_MIN_KEY_SIZE,
2488                         .max_keysize    =       AES_MAX_KEY_SIZE,
2489                         .setkey         =       hifn_setkey,
2490                         .encrypt        =       hifn_encrypt_aes_ofb,
2491                         .decrypt        =       hifn_decrypt_aes_ofb,
2492                 },
2493         },
2494 };
2495
2496 static int hifn_cra_init(struct crypto_tfm *tfm)
2497 {
2498         struct crypto_alg *alg = tfm->__crt_alg;
2499         struct hifn_crypto_alg *ha = crypto_alg_to_hifn(alg);
2500         struct hifn_context *ctx = crypto_tfm_ctx(tfm);
2501
2502         ctx->dev = ha->dev;
2503         tfm->crt_ablkcipher.reqsize = sizeof(struct hifn_request_context);
2504         return 0;
2505 }
2506
2507 static int hifn_alg_alloc(struct hifn_device *dev, struct hifn_alg_template *t)
2508 {
2509         struct hifn_crypto_alg *alg;
2510         int err;
2511
2512         alg = kzalloc(sizeof(struct hifn_crypto_alg), GFP_KERNEL);
2513         if (!alg)
2514                 return -ENOMEM;
2515
2516         snprintf(alg->alg.cra_name, CRYPTO_MAX_ALG_NAME, "%s", t->name);
2517         snprintf(alg->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME, "%s-%s",
2518                  t->drv_name, dev->name);
2519
2520         alg->alg.cra_priority = 300;
2521         alg->alg.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC;
2522         alg->alg.cra_blocksize = t->bsize;
2523         alg->alg.cra_ctxsize = sizeof(struct hifn_context);
2524         alg->alg.cra_alignmask = 0;
2525         alg->alg.cra_type = &crypto_ablkcipher_type;
2526         alg->alg.cra_module = THIS_MODULE;
2527         alg->alg.cra_u.ablkcipher = t->ablkcipher;
2528         alg->alg.cra_init = hifn_cra_init;
2529
2530         alg->dev = dev;
2531
2532         list_add_tail(&alg->entry, &dev->alg_list);
2533
2534         err = crypto_register_alg(&alg->alg);
2535         if (err) {
2536                 list_del(&alg->entry);
2537                 kfree(alg);
2538         }
2539
2540         return err;
2541 }
2542
2543 static void hifn_unregister_alg(struct hifn_device *dev)
2544 {
2545         struct hifn_crypto_alg *a, *n;
2546
2547         list_for_each_entry_safe(a, n, &dev->alg_list, entry) {
2548                 list_del(&a->entry);
2549                 crypto_unregister_alg(&a->alg);
2550                 kfree(a);
2551         }
2552 }
2553
2554 static int hifn_register_alg(struct hifn_device *dev)
2555 {
2556         int i, err;
2557
2558         for (i=0; i<ARRAY_SIZE(hifn_alg_templates); ++i) {
2559                 err = hifn_alg_alloc(dev, &hifn_alg_templates[i]);
2560                 if (err)
2561                         goto err_out_exit;
2562         }
2563
2564         return 0;
2565
2566 err_out_exit:
2567         hifn_unregister_alg(dev);
2568         return err;
2569 }
2570
2571 static void hifn_tasklet_callback(unsigned long data)
2572 {
2573         struct hifn_device *dev = (struct hifn_device *)data;
2574
2575         /*
2576          * This is ok to call this without lock being held,
2577          * althogh it modifies some parameters used in parallel,
2578          * (like dev->success), but they are used in process
2579          * context or update is atomic (like setting dev->sa[i] to NULL).
2580          */
2581         hifn_check_for_completion(dev, 0);
2582
2583         if (dev->started < HIFN_QUEUE_LENGTH && dev->queue.qlen)
2584                 hifn_process_queue(dev);
2585 }
2586
2587 static int hifn_probe(struct pci_dev *pdev, const struct pci_device_id *id)
2588 {
2589         int err, i;
2590         struct hifn_device *dev;
2591         char name[8];
2592
2593         err = pci_enable_device(pdev);
2594         if (err)
2595                 return err;
2596         pci_set_master(pdev);
2597
2598         err = pci_set_dma_mask(pdev, DMA_32BIT_MASK);
2599         if (err)
2600                 goto err_out_disable_pci_device;
2601
2602         snprintf(name, sizeof(name), "hifn%d",
2603                         atomic_inc_return(&hifn_dev_number)-1);
2604
2605         err = pci_request_regions(pdev, name);
2606         if (err)
2607                 goto err_out_disable_pci_device;
2608
2609         if (pci_resource_len(pdev, 0) < HIFN_BAR0_SIZE ||
2610             pci_resource_len(pdev, 1) < HIFN_BAR1_SIZE ||
2611             pci_resource_len(pdev, 2) < HIFN_BAR2_SIZE) {
2612                 dprintk("%s: Broken hardware - I/O regions are too small.\n",
2613                                 pci_name(pdev));
2614                 err = -ENODEV;
2615                 goto err_out_free_regions;
2616         }
2617
2618         dev = kzalloc(sizeof(struct hifn_device) + sizeof(struct crypto_alg),
2619                         GFP_KERNEL);
2620         if (!dev) {
2621                 err = -ENOMEM;
2622                 goto err_out_free_regions;
2623         }
2624
2625         INIT_LIST_HEAD(&dev->alg_list);
2626
2627         snprintf(dev->name, sizeof(dev->name), "%s", name);
2628         spin_lock_init(&dev->lock);
2629
2630         for (i=0; i<3; ++i) {
2631                 unsigned long addr, size;
2632
2633                 addr = pci_resource_start(pdev, i);
2634                 size = pci_resource_len(pdev, i);
2635
2636                 dev->bar[i] = ioremap_nocache(addr, size);
2637                 if (!dev->bar[i])
2638                         goto err_out_unmap_bars;
2639         }
2640
2641         dev->result_mem = __get_free_pages(GFP_KERNEL, HIFN_MAX_RESULT_ORDER);
2642         if (!dev->result_mem) {
2643                 dprintk("Failed to allocate %d pages for result_mem.\n",
2644                                 HIFN_MAX_RESULT_ORDER);
2645                 goto err_out_unmap_bars;
2646         }
2647         memset((void *)dev->result_mem, 0, PAGE_SIZE*(1<<HIFN_MAX_RESULT_ORDER));
2648
2649         dev->dst = pci_map_single(pdev, (void *)dev->result_mem,
2650                         PAGE_SIZE << HIFN_MAX_RESULT_ORDER, PCI_DMA_FROMDEVICE);
2651
2652         dev->desc_virt = pci_alloc_consistent(pdev, sizeof(struct hifn_dma),
2653                         &dev->desc_dma);
2654         if (!dev->desc_virt) {
2655                 dprintk("Failed to allocate descriptor rings.\n");
2656                 goto err_out_free_result_pages;
2657         }
2658         memset(dev->desc_virt, 0, sizeof(struct hifn_dma));
2659
2660         dev->pdev = pdev;
2661         dev->irq = pdev->irq;
2662
2663         for (i=0; i<HIFN_D_RES_RSIZE; ++i)
2664                 dev->sa[i] = NULL;
2665
2666         pci_set_drvdata(pdev, dev);
2667
2668         tasklet_init(&dev->tasklet, hifn_tasklet_callback, (unsigned long)dev);
2669
2670         crypto_init_queue(&dev->queue, 1);
2671
2672         err = request_irq(dev->irq, hifn_interrupt, IRQF_SHARED, dev->name, dev);
2673         if (err) {
2674                 dprintk("Failed to request IRQ%d: err: %d.\n", dev->irq, err);
2675                 dev->irq = 0;
2676                 goto err_out_free_desc;
2677         }
2678
2679         err = hifn_start_device(dev);
2680         if (err)
2681                 goto err_out_free_irq;
2682
2683         err = hifn_test(dev, 1, 0);
2684         if (err)
2685                 goto err_out_stop_device;
2686
2687         err = hifn_register_rng(dev);
2688         if (err)
2689                 goto err_out_stop_device;
2690
2691         err = hifn_register_alg(dev);
2692         if (err)
2693                 goto err_out_unregister_rng;
2694
2695         INIT_DELAYED_WORK(&dev->work, hifn_work);
2696         schedule_delayed_work(&dev->work, HZ);
2697
2698         dprintk("HIFN crypto accelerator card at %s has been "
2699                         "successfully registered as %s.\n",
2700                         pci_name(pdev), dev->name);
2701
2702         return 0;
2703
2704 err_out_unregister_rng:
2705         hifn_unregister_rng(dev);
2706 err_out_stop_device:
2707         hifn_reset_dma(dev, 1);
2708         hifn_stop_device(dev);
2709 err_out_free_irq:
2710         free_irq(dev->irq, dev->name);
2711         tasklet_kill(&dev->tasklet);
2712 err_out_free_desc:
2713         pci_free_consistent(pdev, sizeof(struct hifn_dma),
2714                         dev->desc_virt, dev->desc_dma);
2715
2716 err_out_free_result_pages:
2717         pci_unmap_single(pdev, dev->dst, PAGE_SIZE << HIFN_MAX_RESULT_ORDER,
2718                         PCI_DMA_FROMDEVICE);
2719         free_pages(dev->result_mem, HIFN_MAX_RESULT_ORDER);
2720
2721 err_out_unmap_bars:
2722         for (i=0; i<3; ++i)
2723                 if (dev->bar[i])
2724                         iounmap(dev->bar[i]);
2725
2726 err_out_free_regions:
2727         pci_release_regions(pdev);
2728
2729 err_out_disable_pci_device:
2730         pci_disable_device(pdev);
2731
2732         return err;
2733 }
2734
2735 static void hifn_remove(struct pci_dev *pdev)
2736 {
2737         int i;
2738         struct hifn_device *dev;
2739
2740         dev = pci_get_drvdata(pdev);
2741
2742         if (dev) {
2743                 cancel_delayed_work(&dev->work);
2744                 flush_scheduled_work();
2745
2746                 hifn_unregister_rng(dev);
2747                 hifn_unregister_alg(dev);
2748                 hifn_reset_dma(dev, 1);
2749                 hifn_stop_device(dev);
2750
2751                 free_irq(dev->irq, dev->name);
2752                 tasklet_kill(&dev->tasklet);
2753
2754                 hifn_flush(dev);
2755
2756                 pci_free_consistent(pdev, sizeof(struct hifn_dma),
2757                                 dev->desc_virt, dev->desc_dma);
2758                 pci_unmap_single(pdev, dev->dst,
2759                                 PAGE_SIZE << HIFN_MAX_RESULT_ORDER,
2760                                 PCI_DMA_FROMDEVICE);
2761                 free_pages(dev->result_mem, HIFN_MAX_RESULT_ORDER);
2762                 for (i=0; i<3; ++i)
2763                         if (dev->bar[i])
2764                                 iounmap(dev->bar[i]);
2765
2766                 kfree(dev);
2767         }
2768
2769         pci_release_regions(pdev);
2770         pci_disable_device(pdev);
2771 }
2772
2773 static struct pci_device_id hifn_pci_tbl[] = {
2774         { PCI_DEVICE(PCI_VENDOR_ID_HIFN, PCI_DEVICE_ID_HIFN_7955) },
2775         { PCI_DEVICE(PCI_VENDOR_ID_HIFN, PCI_DEVICE_ID_HIFN_7956) },
2776         { 0 }
2777 };
2778 MODULE_DEVICE_TABLE(pci, hifn_pci_tbl);
2779
2780 static struct pci_driver hifn_pci_driver = {
2781         .name     = "hifn795x",
2782         .id_table = hifn_pci_tbl,
2783         .probe    = hifn_probe,
2784         .remove   = __devexit_p(hifn_remove),
2785 };
2786
2787 static int __devinit hifn_init(void)
2788 {
2789         unsigned int freq;
2790         int err;
2791
2792         if (sizeof(dma_addr_t) > 4) {
2793                 printk(KERN_INFO "HIFN supports only 32-bit addresses.\n");
2794                 return -EINVAL;
2795         }
2796
2797         if (strncmp(hifn_pll_ref, "ext", 3) &&
2798             strncmp(hifn_pll_ref, "pci", 3)) {
2799                 printk(KERN_ERR "hifn795x: invalid hifn_pll_ref clock, "
2800                                 "must be pci or ext");
2801                 return -EINVAL;
2802         }
2803
2804         /*
2805          * For the 7955/7956 the reference clock frequency must be in the
2806          * range of 20MHz-100MHz. For the 7954 the upper bound is 66.67MHz,
2807          * but this chip is currently not supported.
2808          */
2809         if (hifn_pll_ref[3] != '\0') {
2810                 freq = simple_strtoul(hifn_pll_ref + 3, NULL, 10);
2811                 if (freq < 20 || freq > 100) {
2812                         printk(KERN_ERR "hifn795x: invalid hifn_pll_ref "
2813                                         "frequency, must be in the range "
2814                                         "of 20-100");
2815                         return -EINVAL;
2816                 }
2817         }
2818
2819         err = pci_register_driver(&hifn_pci_driver);
2820         if (err < 0) {
2821                 dprintk("Failed to register PCI driver for %s device.\n",
2822                                 hifn_pci_driver.name);
2823                 return -ENODEV;
2824         }
2825
2826         printk(KERN_INFO "Driver for HIFN 795x crypto accelerator chip "
2827                         "has been successfully registered.\n");
2828
2829         return 0;
2830 }
2831
2832 static void __devexit hifn_fini(void)
2833 {
2834         pci_unregister_driver(&hifn_pci_driver);
2835
2836         printk(KERN_INFO "Driver for HIFN 795x crypto accelerator chip "
2837                         "has been successfully unregistered.\n");
2838 }
2839
2840 module_init(hifn_init);
2841 module_exit(hifn_fini);
2842
2843 MODULE_LICENSE("GPL");
2844 MODULE_AUTHOR("Evgeniy Polyakov <johnpol@2ka.mipt.ru>");
2845 MODULE_DESCRIPTION("Driver for HIFN 795x crypto accelerator chip.");