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