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