ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / s390 / crypto / z90main.c
1 /*
2  *  linux/drivers/s390/misc/z90main.c
3  *
4  *  z90crypt 1.3.1
5  *
6  *  Copyright (C)  2001, 2004 IBM Corporation
7  *  Author(s): Robert Burroughs (burrough@us.ibm.com)
8  *             Eric Rossman (edrossma@us.ibm.com)
9  *
10  *  Hotplug & misc device support: Jochen Roehrig (roehrig@de.ibm.com)
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2, or (at your option)
15  * any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25  */
26
27 #include <asm/uaccess.h>       // copy_(from|to)_user
28 #include <linux/compat.h>
29 #include <linux/compiler.h>
30 #include <linux/delay.h>       // mdelay
31 #include <linux/init.h>
32 #include <linux/interrupt.h>   // for tasklets
33 #include <linux/ioctl32.h>
34 #include <linux/module.h>
35 #include <linux/moduleparam.h>
36 #include <linux/proc_fs.h>
37 #include <linux/syscalls.h>
38 #include <linux/version.h>
39 #include "z90crypt.h"
40 #include "z90common.h"
41 #ifndef Z90CRYPT_USE_HOTPLUG
42 #include <linux/miscdevice.h>
43 #endif
44
45 #define VERSION_CODE(vers, rel, seq) (((vers)<<16) | ((rel)<<8) | (seq))
46 #if LINUX_VERSION_CODE < VERSION_CODE(2,4,0) /* version < 2.4 */
47 #  error "This kernel is too old: not supported"
48 #endif
49 #if LINUX_VERSION_CODE > VERSION_CODE(2,7,0) /* version > 2.6 */
50 #  error "This kernel is too recent: not supported by this file"
51 #endif
52
53 #define VERSION_Z90MAIN_C "$Revision: 1.31 $"
54
55 static char z90cmain_version[] __initdata =
56         "z90main.o (" VERSION_Z90MAIN_C "/"
57                       VERSION_Z90COMMON_H "/" VERSION_Z90CRYPT_H ")";
58
59 extern char z90chardware_version[];
60
61 /**
62  * Defaults that may be modified.
63  */
64
65 #ifndef Z90CRYPT_USE_HOTPLUG
66 /**
67  * You can specify a different minor at compile time.
68  */
69 #ifndef Z90CRYPT_MINOR
70 #define Z90CRYPT_MINOR  MISC_DYNAMIC_MINOR
71 #endif
72 #else
73 /**
74  * You can specify a different major at compile time.
75  */
76 #ifndef Z90CRYPT_MAJOR
77 #define Z90CRYPT_MAJOR  0
78 #endif
79 #endif
80
81 /**
82  * You can specify a different domain at compile time or on the insmod
83  * command line.
84  */
85 #ifndef DOMAIN_INDEX
86 #define DOMAIN_INDEX    -1
87 #endif
88
89 /**
90  * This is the name under which the device is registered in /proc/modules.
91  */
92 #define REG_NAME        "z90crypt"
93
94 /**
95  * Cleanup should run every CLEANUPTIME seconds and should clean up requests
96  * older than CLEANUPTIME seconds in the past.
97  */
98 #ifndef CLEANUPTIME
99 #define CLEANUPTIME 15
100 #endif
101
102 /**
103  * Config should run every CONFIGTIME seconds
104  */
105 #ifndef CONFIGTIME
106 #define CONFIGTIME 30
107 #endif
108
109 /**
110  * The first execution of the config task should take place
111  * immediately after initialization
112  */
113 #ifndef INITIAL_CONFIGTIME
114 #define INITIAL_CONFIGTIME 1
115 #endif
116
117 /**
118  * Reader should run every READERTIME milliseconds
119  */
120 #ifndef READERTIME
121 #define READERTIME 2
122 #endif
123
124 /**
125  * turn long device array index into device pointer
126  */
127 #define LONG2DEVPTR(ndx) (z90crypt.device_p[(ndx)])
128
129 /**
130  * turn short device array index into long device array index
131  */
132 #define SHRT2LONG(ndx) (z90crypt.overall_device_x.device_index[(ndx)])
133
134 /**
135  * turn short device array index into device pointer
136  */
137 #define SHRT2DEVPTR(ndx) LONG2DEVPTR(SHRT2LONG(ndx))
138
139 /**
140  * Status for a work-element
141  */
142 #define STAT_DEFAULT    0x00 // request has not been processed
143
144 #define STAT_ROUTED     0x80 // bit 7: requests get routed to specific device
145                              //        else, device is determined each write
146 #define STAT_FAILED     0x40 // bit 6: this bit is set if the request failed
147                              //        before being sent to the hardware.
148 #define STAT_WRITTEN    0x30 // bits 5-4: work to be done, not sent to device
149 //                      0x20 // UNUSED state
150 #define STAT_READPEND   0x10 // bits 5-4: work done, we're returning data now
151 #define STAT_NOWORK     0x00 // bits off: no work on any queue
152 #define STAT_RDWRMASK   0x30 // mask for bits 5-4
153
154 /**
155  * Macros to check the status RDWRMASK
156  */
157 #define CHK_RDWRMASK(statbyte) ((statbyte) & STAT_RDWRMASK)
158 #define SET_RDWRMASK(statbyte, newval) \
159         {(statbyte) &= ~STAT_RDWRMASK; (statbyte) |= newval;}
160
161 /**
162  * Audit Trail.  Progress of a Work element
163  * audit[0]: Unless noted otherwise, these bits are all set by the process
164  */
165 #define FP_COPYFROM     0x80 // Caller's buffer has been copied to work element
166 #define FP_BUFFREQ      0x40 // Low Level buffer requested
167 #define FP_BUFFGOT      0x20 // Low Level buffer obtained
168 #define FP_SENT         0x10 // Work element sent to a crypto device
169                              // (may be set by process or by reader task)
170 #define FP_PENDING      0x08 // Work element placed on pending queue
171                              // (may be set by process or by reader task)
172 #define FP_REQUEST      0x04 // Work element placed on request queue
173 #define FP_ASLEEP       0x02 // Work element about to sleep
174 #define FP_AWAKE        0x01 // Work element has been awakened
175
176 /**
177  * audit[1]: These bits are set by the reader task and/or the cleanup task
178  */
179 #define FP_NOTPENDING     0x80 // Work element removed from pending queue
180 #define FP_AWAKENING      0x40 // Caller about to be awakened
181 #define FP_TIMEDOUT       0x20 // Caller timed out
182 #define FP_RESPSIZESET    0x10 // Response size copied to work element
183 #define FP_RESPADDRCOPIED 0x08 // Response address copied to work element
184 #define FP_RESPBUFFCOPIED 0x04 // Response buffer copied to work element
185 #define FP_REMREQUEST     0x02 // Work element removed from request queue
186 #define FP_SIGNALED       0x01 // Work element was awakened by a signal
187
188 /**
189  * audit[2]: unused
190  */
191
192 /**
193  * state of the file handle in private_data.status
194  */
195 #define STAT_OPEN 0
196 #define STAT_CLOSED 1
197
198 /**
199  * PID() expands to the process ID of the current process
200  */
201 #define PID() (current->pid)
202
203 /**
204  * Selected Constants.  The number of APs and the number of devices
205  */
206 #ifndef Z90CRYPT_NUM_APS
207 #define Z90CRYPT_NUM_APS 64
208 #endif
209 #ifndef Z90CRYPT_NUM_DEVS
210 #define Z90CRYPT_NUM_DEVS Z90CRYPT_NUM_APS
211 #endif
212 #ifndef Z90CRYPT_NUM_TYPES
213 #define Z90CRYPT_NUM_TYPES 3
214 #endif
215
216 /**
217  * Buffer size for receiving responses. The maximum Response Size
218  * is actually the maximum request size, since in an error condition
219  * the request itself may be returned unchanged.
220  */
221 #ifndef MAX_RESPONSE_SIZE
222 #define MAX_RESPONSE_SIZE 0x0000077C
223 #endif
224
225 /**
226  * A count and status-byte mask
227  */
228 struct status {
229         int           st_count;             // # of enabled devices
230         int           disabled_count;       // # of disabled devices
231         int           user_disabled_count;  // # of devices disabled via proc fs
232         unsigned char st_mask[Z90CRYPT_NUM_APS]; // current status mask
233 };
234
235 /**
236  * The array of device indexes is a mechanism for fast indexing into
237  * a long (and sparse) array.  For instance, if APs 3, 9 and 47 are
238  * installed, z90CDeviceIndex[0] is 3, z90CDeviceIndex[1] is 9, and
239  * z90CDeviceIndex[2] is 47.
240  */
241 struct device_x {
242         int device_index[Z90CRYPT_NUM_DEVS];
243 };
244
245 /**
246  * All devices are arranged in a single array: 64 APs
247  */
248 struct device {
249         int              dev_type;          // PCICA, PCICC, or PCIXCC
250         enum devstat     dev_stat;          // current device status
251         int              dev_self_x;        // Index in array
252         int              disabled;          // Set when device is in error
253         int              user_disabled;     // Set when device is disabled by user
254         int              dev_q_depth;       // q depth
255         unsigned char *  dev_resp_p;        // Response buffer address
256         int              dev_resp_l;        // Response Buffer length
257         int              dev_caller_count;  // Number of callers
258         int              dev_total_req_cnt; // # requests for device since load
259         struct list_head dev_caller_list;   // List of callers
260 };
261
262 /**
263  * There's a struct status and a struct device_x for each device type.
264  */
265 struct hdware_block {
266         struct status   hdware_mask;
267         struct status   type_mask[Z90CRYPT_NUM_TYPES];
268         struct device_x type_x_addr[Z90CRYPT_NUM_TYPES];
269         unsigned char   device_type_array[Z90CRYPT_NUM_APS];
270 };
271
272 /**
273  * z90crypt is the topmost data structure in the hierarchy.
274  */
275 struct z90crypt {
276         int                  max_count;         // Nr of possible crypto devices
277         struct status        mask;
278         int                  q_depth_array[Z90CRYPT_NUM_DEVS];
279         int                  dev_type_array[Z90CRYPT_NUM_DEVS];
280         struct device_x      overall_device_x;  // array device indexes
281         struct device *      device_p[Z90CRYPT_NUM_DEVS];
282         int                  terminating;
283         int                  domain_established;// TRUE:  domain has been found
284         int                  cdx;               // Crypto Domain Index
285         int                  len;               // Length of this data structure
286         struct hdware_block *hdware_info;
287 };
288
289 /**
290  * An array of these structures is pointed to from dev_caller
291  * The length of the array depends on the device type. For APs,
292  * there are 8.
293  *
294  * The caller buffer is allocated to the user at OPEN. At WRITE,
295  * it contains the request; at READ, the response. The function
296  * send_to_crypto_device converts the request to device-dependent
297  * form and use the caller's OPEN-allocated buffer for the response.
298  */
299 struct caller {
300         int              caller_buf_l;           // length of original request
301         unsigned char *  caller_buf_p;           // Original request on WRITE
302         int              caller_dev_dep_req_l;   // len device dependent request
303         unsigned char *  caller_dev_dep_req_p;   // Device dependent form
304         unsigned char    caller_id[8];           // caller-supplied message id
305         struct list_head caller_liste;
306         unsigned char    caller_dev_dep_req[MAX_RESPONSE_SIZE];
307 };
308
309 /**
310  * Function prototypes from z90hardware.c
311  */
312 enum hdstat query_online(int, int, int, int *, int *);
313 enum devstat reset_device(int, int, int);
314 enum devstat send_to_AP(int, int, int, unsigned char *);
315 enum devstat receive_from_AP(int, int, int, unsigned char *, unsigned char *);
316 int convert_request(unsigned char *, int, short, int, int, int *,
317                     unsigned char *);
318 int convert_response(unsigned char *, unsigned char *, int *, unsigned char *);
319
320 /**
321  * Low level function prototypes
322  */
323 static int create_z90crypt(int *);
324 static int refresh_z90crypt(int *);
325 static int find_crypto_devices(struct status *);
326 static int create_crypto_device(int);
327 static int destroy_crypto_device(int);
328 static void destroy_z90crypt(void);
329 static int refresh_index_array(struct status *, struct device_x *);
330 static int probe_device_type(struct device *);
331
332 /**
333  * proc fs definitions
334  */
335 static struct proc_dir_entry *z90crypt_entry;
336
337 /**
338  * data structures
339  */
340
341 /**
342  * work_element.opener points back to this structure
343  */
344 struct priv_data {
345         pid_t   opener_pid;
346         unsigned char   status;         // 0: open  1: closed
347 };
348
349 /**
350  * A work element is allocated for each request
351  */
352 struct work_element {
353         struct priv_data *priv_data;
354         pid_t             pid;
355         int               devindex;       // index of device processing this w_e
356                                           // (If request did not specify device,
357                                           // -1 until placed onto a queue)
358         int               devtype;
359         struct list_head  liste;          // used for requestq and pendingq
360         char              buffer[128];    // local copy of user request
361         int               buff_size;      // size of the buffer for the request
362         char              resp_buff[RESPBUFFSIZE];
363         int               resp_buff_size;
364         char *            resp_addr;      // address of response in user space
365         unsigned int      funccode;       // function code of request
366         wait_queue_head_t waitq;
367         unsigned long     requestsent;    // time at which the request was sent
368         atomic_t          alarmrung;      // wake-up signal
369         unsigned char     caller_id[8];   // pid + counter, for this w_e
370         unsigned char     status[1];      // bits to mark status of the request
371         unsigned char     audit[3];       // record of work element's progress
372         unsigned char *   requestptr;     // address of request buffer
373         int               retcode;        // return code of request
374 };
375
376 /**
377  * High level function prototypes
378  */
379 static int z90crypt_open(struct inode *, struct file *);
380 static int z90crypt_release(struct inode *, struct file *);
381 static ssize_t z90crypt_read(struct file *, char *, size_t, loff_t *);
382 static ssize_t z90crypt_write(struct file *, const char *, size_t, loff_t *);
383 static int z90crypt_ioctl(struct inode *, struct file *,
384                           unsigned int, unsigned long);
385
386 static void z90crypt_reader_task(unsigned long);
387 static void z90crypt_schedule_reader_task(unsigned long);
388 static void z90crypt_config_task(unsigned long);
389 static void z90crypt_cleanup_task(unsigned long);
390
391 static int z90crypt_status(char *, char **, off_t, int, int *, void *);
392 static int z90crypt_status_write(struct file *, const char *,
393                                  unsigned long, void *);
394
395 /**
396  * Hotplug support
397  */
398
399 #ifdef Z90CRYPT_USE_HOTPLUG
400 #define Z90CRYPT_HOTPLUG_ADD     1
401 #define Z90CRYPT_HOTPLUG_REMOVE  2
402
403 static void z90crypt_hotplug_event(int, int, int);
404 #endif
405
406 /**
407  * Storage allocated at initialization and used throughout the life of
408  * this insmod
409  */
410 #ifdef Z90CRYPT_USE_HOTPLUG
411 static int z90crypt_major = Z90CRYPT_MAJOR;
412 #endif
413
414 static int domain = DOMAIN_INDEX;
415 static struct z90crypt z90crypt;
416 static int quiesce_z90crypt;
417 static spinlock_t queuespinlock;
418 static struct list_head request_list;
419 static int requestq_count;
420 static struct list_head pending_list;
421 static int pendingq_count;
422
423 static struct tasklet_struct reader_tasklet;
424 static struct timer_list reader_timer;
425 static struct timer_list config_timer;
426 static struct timer_list cleanup_timer;
427 static atomic_t total_open;
428 static atomic_t z90crypt_step;
429
430 static struct file_operations z90crypt_fops = {
431         .owner   = THIS_MODULE,
432         .read    = z90crypt_read,
433         .write   = z90crypt_write,
434         .ioctl   = z90crypt_ioctl,
435         .open    = z90crypt_open,
436         .release = z90crypt_release
437 };
438
439 #ifndef Z90CRYPT_USE_HOTPLUG
440 static struct miscdevice z90crypt_misc_device = {
441         .minor      = Z90CRYPT_MINOR,
442         .name       = DEV_NAME,
443         .fops       = &z90crypt_fops,
444         .devfs_name = DEV_NAME
445 };
446 #endif
447
448 /**
449  * Documentation values.
450  */
451 MODULE_AUTHOR("zLinux Crypto Team: Robert H. Burroughs, Eric D. Rossman"
452               "and Jochen Roehrig");
453 MODULE_DESCRIPTION("zLinux Cryptographic Coprocessor device driver, "
454                    "Copyright 2001, 2004 IBM Corporation");
455 MODULE_LICENSE("GPL");
456 module_param(domain, int, 0);
457 MODULE_PARM_DESC(domain, "domain index for device");
458
459 #ifdef CONFIG_COMPAT
460 /**
461  * ioctl32 conversion routines
462  */
463 struct ica_rsa_modexpo_32 { // For 32-bit callers
464         compat_uptr_t   inputdata;
465         unsigned int    inputdatalength;
466         compat_uptr_t   outputdata;
467         unsigned int    outputdatalength;
468         compat_uptr_t   b_key;
469         compat_uptr_t   n_modulus;
470 };
471
472 static int
473 trans_modexpo32(unsigned int fd, unsigned int cmd, unsigned long arg,
474                 struct file *file)
475 {
476         struct ica_rsa_modexpo_32 *mex32u = compat_ptr(arg);
477         struct ica_rsa_modexpo_32  mex32k;
478         struct ica_rsa_modexpo    *mex64;
479         int ret = 0;
480         unsigned int i;
481
482         if (!access_ok(VERIFY_WRITE, mex32u, sizeof(struct ica_rsa_modexpo_32)))
483                 return -EFAULT;
484         mex64 = compat_alloc_user_space(sizeof(struct ica_rsa_modexpo));
485         if (!access_ok(VERIFY_WRITE, mex64, sizeof(struct ica_rsa_modexpo)))
486                 return -EFAULT;
487         if (copy_from_user(&mex32k, mex32u, sizeof(struct ica_rsa_modexpo_32)))
488                 return -EFAULT;
489         if (__put_user(compat_ptr(mex32k.inputdata), &mex64->inputdata)   ||
490             __put_user(mex32k.inputdatalength, &mex64->inputdatalength)   ||
491             __put_user(compat_ptr(mex32k.outputdata), &mex64->outputdata) ||
492             __put_user(mex32k.outputdatalength, &mex64->outputdatalength) ||
493             __put_user(compat_ptr(mex32k.b_key), &mex64->b_key)           ||
494             __put_user(compat_ptr(mex32k.n_modulus), &mex64->n_modulus))
495                 return -EFAULT;
496         ret = sys_ioctl(fd, cmd, (unsigned long)mex64);
497         if (!ret)
498                 if (__get_user(i, &mex64->outputdatalength) ||
499                     __put_user(i, &mex32u->outputdatalength))
500                         ret = -EFAULT;
501         return ret;
502 }
503
504 struct ica_rsa_modexpo_crt_32 { // For 32-bit callers
505         compat_uptr_t   inputdata;
506         unsigned int    inputdatalength;
507         compat_uptr_t   outputdata;
508         unsigned int    outputdatalength;
509         compat_uptr_t   bp_key;
510         compat_uptr_t   bq_key;
511         compat_uptr_t   np_prime;
512         compat_uptr_t   nq_prime;
513         compat_uptr_t   u_mult_inv;
514 };
515
516 static int
517 trans_modexpo_crt32(unsigned int fd, unsigned int cmd, unsigned long arg,
518                     struct file *file)
519 {
520         struct ica_rsa_modexpo_crt_32 *crt32u = compat_ptr(arg);
521         struct ica_rsa_modexpo_crt_32  crt32k;
522         struct ica_rsa_modexpo_crt    *crt64;
523         int ret = 0;
524         unsigned int i;
525
526         if (!access_ok(VERIFY_WRITE, crt32u,
527                        sizeof(struct ica_rsa_modexpo_crt_32)))
528                 return -EFAULT;
529         crt64 = compat_alloc_user_space(sizeof(struct ica_rsa_modexpo_crt));
530         if (!access_ok(VERIFY_WRITE, crt64, sizeof(struct ica_rsa_modexpo_crt)))
531                 return -EFAULT;
532         if (copy_from_user(&crt32k, crt32u,
533                            sizeof(struct ica_rsa_modexpo_crt_32)))
534                 return -EFAULT;
535         if (__put_user(compat_ptr(crt32k.inputdata), &crt64->inputdata)   ||
536             __put_user(crt32k.inputdatalength, &crt64->inputdatalength)   ||
537             __put_user(compat_ptr(crt32k.outputdata), &crt64->outputdata) ||
538             __put_user(crt32k.outputdatalength, &crt64->outputdatalength) ||
539             __put_user(compat_ptr(crt32k.bp_key), &crt64->bp_key)         ||
540             __put_user(compat_ptr(crt32k.bq_key), &crt64->bq_key)         ||
541             __put_user(compat_ptr(crt32k.np_prime), &crt64->np_prime)     ||
542             __put_user(compat_ptr(crt32k.nq_prime), &crt64->nq_prime)     ||
543             __put_user(compat_ptr(crt32k.u_mult_inv), &crt64->u_mult_inv))
544                 ret = -EFAULT;
545         if (!ret)
546                 ret = sys_ioctl(fd, cmd, (unsigned long)crt64);
547         if (!ret)
548                 if (__get_user(i, &crt64->outputdatalength) ||
549                     __put_user(i, &crt32u->outputdatalength))
550                         ret = -EFAULT;
551         return ret;
552 }
553
554 static int compatible_ioctls[] = {
555         ICAZ90STATUS, Z90QUIESCE, Z90STAT_TOTALCOUNT, Z90STAT_PCICACOUNT,
556         Z90STAT_PCICCCOUNT, Z90STAT_PCIXCCCOUNT, Z90STAT_REQUESTQ_COUNT,
557         Z90STAT_PENDINGQ_COUNT, Z90STAT_TOTALOPEN_COUNT, Z90STAT_DOMAIN_INDEX,
558         Z90STAT_STATUS_MASK, Z90STAT_QDEPTH_MASK, Z90STAT_PERDEV_REQCNT,
559 };
560
561 static void z90_unregister_ioctl32s(void)
562 {
563         int i;
564
565         unregister_ioctl32_conversion(ICARSAMODEXPO);
566         unregister_ioctl32_conversion(ICARSACRT);
567
568         for(i = 0; i < ARRAY_SIZE(compatible_ioctls); i++)
569                 unregister_ioctl32_conversion(compatible_ioctls[i]);
570 }
571
572 static int z90_register_ioctl32s(void)
573 {
574         int result, i;
575
576         result = register_ioctl32_conversion(ICARSAMODEXPO, trans_modexpo32);
577         if (result)
578                 return result;
579         result = register_ioctl32_conversion(ICARSACRT, trans_modexpo_crt32);
580         if (result)
581                 return result;
582
583         for(i = 0; i < ARRAY_SIZE(compatible_ioctls); i++) {
584                 result = register_ioctl32_conversion(compatible_ioctls[i],NULL);
585                 if (result) {
586                         z90_unregister_ioctl32s();
587                         return result;
588                 }
589         }
590         return result;
591 }
592 #else // !CONFIG_COMPAT
593 static inline void z90_unregister_ioctl32s(void)
594 {
595 }
596
597 static inline int z90_register_ioctl32s(void)
598 {
599         return 0;
600 }
601 #endif
602
603 /**
604  * The module initialization code.
605  */
606 static int __init
607 z90crypt_init_module(void)
608 {
609         int result, nresult;
610         struct proc_dir_entry *entry;
611
612         PDEBUG("PID %d\n", PID());
613
614 #ifndef Z90CRYPT_USE_HOTPLUG
615         /* Register as misc device with given minor (or get a dynamic one). */
616         result = misc_register(&z90crypt_misc_device);
617         if (result <0) {
618                 PRINTKW(KERN_ERR "misc_register (minor %d) failed with %d\n",
619                         z90crypt_misc_device.minor, result);
620                 return result;
621         }
622 #else
623         /* Register the major (or get a dynamic one). */
624         result = register_chrdev(z90crypt_major, REG_NAME, &z90crypt_fops);
625         if (result < 0) {
626                 PRINTKW("register_chrdev (major %d) failed with %d.\n",
627                         z90crypt_major, result);
628                 return result;
629         }
630
631         if (z90crypt_major == 0)
632                 z90crypt_major = result;
633 #endif
634
635         PDEBUG("Registered " DEV_NAME " with result %d\n", result);
636
637         result = create_z90crypt(&domain);
638         if (result != 0) {
639                 PRINTKW("create_z90crypt (domain index %d) failed with %d.\n",
640                         domain, result);
641                 result = -ENOMEM;
642                 goto init_module_cleanup;
643         }
644
645         if (result == 0) {
646                 PRINTKN("Version %d.%d.%d loaded, built on %s %s\n",
647                         z90crypt_VERSION, z90crypt_RELEASE, z90crypt_VARIANT,
648                         __DATE__, __TIME__);
649                 PRINTKN("%s\n", z90cmain_version);
650                 PRINTKN("%s\n", z90chardware_version);
651                 PDEBUG("create_z90crypt (domain index %d) successful.\n",
652                        domain);
653         } else
654                 PRINTK("No devices at startup\n");
655
656 #ifdef Z90CRYPT_USE_HOTPLUG
657         /* generate hotplug event for device node generation */
658         z90crypt_hotplug_event(z90crypt_major, 0, Z90CRYPT_HOTPLUG_ADD);
659 #endif
660
661         /* Initialize globals. */
662         spin_lock_init(&queuespinlock);
663
664         INIT_LIST_HEAD(&pending_list);
665         pendingq_count = 0;
666
667         INIT_LIST_HEAD(&request_list);
668         requestq_count = 0;
669
670         quiesce_z90crypt = 0;
671
672         atomic_set(&total_open, 0);
673         atomic_set(&z90crypt_step, 0);
674
675         /* Set up the cleanup task. */
676         init_timer(&cleanup_timer);
677         cleanup_timer.function = z90crypt_cleanup_task;
678         cleanup_timer.data = 0;
679         cleanup_timer.expires = jiffies + (CLEANUPTIME * HZ);
680         add_timer(&cleanup_timer);
681
682         /* Set up the proc file system */
683         entry = create_proc_entry("driver/z90crypt", 0644, 0);
684         if (entry) {
685                 entry->nlink = 1;
686                 entry->data = 0;
687                 entry->read_proc = z90crypt_status;
688                 entry->write_proc = z90crypt_status_write;
689         }
690         else
691                 PRINTK("Couldn't create z90crypt proc entry\n");
692         z90crypt_entry = entry;
693
694         /* Set up the configuration task. */
695         init_timer(&config_timer);
696         config_timer.function = z90crypt_config_task;
697         config_timer.data = 0;
698         config_timer.expires = jiffies + (INITIAL_CONFIGTIME * HZ);
699         add_timer(&config_timer);
700
701         /* Set up the reader task */
702         tasklet_init(&reader_tasklet, z90crypt_reader_task, 0);
703         init_timer(&reader_timer);
704         reader_timer.function = z90crypt_schedule_reader_task;
705         reader_timer.data = 0;
706         reader_timer.expires = jiffies + (READERTIME * HZ / 1000);
707         add_timer(&reader_timer);
708
709         if ((result = z90_register_ioctl32s()))
710                 goto init_module_cleanup;
711
712         return 0; // success
713
714 init_module_cleanup:
715         z90_unregister_ioctl32s();
716
717 #ifndef Z90CRYPT_USE_HOTPLUG
718         if ((nresult = misc_deregister(&z90crypt_misc_device)))
719                 PRINTK("misc_deregister failed with %d.\n", nresult);
720         else
721                 PDEBUG("misc_deregister successful.\n");
722 #else
723         if ((nresult = unregister_chrdev(z90crypt_major, REG_NAME)))
724                 PRINTK("unregister_chrdev failed with %d.\n", nresult);
725         else
726                 PDEBUG("unregister_chrdev successful.\n");
727 #endif
728
729         return result; // failure
730 }
731
732 /**
733  * The module termination code
734  */
735 static void __exit
736 z90crypt_cleanup_module(void)
737 {
738         int nresult;
739
740         PDEBUG("PID %d\n", PID());
741
742         z90_unregister_ioctl32s();
743
744         remove_proc_entry("driver/z90crypt", 0);
745
746 #ifndef Z90CRYPT_USE_HOTPLUG
747         if ((nresult = misc_deregister(&z90crypt_misc_device)))
748                 PRINTK("misc_deregister failed with %d.\n", nresult);
749         else
750                 PDEBUG("misc_deregister successful.\n");
751 #else
752         z90crypt_hotplug_event(z90crypt_major, 0, Z90CRYPT_HOTPLUG_REMOVE);
753
754         if ((nresult = unregister_chrdev(z90crypt_major, REG_NAME)))
755                 PRINTK("unregister_chrdev failed with %d.\n", nresult);
756         else
757                 PDEBUG("unregister_chrdev successful.\n");
758 #endif
759
760         /* Remove the tasks */
761         tasklet_kill(&reader_tasklet);
762         del_timer(&reader_timer);
763         del_timer(&config_timer);
764         del_timer(&cleanup_timer);
765
766         destroy_z90crypt();
767
768         PRINTKN("Unloaded.\n");
769 }
770
771 /**
772  * Functions running under a process id
773  *
774  * The I/O functions:
775  *     z90crypt_open
776  *     z90crypt_release
777  *     z90crypt_read
778  *     z90crypt_write
779  *     z90crypt_ioctl
780  *     z90crypt_status
781  *     z90crypt_status_write
782  *       disable_card
783  *       enable_card
784  *       scan_char
785  *       scan_string
786  *
787  * Helper functions:
788  *     z90crypt_rsa
789  *       z90crypt_prepare
790  *       z90crypt_send
791  *       z90crypt_process_results
792  *
793  */
794 static int
795 z90crypt_open(struct inode *inode, struct file *filp)
796 {
797         struct priv_data *private_data_p;
798
799         if (quiesce_z90crypt)
800                 return -EQUIESCE;
801
802         private_data_p = kmalloc(sizeof(struct priv_data), GFP_KERNEL);
803         if (!private_data_p) {
804                 PRINTK("Memory allocate failed\n");
805                 return -ENOMEM;
806         }
807
808         memset((void *)private_data_p, 0, sizeof(struct priv_data));
809         private_data_p->status = STAT_OPEN;
810         private_data_p->opener_pid = PID();
811         filp->private_data = private_data_p;
812         atomic_inc(&total_open);
813
814         return 0;
815 }
816
817 static int
818 z90crypt_release(struct inode *inode, struct file *filp)
819 {
820         struct priv_data *private_data_p = filp->private_data;
821
822         PDEBUG("PID %d (filp %p)\n", PID(), filp);
823
824         private_data_p->status = STAT_CLOSED;
825         memset(private_data_p, 0, sizeof(struct priv_data));
826         kfree(private_data_p);
827         atomic_dec(&total_open);
828
829         return 0;
830 }
831
832 /*
833  * there are two read functions, of which compile options will choose one
834  * without USE_GET_RANDOM_BYTES
835  *   => read() always returns -EPERM;
836  * otherwise
837  *   => read() uses get_random_bytes() kernel function
838  */
839 #ifndef USE_GET_RANDOM_BYTES
840 /**
841  * z90crypt_read will not be supported beyond z90crypt 1.3.1
842  */
843 static ssize_t
844 z90crypt_read(struct file *filp, char *buf, size_t count, loff_t *f_pos)
845 {
846         PDEBUG("filp %p (PID %d)\n", filp, PID());
847         return -EPERM;
848 }
849 #else // we want to use get_random_bytes
850 /**
851  * read() just returns a string of random bytes.  Since we have no way
852  * to generate these cryptographically, we just execute get_random_bytes
853  * for the length specified.
854  */
855 #include <linux/random.h>
856 static ssize_t
857 z90crypt_read(struct file *filp, char *buf, size_t count, loff_t *f_pos)
858 {
859         unsigned char *temp_buff;
860
861         PDEBUG("filp %p (PID %d)\n", filp, PID());
862
863         if (quiesce_z90crypt)
864                 return -EQUIESCE;
865         if (count < 0) {
866                 PRINTK("Requested random byte count negative: %ld\n", count);
867                 return -EINVAL;
868         }
869         if (count > RESPBUFFSIZE) {
870                 PDEBUG("count[%d] > RESPBUFFSIZE", count);
871                 return -EINVAL;
872         }
873         if (count == 0)
874                 return 0;
875         temp_buff = kmalloc(RESPBUFFSIZE, GFP_KERNEL);
876         if (!temp_buff) {
877                 PRINTK("Memory allocate failed\n");
878                 return -ENOMEM;
879         }
880         get_random_bytes(temp_buff, count);
881
882         if (copy_to_user(buf, temp_buff, count) != 0) {
883                 kfree(temp_buff);
884                 return -EFAULT;
885         }
886         kfree(temp_buff);
887         return count;
888 }
889 #endif
890
891 /**
892  * Write is is not allowed
893  */
894 static ssize_t
895 z90crypt_write(struct file *filp, const char *buf, size_t count, loff_t *f_pos)
896 {
897         PDEBUG("filp %p (PID %d)\n", filp, PID());
898         return -EPERM;
899 }
900
901 /**
902  * New status functions
903  */
904 static inline int
905 get_status_totalcount(void)
906 {
907         return z90crypt.hdware_info->hdware_mask.st_count;
908 }
909
910 static inline int
911 get_status_PCICAcount(void)
912 {
913         return z90crypt.hdware_info->type_mask[PCICA].st_count;
914 }
915
916 static inline int
917 get_status_PCICCcount(void)
918 {
919         return z90crypt.hdware_info->type_mask[PCICC].st_count;
920 }
921
922 static inline int
923 get_status_PCIXCCcount(void)
924 {
925         return z90crypt.hdware_info->type_mask[PCIXCC].st_count;
926 }
927
928 static inline int
929 get_status_requestq_count(void)
930 {
931         return requestq_count;
932 }
933
934 static inline int
935 get_status_pendingq_count(void)
936 {
937         return pendingq_count;
938 }
939
940 static inline int
941 get_status_totalopen_count(void)
942 {
943         return atomic_read(&total_open);
944 }
945
946 static inline int
947 get_status_domain_index(void)
948 {
949         return z90crypt.cdx;
950 }
951
952 static inline unsigned char *
953 get_status_status_mask(unsigned char status[Z90CRYPT_NUM_APS])
954 {
955         int i, ix;
956
957         memcpy(status, z90crypt.hdware_info->device_type_array,
958                Z90CRYPT_NUM_APS);
959
960         for (i = 0; i < get_status_totalcount(); i++) {
961                 ix = SHRT2LONG(i);
962                 if (LONG2DEVPTR(ix)->user_disabled)
963                         status[ix] = 0x0d;
964         }
965
966         return status;
967 }
968
969 static inline unsigned char *
970 get_status_qdepth_mask(unsigned char qdepth[Z90CRYPT_NUM_APS])
971 {
972         int i, ix;
973
974         memset(qdepth, 0, Z90CRYPT_NUM_APS);
975
976         for (i = 0; i < get_status_totalcount(); i++) {
977                 ix = SHRT2LONG(i);
978                 qdepth[ix] = LONG2DEVPTR(ix)->dev_caller_count;
979         }
980
981         return qdepth;
982 }
983
984 static inline unsigned int *
985 get_status_perdevice_reqcnt(unsigned int reqcnt[Z90CRYPT_NUM_APS])
986 {
987         int i, ix;
988
989         memset(reqcnt, 0, Z90CRYPT_NUM_APS * sizeof(int));
990
991         for (i = 0; i < get_status_totalcount(); i++) {
992                 ix = SHRT2LONG(i);
993                 reqcnt[ix] = LONG2DEVPTR(ix)->dev_total_req_cnt;
994         }
995
996         return reqcnt;
997 }
998
999 static inline void
1000 init_work_element(struct work_element *we_p,
1001                   struct priv_data *priv_data, pid_t pid)
1002 {
1003         int step;
1004
1005         we_p->requestptr = (unsigned char *)we_p + sizeof(struct work_element);
1006         /* Come up with a unique id for this caller. */
1007         step = atomic_inc_return(&z90crypt_step);
1008         memcpy(we_p->caller_id+0, (void *) &pid, sizeof(pid));
1009         memcpy(we_p->caller_id+4, (void *) &step, sizeof(step));
1010         we_p->pid = pid;
1011         we_p->priv_data = priv_data;
1012         we_p->status[0] = STAT_DEFAULT;
1013         we_p->audit[0] = 0x00;
1014         we_p->audit[1] = 0x00;
1015         we_p->audit[2] = 0x00;
1016         we_p->resp_buff_size = 0;
1017         we_p->retcode = 0;
1018         we_p->devindex = -1; // send_to_crypto selects the device
1019         we_p->devtype = -1;  // getCryptoBuffer selects the type
1020         atomic_set(&we_p->alarmrung, 0);
1021         init_waitqueue_head(&we_p->waitq);
1022         INIT_LIST_HEAD(&(we_p->liste));
1023 }
1024
1025 static inline int
1026 allocate_work_element(struct work_element **we_pp,
1027                       struct priv_data *priv_data_p, pid_t pid)
1028 {
1029         struct work_element *we_p;
1030
1031         we_p = (struct work_element *) get_zeroed_page(GFP_KERNEL);
1032         if (!we_p)
1033                 return -ENOMEM;
1034         init_work_element(we_p, priv_data_p, pid);
1035         *we_pp = we_p;
1036         return 0;
1037 }
1038
1039 static inline void
1040 remove_device(struct device *device_p)
1041 {
1042         if (!device_p || device_p->disabled != 0)
1043                 return;
1044         device_p->disabled = 1;
1045         z90crypt.hdware_info->type_mask[device_p->dev_type].disabled_count++;
1046         z90crypt.hdware_info->hdware_mask.disabled_count++;
1047 }
1048
1049 static inline int
1050 select_device_type(int *dev_type_p)
1051 {
1052         struct status *stat;
1053         if ((*dev_type_p != PCICC) && (*dev_type_p != PCICA) &&
1054             (*dev_type_p != PCIXCC) && (*dev_type_p != ANYDEV))
1055                 return -1;
1056         if (*dev_type_p != ANYDEV) {
1057                 stat = &z90crypt.hdware_info->type_mask[*dev_type_p];
1058                 if (stat->st_count >
1059                     stat->disabled_count + stat->user_disabled_count)
1060                         return 0;
1061                 return -1;
1062         }
1063
1064         stat = &z90crypt.hdware_info->type_mask[PCICA];
1065         if (stat->st_count > stat->disabled_count + stat->user_disabled_count) {
1066                 *dev_type_p = PCICA;
1067                 return 0;
1068         }
1069
1070         stat = &z90crypt.hdware_info->type_mask[PCIXCC];
1071         if (stat->st_count > stat->disabled_count + stat->user_disabled_count) {
1072                 *dev_type_p = PCIXCC;
1073                 return 0;
1074         }
1075
1076         stat = &z90crypt.hdware_info->type_mask[PCICC];
1077         if (stat->st_count > stat->disabled_count + stat->user_disabled_count) {
1078                 *dev_type_p = PCICC;
1079                 return 0;
1080         }
1081
1082         return -1;
1083 }
1084
1085 /**
1086  * Try the selected number, then the selected type (can be ANYDEV)
1087  */
1088 static inline int
1089 select_device(int *dev_type_p, int *device_nr_p)
1090 {
1091         int i, indx, devTp, low_count, low_indx;
1092         struct device_x *index_p;
1093         struct device *dev_ptr;
1094
1095         PDEBUG("device type = %d, index = %d\n", *dev_type_p, *device_nr_p);
1096         if ((*device_nr_p >= 0) && (*device_nr_p < Z90CRYPT_NUM_DEVS)) {
1097                 PDEBUG("trying index = %d\n", *device_nr_p);
1098                 dev_ptr = z90crypt.device_p[*device_nr_p];
1099
1100                 if (dev_ptr &&
1101                     dev_ptr->dev_stat != DEV_GONE &&
1102                     dev_ptr->disabled == 0 &&
1103                     dev_ptr->user_disabled == 0) {
1104                         PDEBUG("selected by number, index = %d\n",
1105                                *device_nr_p);
1106                         *dev_type_p = dev_ptr->dev_type;
1107                         return *device_nr_p;
1108                 }
1109         }
1110         *device_nr_p = -1;
1111         PDEBUG("trying type = %d\n", *dev_type_p);
1112         devTp = *dev_type_p;
1113         if (select_device_type(&devTp) == -1) {
1114                 PDEBUG("failed to select by type\n");
1115                 return -1;
1116         }
1117         PDEBUG("selected type = %d\n", devTp);
1118         index_p = &z90crypt.hdware_info->type_x_addr[devTp];
1119         low_count = 0x0000FFFF;
1120         low_indx = -1;
1121         for (i = 0; i < z90crypt.hdware_info->type_mask[devTp].st_count; i++) {
1122                 indx = index_p->device_index[i];
1123                 dev_ptr = z90crypt.device_p[indx];
1124                 if (dev_ptr &&
1125                     dev_ptr->dev_stat != DEV_GONE &&
1126                     dev_ptr->disabled == 0 &&
1127                     dev_ptr->user_disabled == 0 &&
1128                     devTp == dev_ptr->dev_type &&
1129                     low_count > dev_ptr->dev_caller_count) {
1130                         low_count = dev_ptr->dev_caller_count;
1131                         low_indx = indx;
1132                 }
1133         }
1134         *device_nr_p = low_indx;
1135         return low_indx;
1136 }
1137
1138 static inline int
1139 send_to_crypto_device(struct work_element *we_p)
1140 {
1141         struct caller *caller_p;
1142         struct device *device_p;
1143         int dev_nr;
1144
1145         if (!we_p->requestptr)
1146                 return SEN_FATAL_ERROR;
1147         caller_p = (struct caller *)we_p->requestptr;
1148         dev_nr = we_p->devindex;
1149         if (select_device(&we_p->devtype, &dev_nr) == -1) {
1150                 if (z90crypt.hdware_info->hdware_mask.st_count != 0)
1151                         return SEN_RETRY;
1152                 else
1153                         return SEN_NOT_AVAIL;
1154         }
1155         we_p->devindex = dev_nr;
1156         device_p = z90crypt.device_p[dev_nr];
1157         if (!device_p)
1158                 return SEN_NOT_AVAIL;
1159         if (device_p->dev_type != we_p->devtype)
1160                 return SEN_RETRY;
1161         if (device_p->dev_caller_count >= device_p->dev_q_depth)
1162                 return SEN_QUEUE_FULL;
1163         PDEBUG("device number prior to send: %d\n", dev_nr);
1164         switch (send_to_AP(dev_nr, z90crypt.cdx,
1165                            caller_p->caller_dev_dep_req_l,
1166                            caller_p->caller_dev_dep_req_p)) {
1167         case DEV_SEN_EXCEPTION:
1168                 PRINTKC("Exception during send to device %d\n", dev_nr);
1169                 z90crypt.terminating = 1;
1170                 return SEN_FATAL_ERROR;
1171         case DEV_GONE:
1172                 PRINTK("Device %d not available\n", dev_nr);
1173                 remove_device(device_p);
1174                 return SEN_NOT_AVAIL;
1175         case DEV_EMPTY:
1176                 return SEN_NOT_AVAIL;
1177         case DEV_NO_WORK:
1178                 return SEN_FATAL_ERROR;
1179         case DEV_BAD_MESSAGE:
1180                 return SEN_USER_ERROR;
1181         case DEV_QUEUE_FULL:
1182                 return SEN_QUEUE_FULL;
1183         default:
1184         case DEV_ONLINE:
1185                 break;
1186         }
1187         list_add_tail(&(caller_p->caller_liste), &(device_p->dev_caller_list));
1188         device_p->dev_caller_count++;
1189         return 0;
1190 }
1191
1192 /**
1193  * Send puts the user's work on one of two queues:
1194  *   the pending queue if the send was successful
1195  *   the request queue if the send failed because device full or busy
1196  */
1197 static inline int
1198 z90crypt_send(struct work_element *we_p, const char *buf)
1199 {
1200         int rv;
1201
1202         PDEBUG("PID %d\n", PID());
1203
1204         if (CHK_RDWRMASK(we_p->status[0]) != STAT_NOWORK) {
1205                 PDEBUG("PID %d tried to send more work but has outstanding "
1206                        "work.\n", PID());
1207                 return -EWORKPEND;
1208         }
1209         we_p->devindex = -1; // Reset device number
1210         spin_lock_irq(&queuespinlock);
1211         rv = send_to_crypto_device(we_p);
1212         switch (rv) {
1213         case 0:
1214                 we_p->requestsent = jiffies;
1215                 we_p->audit[0] |= FP_SENT;
1216                 list_add_tail(&we_p->liste, &pending_list);
1217                 ++pendingq_count;
1218                 we_p->audit[0] |= FP_PENDING;
1219                 break;
1220         case SEN_BUSY:
1221         case SEN_QUEUE_FULL:
1222                 rv = 0;
1223                 we_p->devindex = -1; // any device will do
1224                 we_p->requestsent = jiffies;
1225                 list_add_tail(&we_p->liste, &request_list);
1226                 ++requestq_count;
1227                 we_p->audit[0] |= FP_REQUEST;
1228                 break;
1229         case SEN_RETRY:
1230                 rv = -ERESTARTSYS;
1231                 break;
1232         case SEN_NOT_AVAIL:
1233                 PRINTK("*** No devices available.\n");
1234                 rv = we_p->retcode = -ENODEV;
1235                 we_p->status[0] |= STAT_FAILED;
1236                 break;
1237         case REC_OPERAND_INV:
1238         case REC_OPERAND_SIZE:
1239         case REC_EVEN_MOD:
1240         case REC_INVALID_PAD:
1241                 rv = we_p->retcode = -EINVAL;
1242                 we_p->status[0] |= STAT_FAILED;
1243                 break;
1244         default:
1245                 we_p->retcode = rv;
1246                 we_p->status[0] |= STAT_FAILED;
1247                 break;
1248         }
1249         if (rv != -ERESTARTSYS)
1250                 SET_RDWRMASK(we_p->status[0], STAT_WRITTEN);
1251         spin_unlock_irq(&queuespinlock);
1252         if (rv == 0)
1253                 tasklet_schedule(&reader_tasklet);
1254         return rv;
1255 }
1256
1257 /**
1258  * process_results copies the user's work from kernel space.
1259  */
1260 static inline int
1261 z90crypt_process_results(struct work_element *we_p, char *buf)
1262 {
1263         int rv;
1264
1265         PDEBUG("we_p %p (PID %d)\n", we_p, PID());
1266
1267         LONG2DEVPTR(we_p->devindex)->dev_total_req_cnt++;
1268         SET_RDWRMASK(we_p->status[0], STAT_READPEND);
1269
1270         rv = 0;
1271         if (!we_p->buffer) {
1272                 PRINTK("we_p %p PID %d in STAT_READPEND: buffer NULL.\n",
1273                         we_p, PID());
1274                 rv = -ENOBUFF;
1275         }
1276
1277         if (!rv)
1278                 if ((rv = copy_to_user(buf, we_p->buffer, we_p->buff_size))) {
1279                         PDEBUG("copy_to_user failed: rv = %d\n", rv);
1280                         rv = -EFAULT;
1281                 }
1282
1283         if (!rv)
1284                 rv = we_p->retcode;
1285         if (!rv)
1286                 if (we_p->resp_buff_size
1287                     &&  copy_to_user(we_p->resp_addr, we_p->resp_buff,
1288                                      we_p->resp_buff_size))
1289                         rv = -EFAULT;
1290
1291         SET_RDWRMASK(we_p->status[0], STAT_NOWORK);
1292         return rv;
1293 }
1294
1295 static unsigned char NULL_psmid[8] =
1296 {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
1297
1298 /**
1299  * MIN_MOD_SIZE is a PCICC and PCIXCC limit.
1300  * MAX_PCICC_MOD_SIZE is a hard limit for the PCICC.
1301  * MAX_MOD_SIZE is a hard limit for the PCIXCC and PCICA.
1302  */
1303 #define MIN_MOD_SIZE 64
1304 #define MAX_PCICC_MOD_SIZE 128
1305 #define MAX_MOD_SIZE 256
1306
1307 /**
1308  * Used in device configuration functions
1309  */
1310 #define MAX_RESET 90
1311
1312 /**
1313  * This is used only for PCICC support
1314  */
1315 static inline int
1316 is_PKCS11_padded(unsigned char *buffer, int length)
1317 {
1318         int i;
1319         if ((buffer[0] != 0x00) || (buffer[1] != 0x01))
1320                 return 0;
1321         for (i = 2; i < length; i++)
1322                 if (buffer[i] != 0xFF)
1323                         break;
1324         if ((i < 10) || (i == length))
1325                 return 0;
1326         if (buffer[i] != 0x00)
1327                 return 0;
1328         return 1;
1329 }
1330
1331 /**
1332  * This is used only for PCICC support
1333  */
1334 static inline int
1335 is_PKCS12_padded(unsigned char *buffer, int length)
1336 {
1337         int i;
1338         if ((buffer[0] != 0x00) || (buffer[1] != 0x02))
1339                 return 0;
1340         for (i = 2; i < length; i++)
1341                 if (buffer[i] == 0x00)
1342                         break;
1343         if ((i < 10) || (i == length))
1344                 return 0;
1345         if (buffer[i] != 0x00)
1346                 return 0;
1347         return 1;
1348 }
1349
1350 /**
1351  * builds struct caller and converts message from generic format to
1352  * device-dependent format
1353  * func is ICARSAMODEXPO or ICARSACRT
1354  * function is PCI_FUNC_KEY_ENCRYPT or PCI_FUNC_KEY_DECRYPT
1355  */
1356 static inline int
1357 build_caller(struct work_element *we_p, short function)
1358 {
1359         int rv;
1360         struct caller *caller_p = (struct caller *)we_p->requestptr;
1361
1362         if ((we_p->devtype != PCICC) && (we_p->devtype != PCICA) &&
1363             (we_p->devtype != PCIXCC))
1364                 return SEN_NOT_AVAIL;
1365
1366         memcpy(caller_p->caller_id, we_p->caller_id,
1367                sizeof(caller_p->caller_id));
1368         caller_p->caller_dev_dep_req_p = caller_p->caller_dev_dep_req;
1369         caller_p->caller_dev_dep_req_l = MAX_RESPONSE_SIZE;
1370         caller_p->caller_buf_p = we_p->buffer;
1371         INIT_LIST_HEAD(&(caller_p->caller_liste));
1372
1373         rv = convert_request(we_p->buffer, we_p->funccode, function,
1374                              z90crypt.cdx, we_p->devtype,
1375                              &caller_p->caller_dev_dep_req_l,
1376                              caller_p->caller_dev_dep_req_p);
1377         if (rv) {
1378                 if (rv == SEN_NOT_AVAIL)
1379                         PDEBUG("request can't be processed on hdwr avail\n");
1380                 else
1381                         PRINTK("Error from convert_request: %d\n", rv);
1382         }
1383         else
1384                 memcpy(&(caller_p->caller_dev_dep_req_p[4]), we_p->caller_id,8);
1385         return rv;
1386 }
1387
1388 static inline void
1389 unbuild_caller(struct device *device_p, struct caller *caller_p)
1390 {
1391         if (!caller_p)
1392                 return;
1393         if (caller_p->caller_liste.next && caller_p->caller_liste.prev)
1394                 if (!list_empty(&caller_p->caller_liste)) {
1395                         list_del(&caller_p->caller_liste);
1396                         device_p->dev_caller_count--;
1397                         INIT_LIST_HEAD(&caller_p->caller_liste);
1398                 }
1399         memset(caller_p->caller_id, 0, sizeof(caller_p->caller_id));
1400 }
1401
1402 static inline int
1403 get_crypto_request_buffer(struct work_element *we_p)
1404 {
1405         struct ica_rsa_modexpo *mex_p;
1406         struct ica_rsa_modexpo_crt *crt_p;
1407         unsigned char *temp_buffer;
1408         short function;
1409         int rv;
1410
1411         mex_p = (struct ica_rsa_modexpo *) we_p->buffer;
1412         crt_p = (struct ica_rsa_modexpo_crt *) we_p->buffer;
1413
1414         PDEBUG("device type input = %d\n", we_p->devtype);
1415
1416         if (z90crypt.terminating)
1417                 return REC_NO_RESPONSE;
1418         if (memcmp(we_p->caller_id, NULL_psmid, 8) == 0) {
1419                 PRINTK("psmid zeroes\n");
1420                 return SEN_FATAL_ERROR;
1421         }
1422         if (!we_p->buffer) {
1423                 PRINTK("buffer pointer NULL\n");
1424                 return SEN_USER_ERROR;
1425         }
1426         if (!we_p->requestptr) {
1427                 PRINTK("caller pointer NULL\n");
1428                 return SEN_USER_ERROR;
1429         }
1430
1431         if ((we_p->devtype != PCICA) && (we_p->devtype != PCICC) &&
1432             (we_p->devtype != PCIXCC) && (we_p->devtype != ANYDEV)) {
1433                 PRINTK("invalid device type\n");
1434                 return SEN_USER_ERROR;
1435         }
1436
1437         if ((mex_p->inputdatalength < 1) ||
1438             (mex_p->inputdatalength > MAX_MOD_SIZE)) {
1439                 PRINTK("inputdatalength[%d] is not valid\n",
1440                        mex_p->inputdatalength);
1441                 return SEN_USER_ERROR;
1442         }
1443
1444         if (mex_p->outputdatalength < mex_p->inputdatalength) {
1445                 PRINTK("outputdatalength[%d] < inputdatalength[%d]\n",
1446                        mex_p->outputdatalength, mex_p->inputdatalength);
1447                 return SEN_USER_ERROR;
1448         }
1449
1450         if (!mex_p->inputdata || !mex_p->outputdata) {
1451                 PRINTK("inputdata[%p] or outputdata[%p] is NULL\n",
1452                        mex_p->outputdata, mex_p->inputdata);
1453                 return SEN_USER_ERROR;
1454         }
1455
1456         /**
1457          * As long as outputdatalength is big enough, we can set the
1458          * outputdatalength equal to the inputdatalength, since that is the
1459          * number of bytes we will copy in any case
1460          */
1461         mex_p->outputdatalength = mex_p->inputdatalength;
1462
1463         rv = 0;
1464         switch (we_p->funccode) {
1465         case ICARSAMODEXPO:
1466                 if (!mex_p->b_key || !mex_p->n_modulus)
1467                         rv = SEN_USER_ERROR;
1468                 break;
1469         case ICARSACRT:
1470                 if (!IS_EVEN(crt_p->inputdatalength)) {
1471                         PRINTK("inputdatalength[%d] is odd, CRT form\n",
1472                                crt_p->inputdatalength);
1473                         rv = SEN_USER_ERROR;
1474                         break;
1475                 }
1476                 if (!crt_p->bp_key ||
1477                     !crt_p->bq_key ||
1478                     !crt_p->np_prime ||
1479                     !crt_p->nq_prime ||
1480                     !crt_p->u_mult_inv) {
1481                         PRINTK("CRT form, bad data: %p/%p/%p/%p/%p\n",
1482                                crt_p->bp_key, crt_p->bq_key,
1483                                crt_p->np_prime, crt_p->nq_prime,
1484                                crt_p->u_mult_inv);
1485                         rv = SEN_USER_ERROR;
1486                 }
1487                 break;
1488         default:
1489                 PRINTK("bad func = %d\n", we_p->funccode);
1490                 rv = SEN_USER_ERROR;
1491                 break;
1492         }
1493         if (rv != 0)
1494                 return rv;
1495
1496         if (select_device_type(&we_p->devtype) < 0)
1497                 return SEN_NOT_AVAIL;
1498
1499         temp_buffer = (unsigned char *)we_p + sizeof(struct work_element) +
1500                       sizeof(struct caller);
1501         if (copy_from_user(temp_buffer, mex_p->inputdata,
1502                            mex_p->inputdatalength) != 0)
1503                 return SEN_RELEASED;
1504
1505         function = PCI_FUNC_KEY_ENCRYPT;
1506         switch (we_p->devtype) {
1507         /* PCICA does everything with a simple RSA mod-expo operation */
1508         case PCICA:
1509                 function = PCI_FUNC_KEY_ENCRYPT;
1510                 break;
1511         /**
1512          * PCIXCC does all Mod-Expo form with a simple RSA mod-expo
1513          * operation, and all CRT forms with a PKCS-1.2 format decrypt.
1514          */
1515         case PCIXCC:
1516                 /* Anything less than MIN_MOD_SIZE MUST go to a PCICA */
1517                 if (mex_p->inputdatalength < MIN_MOD_SIZE)
1518                         return SEN_NOT_AVAIL;
1519                 if (we_p->funccode == ICARSAMODEXPO)
1520                         function = PCI_FUNC_KEY_ENCRYPT;
1521                 else
1522                         function = PCI_FUNC_KEY_DECRYPT;
1523                 break;
1524         /**
1525          * PCICC does everything as a PKCS-1.2 format request
1526          */
1527         case PCICC:
1528                 /* Anything less than MIN_MOD_SIZE MUST go to a PCICA */
1529                 if (mex_p->inputdatalength < MIN_MOD_SIZE) {
1530                         return SEN_NOT_AVAIL;
1531                 }
1532                 /* Anythings over MAX_PCICC_MOD_SIZE MUST go to a PCICA */
1533                 if (mex_p->inputdatalength > MAX_PCICC_MOD_SIZE) {
1534                         return SEN_NOT_AVAIL;
1535                 }
1536                 /* PCICC cannot handle input that is is PKCS#1.1 padded */
1537                 if (is_PKCS11_padded(temp_buffer, mex_p->inputdatalength)) {
1538                         return SEN_NOT_AVAIL;
1539                 }
1540                 if (we_p->funccode == ICARSAMODEXPO) {
1541                         if (is_PKCS12_padded(temp_buffer,
1542                                              mex_p->inputdatalength))
1543                                 function = PCI_FUNC_KEY_ENCRYPT;
1544                         else
1545                                 function = PCI_FUNC_KEY_DECRYPT;
1546                 } else
1547                         /* all CRT forms are decrypts */
1548                         function = PCI_FUNC_KEY_DECRYPT;
1549                 break;
1550         }
1551         PDEBUG("function: %04x\n", function);
1552         rv = build_caller(we_p, function);
1553         PDEBUG("rv from build_caller = %d\n", rv);
1554         return rv;
1555 }
1556
1557 static inline int
1558 z90crypt_prepare(struct work_element *we_p, unsigned int funccode,
1559                  const char *buffer)
1560 {
1561         int rv;
1562
1563         we_p->devindex = -1;
1564         if (funccode == ICARSAMODEXPO)
1565                 we_p->buff_size = sizeof(struct ica_rsa_modexpo);
1566         else
1567                 we_p->buff_size = sizeof(struct ica_rsa_modexpo_crt);
1568
1569         if (copy_from_user(we_p->buffer, buffer, we_p->buff_size))
1570                 return -EFAULT;
1571
1572         we_p->audit[0] |= FP_COPYFROM;
1573         SET_RDWRMASK(we_p->status[0], STAT_WRITTEN);
1574         we_p->funccode = funccode;
1575         we_p->devtype = -1;
1576         we_p->audit[0] |= FP_BUFFREQ;
1577         rv = get_crypto_request_buffer(we_p);
1578         switch (rv) {
1579         case 0:
1580                 we_p->audit[0] |= FP_BUFFGOT;
1581                 break;
1582         case SEN_USER_ERROR:
1583                 rv = -EINVAL;
1584                 break;
1585         case SEN_QUEUE_FULL:
1586                 rv = 0;
1587                 break;
1588         case SEN_RELEASED:
1589                 rv = -EFAULT;
1590                 break;
1591         case REC_NO_RESPONSE:
1592                 rv = -ENODEV;
1593                 break;
1594         case SEN_NOT_AVAIL:
1595                 rv = -EGETBUFF;
1596                 break;
1597         default:
1598                 PRINTK("rv = %d\n", rv);
1599                 rv = -EGETBUFF;
1600                 break;
1601         }
1602         if (CHK_RDWRMASK(we_p->status[0]) == STAT_WRITTEN)
1603                 SET_RDWRMASK(we_p->status[0], STAT_DEFAULT);
1604         return rv;
1605 }
1606
1607 static inline void
1608 purge_work_element(struct work_element *we_p)
1609 {
1610         struct list_head *lptr;
1611
1612         spin_lock_irq(&queuespinlock);
1613         list_for_each(lptr, &request_list) {
1614                 if (lptr == &we_p->liste) {
1615                         list_del(lptr);
1616                         requestq_count--;
1617                         break;
1618                 }
1619         }
1620         list_for_each(lptr, &pending_list) {
1621                 if (lptr == &we_p->liste) {
1622                         list_del(lptr);
1623                         pendingq_count--;
1624                         break;
1625                 }
1626         }
1627         spin_unlock_irq(&queuespinlock);
1628 }
1629
1630 /**
1631  * Build the request and send it.
1632  */
1633 static inline int
1634 z90crypt_rsa(struct priv_data *private_data_p, pid_t pid,
1635              unsigned int cmd, unsigned long arg)
1636 {
1637         struct work_element *we_p;
1638         int rv;
1639
1640         if ((rv = allocate_work_element(&we_p, private_data_p, pid))) {
1641                 PDEBUG("PID %d: allocate_work_element returned ENOMEM\n", pid);
1642                 return rv;
1643         }
1644         if ((rv = z90crypt_prepare(we_p, cmd, (const char *)arg)))
1645                 PDEBUG("PID %d: rv = %d from z90crypt_prepare\n", pid, rv);
1646         if (!rv)
1647                 if ((rv = z90crypt_send(we_p, (const char *)arg)))
1648                         PDEBUG("PID %d: rv %d from z90crypt_send.\n", pid, rv);
1649         if (!rv) {
1650                 we_p->audit[0] |= FP_ASLEEP;
1651                 wait_event(we_p->waitq, atomic_read(&we_p->alarmrung));
1652                 we_p->audit[0] |= FP_AWAKE;
1653                 rv = we_p->retcode;
1654         }
1655         if (!rv)
1656                 rv = z90crypt_process_results(we_p, (char *)arg);
1657
1658         if ((we_p->status[0] & STAT_FAILED)) {
1659                 switch (rv) {
1660                 /**
1661                  * EINVAL *after* receive is almost always padding
1662                  * error issued by a PCICC or PCIXCC. We convert this
1663                  * return value to -EGETBUFF which should trigger a
1664                  * fallback to software.
1665                  */
1666                 case -EINVAL:
1667                         if ((we_p->devtype == PCICC) ||
1668                             (we_p->devtype == PCIXCC))
1669                                 rv = -EGETBUFF;
1670                         break;
1671                 case -ETIMEOUT:
1672                         if (z90crypt.mask.st_count > 0)
1673                                 rv = -ERESTARTSYS; // retry with another
1674                         else
1675                                 rv = -ENODEV; // no cards left
1676                 /* fall through to clean up request queue */
1677                 case -ERESTARTSYS:
1678                 case -ERELEASED:
1679                         switch (CHK_RDWRMASK(we_p->status[0])) {
1680                         case STAT_WRITTEN:
1681                                 purge_work_element(we_p);
1682                                 break;
1683                         case STAT_READPEND:
1684                         case STAT_NOWORK:
1685                         default:
1686                                 break;
1687                         }
1688                         break;
1689                 default:
1690                         we_p->status[0] ^= STAT_FAILED;
1691                         break;
1692                 }
1693         }
1694         free_page((long)we_p);
1695         return rv;
1696 }
1697
1698 /**
1699  * This function is a little long, but it's really just one large switch
1700  * statement.
1701  */
1702 static int
1703 z90crypt_ioctl(struct inode *inode, struct file *filp,
1704                unsigned int cmd, unsigned long arg)
1705 {
1706         struct priv_data *private_data_p = filp->private_data;
1707         unsigned char *status;
1708         unsigned char *qdepth;
1709         unsigned int *reqcnt;
1710         struct ica_z90_status *pstat;
1711         int ret, i, loopLim, tempstat;
1712         static int deprecated_msg_count = 0;
1713
1714         PDEBUG("filp %p (PID %d), cmd 0x%08X\n", filp, PID(), cmd);
1715         PDEBUG("cmd 0x%08X: dir %s, size 0x%04X, type 0x%02X, nr 0x%02X\n",
1716                 cmd,
1717                 !_IOC_DIR(cmd) ? "NO"
1718                 : ((_IOC_DIR(cmd) == (_IOC_READ|_IOC_WRITE)) ? "RW"
1719                 : ((_IOC_DIR(cmd) == _IOC_READ) ? "RD"
1720                 : "WR")),
1721                 _IOC_SIZE(cmd), _IOC_TYPE(cmd), _IOC_NR(cmd));
1722
1723         if (_IOC_TYPE(cmd) != Z90_IOCTL_MAGIC) {
1724                 PRINTK("cmd 0x%08X contains bad magic\n", cmd);
1725                 return -ENOTTY;
1726         }
1727
1728         ret = 0;
1729         switch (cmd) {
1730         case ICARSAMODEXPO:
1731         case ICARSACRT:
1732                 if (quiesce_z90crypt) {
1733                         ret = -EQUIESCE;
1734                         break;
1735                 }
1736                 ret = -ENODEV; // Default if no devices
1737                 loopLim = z90crypt.hdware_info->hdware_mask.st_count -
1738                         (z90crypt.hdware_info->hdware_mask.disabled_count +
1739                          z90crypt.hdware_info->hdware_mask.user_disabled_count);
1740                 for (i = 0; i < loopLim; i++) {
1741                         ret = z90crypt_rsa(private_data_p, PID(), cmd, arg);
1742                         if (ret != -ERESTARTSYS)
1743                                 break;
1744                 }
1745                 if (ret == -ERESTARTSYS)
1746                         ret = -ENODEV;
1747                 break;
1748
1749         case Z90STAT_TOTALCOUNT:
1750                 tempstat = get_status_totalcount();
1751                 if (copy_to_user((int *)arg, &tempstat,sizeof(int)) != 0)
1752                         ret = -EFAULT;
1753                 break;
1754
1755         case Z90STAT_PCICACOUNT:
1756                 tempstat = get_status_PCICAcount();
1757                 if (copy_to_user((int *)arg, &tempstat, sizeof(int)) != 0)
1758                         ret = -EFAULT;
1759                 break;
1760
1761         case Z90STAT_PCICCCOUNT:
1762                 tempstat = get_status_PCICCcount();
1763                 if (copy_to_user((int *)arg, &tempstat, sizeof(int)) != 0)
1764                         ret = -EFAULT;
1765                 break;
1766
1767         case Z90STAT_PCIXCCCOUNT:
1768                 tempstat = get_status_PCIXCCcount();
1769                 if (copy_to_user((int *)arg, &tempstat, sizeof(int)) != 0)
1770                         ret = -EFAULT;
1771                 break;
1772
1773         case Z90STAT_REQUESTQ_COUNT:
1774                 tempstat = get_status_requestq_count();
1775                 if (copy_to_user((int *)arg, &tempstat, sizeof(int)) != 0)
1776                         ret = -EFAULT;
1777                 break;
1778
1779         case Z90STAT_PENDINGQ_COUNT:
1780                 tempstat = get_status_pendingq_count();
1781                 if (copy_to_user((int *)arg, &tempstat, sizeof(int)) != 0)
1782                         ret = -EFAULT;
1783                 break;
1784
1785         case Z90STAT_TOTALOPEN_COUNT:
1786                 tempstat = get_status_totalopen_count();
1787                 if (copy_to_user((int *)arg, &tempstat, sizeof(int)) != 0)
1788                         ret = -EFAULT;
1789                 break;
1790
1791         case Z90STAT_DOMAIN_INDEX:
1792                 tempstat = get_status_domain_index();
1793                 if (copy_to_user((int *)arg, &tempstat, sizeof(int)) != 0)
1794                         ret = -EFAULT;
1795                 break;
1796
1797         case Z90STAT_STATUS_MASK:
1798                 status = kmalloc(Z90CRYPT_NUM_APS, GFP_KERNEL);
1799                 if (!status) {
1800                         PRINTK("kmalloc for status failed!\n");
1801                         ret = -ENOMEM;
1802                         break;
1803                 }
1804                 get_status_status_mask(status);
1805                 if (copy_to_user((char *) arg, status, Z90CRYPT_NUM_APS) != 0)
1806                         ret = -EFAULT;
1807                 kfree(status);
1808                 break;
1809
1810         case Z90STAT_QDEPTH_MASK:
1811                 qdepth = kmalloc(Z90CRYPT_NUM_APS, GFP_KERNEL);
1812                 if (!qdepth) {
1813                         PRINTK("kmalloc for qdepth failed!\n");
1814                         ret = -ENOMEM;
1815                         break;
1816                 }
1817                 get_status_qdepth_mask(qdepth);
1818                 if (copy_to_user((char *) arg, qdepth, Z90CRYPT_NUM_APS) != 0)
1819                         ret = -EFAULT;
1820                 kfree(qdepth);
1821                 break;
1822
1823         case Z90STAT_PERDEV_REQCNT:
1824                 reqcnt = kmalloc(sizeof(int) * Z90CRYPT_NUM_APS, GFP_KERNEL);
1825                 if (!reqcnt) {
1826                         PRINTK("kmalloc for reqcnt failed!\n");
1827                         ret = -ENOMEM;
1828                         break;
1829                 }
1830                 get_status_perdevice_reqcnt(reqcnt);
1831                 if (copy_to_user((char *) arg, reqcnt,
1832                                  Z90CRYPT_NUM_APS * sizeof(int)) != 0)
1833                         ret = -EFAULT;
1834                 kfree(reqcnt);
1835                 break;
1836
1837                 /* THIS IS DEPRECATED.  USE THE NEW STATUS CALLS */
1838         case ICAZ90STATUS:
1839                 if (deprecated_msg_count < 100) {
1840                         PRINTK("deprecated call to ioctl (ICAZ90STATUS)!\n");
1841                         deprecated_msg_count++;
1842                         if (deprecated_msg_count == 100)
1843                                 PRINTK("No longer issuing messages related to "
1844                                        "deprecated call to ICAZ90STATUS.\n");
1845                 }
1846
1847                 pstat = kmalloc(sizeof(struct ica_z90_status), GFP_KERNEL);
1848                 if (!pstat) {
1849                         PRINTK("kmalloc for pstat failed!\n");
1850                         ret = -ENOMEM;
1851                         break;
1852                 }
1853
1854                 pstat->totalcount        = get_status_totalcount();
1855                 pstat->leedslitecount    = get_status_PCICAcount();
1856                 pstat->leeds2count       = get_status_PCICCcount();
1857                 pstat->requestqWaitCount = get_status_requestq_count();
1858                 pstat->pendingqWaitCount = get_status_pendingq_count();
1859                 pstat->totalOpenCount    = get_status_totalopen_count();
1860                 pstat->cryptoDomain      = get_status_domain_index();
1861                 get_status_status_mask(pstat->status);
1862                 get_status_qdepth_mask(pstat->qdepth);
1863
1864                 if (copy_to_user((struct ica_z90_status *) arg, pstat,
1865                                  sizeof(struct ica_z90_status)) != 0)
1866                         ret = -EFAULT;
1867                 kfree(pstat);
1868                 break;
1869
1870         case Z90QUIESCE:
1871                 if (current->euid != 0) {
1872                         PRINTK("QUIESCE fails: euid %d\n",
1873                                current->euid);
1874                         ret = -EACCES;
1875                 } else {
1876                         PRINTK("QUIESCE device from PID %d\n", PID());
1877                         quiesce_z90crypt = 1;
1878                 }
1879                 break;
1880
1881         default:
1882                 /* user passed an invalid IOCTL number */
1883                 PDEBUG("cmd 0x%08X contains invalid ioctl code\n", cmd);
1884                 ret = -ENOTTY;
1885                 break;
1886         }
1887
1888         return ret;
1889 }
1890
1891 static inline int
1892 sprintcl(unsigned char *outaddr, unsigned char *addr, unsigned int len)
1893 {
1894         int hl, i;
1895
1896         hl = 0;
1897         for (i = 0; i < len; i++)
1898                 hl += sprintf(outaddr+hl, "%01x", (unsigned int) addr[i]);
1899         hl += sprintf(outaddr+hl, " ");
1900
1901         return hl;
1902 }
1903
1904 static inline int
1905 sprintrw(unsigned char *outaddr, unsigned char *addr, unsigned int len)
1906 {
1907         int hl, inl, c, cx;
1908
1909         hl = sprintf(outaddr, "    ");
1910         inl = 0;
1911         for (c = 0; c < (len / 16); c++) {
1912                 hl += sprintcl(outaddr+hl, addr+inl, 16);
1913                 inl += 16;
1914         }
1915
1916         cx = len%16;
1917         if (cx) {
1918                 hl += sprintcl(outaddr+hl, addr+inl, cx);
1919                 inl += cx;
1920         }
1921
1922         hl += sprintf(outaddr+hl, "\n");
1923
1924         return hl;
1925 }
1926
1927 static inline int
1928 sprinthx(unsigned char *title, unsigned char *outaddr,
1929          unsigned char *addr, unsigned int len)
1930 {
1931         int hl, inl, r, rx;
1932
1933         hl = sprintf(outaddr, "\n%s\n", title);
1934         inl = 0;
1935         for (r = 0; r < (len / 64); r++) {
1936                 hl += sprintrw(outaddr+hl, addr+inl, 64);
1937                 inl += 64;
1938         }
1939         rx = len % 64;
1940         if (rx) {
1941                 hl += sprintrw(outaddr+hl, addr+inl, rx);
1942                 inl += rx;
1943         }
1944
1945         hl += sprintf(outaddr+hl, "\n");
1946
1947         return hl;
1948 }
1949
1950 static inline int
1951 sprinthx4(unsigned char *title, unsigned char *outaddr,
1952           unsigned int *array, unsigned int len)
1953 {
1954         int hl, r;
1955
1956         hl = sprintf(outaddr, "\n%s\n", title);
1957
1958         for (r = 0; r < len; r++) {
1959                 if ((r % 8) == 0)
1960                         hl += sprintf(outaddr+hl, "    ");
1961                 hl += sprintf(outaddr+hl, "%08X ", array[r]);
1962                 if ((r % 8) == 7)
1963                         hl += sprintf(outaddr+hl, "\n");
1964         }
1965
1966         hl += sprintf(outaddr+hl, "\n");
1967
1968         return hl;
1969 }
1970
1971 static int
1972 z90crypt_status(char *resp_buff, char **start, off_t offset,
1973                 int count, int *eof, void *data)
1974 {
1975         unsigned char *workarea;
1976         int len;
1977
1978         /* resp_buff is a page. Use the right half for a work area */
1979         workarea = resp_buff+2000;
1980         len = 0;
1981         len += sprintf(resp_buff+len, "\nz90crypt version: %d.%d.%d\n",
1982                 z90crypt_VERSION, z90crypt_RELEASE, z90crypt_VARIANT);
1983         len += sprintf(resp_buff+len, "Cryptographic domain: %d\n",
1984                 get_status_domain_index());
1985         len += sprintf(resp_buff+len, "Total device count: %d\n",
1986                 get_status_totalcount());
1987         len += sprintf(resp_buff+len, "PCICA count: %d\n",
1988                 get_status_PCICAcount());
1989         len += sprintf(resp_buff+len, "PCICC count: %d\n",
1990                 get_status_PCICCcount());
1991         len += sprintf(resp_buff+len, "PCIXCC count: %d\n",
1992                 get_status_PCIXCCcount());
1993         len += sprintf(resp_buff+len, "requestq count: %d\n",
1994                 get_status_requestq_count());
1995         len += sprintf(resp_buff+len, "pendingq count: %d\n",
1996                 get_status_pendingq_count());
1997         len += sprintf(resp_buff+len, "Total open handles: %d\n\n",
1998                 get_status_totalopen_count());
1999         len += sprinthx(
2000                 "Online devices: 1 means PCICA, 2 means PCICC, 3 means PCIXCC",
2001                 resp_buff+len,
2002                 get_status_status_mask(workarea),
2003                 Z90CRYPT_NUM_APS);
2004         len += sprinthx("Waiting work element counts",
2005                 resp_buff+len,
2006                 get_status_qdepth_mask(workarea),
2007                 Z90CRYPT_NUM_APS);
2008         len += sprinthx4(
2009                 "Per-device successfully completed request counts",
2010                 resp_buff+len,
2011                 get_status_perdevice_reqcnt((unsigned int *)workarea),
2012                 Z90CRYPT_NUM_APS);
2013         *eof = 1;
2014         memset(workarea, 0, Z90CRYPT_NUM_APS * sizeof(unsigned int));
2015         return len;
2016 }
2017
2018 static inline void
2019 disable_card(int card_index)
2020 {
2021         struct device *devp;
2022
2023         devp = LONG2DEVPTR(card_index);
2024         if (!devp || devp->user_disabled)
2025                 return;
2026         devp->user_disabled = 1;
2027         z90crypt.hdware_info->hdware_mask.user_disabled_count++;
2028         if (devp->dev_type == -1)
2029                 return;
2030         z90crypt.hdware_info->type_mask[devp->dev_type].user_disabled_count++;
2031 }
2032
2033 static inline void
2034 enable_card(int card_index)
2035 {
2036         struct device *devp;
2037
2038         devp = LONG2DEVPTR(card_index);
2039         if (!devp || !devp->user_disabled)
2040                 return;
2041         devp->user_disabled = 0;
2042         z90crypt.hdware_info->hdware_mask.user_disabled_count--;
2043         if (devp->dev_type == -1)
2044                 return;
2045         z90crypt.hdware_info->type_mask[devp->dev_type].user_disabled_count--;
2046 }
2047
2048 static inline int
2049 scan_char(unsigned char *bf, unsigned int len,
2050           unsigned int *offs, unsigned int *p_eof, unsigned char c)
2051 {
2052         unsigned int i, found;
2053
2054         found = 0;
2055         for (i = 0; i < len; i++) {
2056                 if (bf[i] == c) {
2057                         found = 1;
2058                         break;
2059                 }
2060                 if (bf[i] == '\0') {
2061                         *p_eof = 1;
2062                         break;
2063                 }
2064                 if (bf[i] == '\n') {
2065                         break;
2066                 }
2067         }
2068         *offs = i+1;
2069         return found;
2070 }
2071
2072 static inline int
2073 scan_string(unsigned char *bf, unsigned int len,
2074             unsigned int *offs, unsigned int *p_eof, unsigned char *s)
2075 {
2076         unsigned int temp_len, temp_offs, found, eof;
2077
2078         temp_len = temp_offs = found = eof = 0;
2079         while (!eof && !found) {
2080                 found = scan_char(bf+temp_len, len-temp_len,
2081                                   &temp_offs, &eof, *s);
2082
2083                 temp_len += temp_offs;
2084                 if (eof) {
2085                         found = 0;
2086                         break;
2087                 }
2088
2089                 if (found) {
2090                         if (len >= temp_offs+strlen(s)) {
2091                                 found = !strncmp(bf+temp_len-1, s, strlen(s));
2092                                 if (found) {
2093                                         *offs = temp_len+strlen(s)-1;
2094                                         break;
2095                                 }
2096                         } else {
2097                                 found = 0;
2098                                 *p_eof = 1;
2099                                 break;
2100                         }
2101                 }
2102         }
2103         return found;
2104 }
2105
2106 static int
2107 z90crypt_status_write(struct file *file, const char *buffer,
2108                       unsigned long count, void *data)
2109 {
2110         int i, j, len, offs, found, eof;
2111         unsigned char *lbuf;
2112         unsigned int local_count;
2113
2114 #define LBUFSIZE 600
2115         lbuf = kmalloc(LBUFSIZE, GFP_KERNEL);
2116         if (!lbuf) {
2117                 PRINTK("kmalloc failed!\n");
2118                 return 0;
2119         }
2120
2121         if (count <= 0)
2122                 return 0;
2123
2124         local_count = UMIN((unsigned int)count, LBUFSIZE-1);
2125
2126         if (copy_from_user(lbuf, buffer, local_count) != 0) {
2127                 kfree(lbuf);
2128                 return -EFAULT;
2129         }
2130
2131         lbuf[local_count-1] = '\0';
2132
2133         len = 0;
2134         eof = 0;
2135         found = 0;
2136         while (!eof) {
2137                 found = scan_string(lbuf+len, local_count-len, &offs, &eof,
2138                                     "Online devices");
2139                 len += offs;
2140                 if (found == 1)
2141                         break;
2142         }
2143
2144         if (eof) {
2145                 kfree(lbuf);
2146                 return count;
2147         }
2148
2149         if (found)
2150                 found = scan_char(lbuf+len, local_count-len, &offs, &eof, '\n');
2151
2152         if (!found || eof) {
2153                 kfree(lbuf);
2154                 return count;
2155         }
2156
2157         len += offs;
2158         j = 0;
2159         for (i = 0; i < 80; i++) {
2160                 switch (*(lbuf+len+i)) {
2161                 case '\t':
2162                 case ' ':
2163                         break;
2164                 case '\n':
2165                 default:
2166                         eof = 1;
2167                         break;
2168                 case '0':
2169                 case '1':
2170                 case '2':
2171                 case '3':
2172                         j++;
2173                         break;
2174                 case 'd':
2175                 case 'D':
2176                         disable_card(j);
2177                         j++;
2178                         break;
2179                 case 'e':
2180                 case 'E':
2181                         enable_card(j);
2182                         j++;
2183                         break;
2184                 }
2185                 if (eof)
2186                         break;
2187         }
2188
2189         kfree(lbuf);
2190         return count;
2191 }
2192
2193 /**
2194  * Functions that run under a timer, with no process id
2195  *
2196  * The task functions:
2197  *     z90crypt_reader_task
2198  *       helper_send_work
2199  *       helper_handle_work_element
2200  *       helper_receive_rc
2201  *     z90crypt_config_task
2202  *     z90crypt_cleanup_task
2203  *
2204  * Helper functions:
2205  *     z90crypt_schedule_reader_timer
2206  *     z90crypt_schedule_reader_task
2207  *     z90crypt_schedule_config_task
2208  *     z90crypt_schedule_cleanup_task
2209  */
2210 static inline int
2211 receive_from_crypto_device(int index, unsigned char *psmid, int *buff_len_p,
2212                            unsigned char *buff, unsigned char **dest_p_p)
2213 {
2214         int dv, rv;
2215         struct device *dev_ptr;
2216         struct caller *caller_p;
2217         struct ica_rsa_modexpo *icaMsg_p;
2218         struct list_head *ptr, *tptr;
2219
2220         memcpy(psmid, NULL_psmid, sizeof(NULL_psmid));
2221
2222         if (z90crypt.terminating)
2223                 return REC_FATAL_ERROR;
2224
2225         caller_p = 0;
2226         dev_ptr = z90crypt.device_p[index];
2227         rv = 0;
2228         do {
2229                 PDEBUG("Dequeue called for device %d\n", index);
2230                 if (!dev_ptr || dev_ptr->disabled) {
2231                         rv = REC_NO_RESPONSE;
2232                         break;
2233                 }
2234                 if (dev_ptr->dev_self_x != index) {
2235                         PRINTK("Corrupt dev ptr in receive_from_AP\n");
2236                         z90crypt.terminating = 1;
2237                         rv = REC_FATAL_ERROR;
2238                         break;
2239                 }
2240                 if (!dev_ptr->dev_resp_l || !dev_ptr->dev_resp_p) {
2241                         dv = DEV_REC_EXCEPTION;
2242                         PRINTK("dev_resp_l = %d, dev_resp_p = %p\n",
2243                                dev_ptr->dev_resp_l, dev_ptr->dev_resp_p);
2244                 } else {
2245                         dv = receive_from_AP(index, z90crypt.cdx,
2246                                              dev_ptr->dev_resp_l,
2247                                              dev_ptr->dev_resp_p, psmid);
2248                 }
2249                 switch (dv) {
2250                 case DEV_REC_EXCEPTION:
2251                         rv = REC_FATAL_ERROR;
2252                         z90crypt.terminating = 1;
2253                         PRINTKC("Exception in receive from device %d\n",
2254                                 index);
2255                         break;
2256                 case DEV_ONLINE:
2257                         rv = 0;
2258                         break;
2259                 case DEV_EMPTY:
2260                         rv = REC_EMPTY;
2261                         break;
2262                 case DEV_NO_WORK:
2263                         rv = REC_NO_WORK;
2264                         break;
2265                 case DEV_BAD_MESSAGE:
2266                 case DEV_GONE:
2267                 case REC_HARDWAR_ERR:
2268                 default:
2269                         rv = REC_NO_RESPONSE;
2270                         break;
2271                 }
2272                 if (rv)
2273                         break;
2274                 if (dev_ptr->dev_caller_count <= 0) {
2275                         rv = REC_USER_GONE;
2276                         break;
2277                 }
2278
2279                 list_for_each_safe(ptr, tptr, &dev_ptr->dev_caller_list) {
2280                         caller_p = list_entry(ptr, struct caller, caller_liste);
2281                         if (!memcmp(caller_p->caller_id, psmid,
2282                                     sizeof(caller_p->caller_id))) {
2283                                 if (!list_empty(&caller_p->caller_liste)) {
2284                                         list_del(ptr);
2285                                         dev_ptr->dev_caller_count--;
2286                                         INIT_LIST_HEAD(&caller_p->caller_liste);
2287                                         break;
2288                                 }
2289                         }
2290                         caller_p = 0;
2291                 }
2292                 if (!caller_p) {
2293                         rv = REC_USER_GONE;
2294                         break;
2295                 }
2296
2297                 PDEBUG("caller_p after successful receive: %p\n", caller_p);
2298                 rv = convert_response(dev_ptr->dev_resp_p,
2299                                       caller_p->caller_buf_p, buff_len_p, buff);
2300                 switch (rv) {
2301                 case REC_OPERAND_INV:
2302                         PDEBUG("dev %d: user error %d\n", index, rv);
2303                         break;
2304                 case WRONG_DEVICE_TYPE:
2305                 case REC_HARDWAR_ERR:
2306                 case REC_BAD_MESSAGE:
2307                         PRINTK("dev %d: hardware error %d\n",
2308                                index, rv);
2309                         rv = REC_NO_RESPONSE;
2310                         break;
2311                 case REC_RELEASED:
2312                         PDEBUG("dev %d: REC_RELEASED = %d\n",
2313                                index, rv);
2314                         break;
2315                 default:
2316                         PDEBUG("dev %d: rv = %d\n", index, rv);
2317                         break;
2318                 }
2319         } while (0);
2320
2321         switch (rv) {
2322         case 0:
2323                 PDEBUG("Successful receive from device %d\n", index);
2324                 icaMsg_p = (struct ica_rsa_modexpo *)caller_p->caller_buf_p;
2325                 *dest_p_p = icaMsg_p->outputdata;
2326                 if (*buff_len_p == 0)
2327                         PRINTK("Zero *buff_len_p\n");
2328                 break;
2329         case REC_NO_RESPONSE:
2330                 remove_device(dev_ptr);
2331                 break;
2332         }
2333
2334         if (caller_p)
2335                 unbuild_caller(dev_ptr, caller_p);
2336
2337         return rv;
2338 }
2339
2340 static inline void
2341 helper_send_work(int index)
2342 {
2343         struct work_element *rq_p;
2344         int rv;
2345
2346         if (list_empty(&request_list))
2347                 return;
2348         requestq_count--;
2349         rq_p = list_entry(request_list.next, struct work_element, liste);
2350         list_del(&rq_p->liste);
2351         rq_p->audit[1] |= FP_REMREQUEST;
2352         if (rq_p->devtype == SHRT2DEVPTR(index)->dev_type) {
2353                 rq_p->devindex = SHRT2LONG(index);
2354                 rv = send_to_crypto_device(rq_p);
2355                 if (rv == 0) {
2356                         rq_p->requestsent = jiffies;
2357                         rq_p->audit[0] |= FP_SENT;
2358                         list_add_tail(&rq_p->liste, &pending_list);
2359                         ++pendingq_count;
2360                         rq_p->audit[0] |= FP_PENDING;
2361                 } else {
2362                         switch (rv) {
2363                         case REC_OPERAND_INV:
2364                         case REC_OPERAND_SIZE:
2365                         case REC_EVEN_MOD:
2366                         case REC_INVALID_PAD:
2367                                 rq_p->retcode = -EINVAL;
2368                                 break;
2369                         case SEN_NOT_AVAIL:
2370                         case SEN_RETRY:
2371                         case REC_NO_RESPONSE:
2372                         default:
2373                                 if (z90crypt.mask.st_count > 1)
2374                                         rq_p->retcode =
2375                                                 -ERESTARTSYS;
2376                                 else
2377                                         rq_p->retcode = -ENODEV;
2378                                 break;
2379                         }
2380                         rq_p->status[0] |= STAT_FAILED;
2381                         rq_p->audit[1] |= FP_AWAKENING;
2382                         atomic_set(&rq_p->alarmrung, 1);
2383                         wake_up(&rq_p->waitq);
2384                 }
2385         } else {
2386                 if (z90crypt.mask.st_count > 1)
2387                         rq_p->retcode = -ERESTARTSYS;
2388                 else
2389                         rq_p->retcode = -ENODEV;
2390                 rq_p->status[0] |= STAT_FAILED;
2391                 rq_p->audit[1] |= FP_AWAKENING;
2392                 atomic_set(&rq_p->alarmrung, 1);
2393                 wake_up(&rq_p->waitq);
2394         }
2395 }
2396
2397 static inline void
2398 helper_handle_work_element(int index, unsigned char psmid[8], int rc,
2399                            int buff_len, unsigned char *buff,
2400                            unsigned char *resp_addr)
2401 {
2402         struct work_element *pq_p;
2403         struct list_head *lptr, *tptr;
2404
2405         pq_p = 0;
2406         list_for_each_safe(lptr, tptr, &pending_list) {
2407                 pq_p = list_entry(lptr, struct work_element, liste);
2408                 if (!memcmp(pq_p->caller_id, psmid, sizeof(pq_p->caller_id))) {
2409                         list_del(lptr);
2410                         pendingq_count--;
2411                         pq_p->audit[1] |= FP_NOTPENDING;
2412                         break;
2413                 }
2414                 pq_p = 0;
2415         }
2416
2417         if (!pq_p) {
2418                 PRINTK("device %d has work but no caller exists on pending Q\n",
2419                        SHRT2LONG(index));
2420                 return;
2421         }
2422
2423         switch (rc) {
2424                 case 0:
2425                         pq_p->resp_buff_size = buff_len;
2426                         pq_p->audit[1] |= FP_RESPSIZESET;
2427                         if (buff_len) {
2428                                 pq_p->resp_addr = resp_addr;
2429                                 pq_p->audit[1] |= FP_RESPADDRCOPIED;
2430                                 memcpy(pq_p->resp_buff, buff, buff_len);
2431                                 pq_p->audit[1] |= FP_RESPBUFFCOPIED;
2432                         }
2433                         break;
2434                 case REC_OPERAND_INV:
2435                 case REC_OPERAND_SIZE:
2436                 case REC_EVEN_MOD:
2437                 case REC_INVALID_PAD:
2438                         PDEBUG("-EINVAL after application error %d\n", rc);
2439                         pq_p->retcode = -EINVAL;
2440                         pq_p->status[0] |= STAT_FAILED;
2441                         break;
2442                 case REC_NO_RESPONSE:
2443                 default:
2444                         if (z90crypt.mask.st_count > 1)
2445                                 pq_p->retcode = -ERESTARTSYS;
2446                         else
2447                                 pq_p->retcode = -ENODEV;
2448                         pq_p->status[0] |= STAT_FAILED;
2449                         break;
2450         }
2451         if ((pq_p->status[0] != STAT_FAILED) || (pq_p->retcode != -ERELEASED)) {
2452                 pq_p->audit[1] |= FP_AWAKENING;
2453                 atomic_set(&pq_p->alarmrung, 1);
2454                 wake_up(&pq_p->waitq);
2455         }
2456 }
2457
2458 /**
2459  * return TRUE if the work element should be removed from the queue
2460  */
2461 static inline int
2462 helper_receive_rc(int index, int *rc_p, int *workavail_p)
2463 {
2464         switch (*rc_p) {
2465         case 0:
2466         case REC_OPERAND_INV:
2467         case REC_OPERAND_SIZE:
2468         case REC_EVEN_MOD:
2469         case REC_INVALID_PAD:
2470                 return 1;
2471
2472         case REC_BUSY:
2473         case REC_NO_WORK:
2474         case REC_EMPTY:
2475         case REC_RETRY_DEV:
2476         case REC_FATAL_ERROR:
2477                 break;
2478
2479         case REC_NO_RESPONSE:
2480                 *workavail_p = 0;
2481                 break;
2482
2483         default:
2484                 PRINTK("rc %d, device %d\n", *rc_p, SHRT2LONG(index));
2485                 *rc_p = REC_NO_RESPONSE;
2486                 *workavail_p = 0;
2487                 break;
2488         }
2489         return 0;
2490 }
2491
2492 static inline void
2493 z90crypt_schedule_reader_timer(void)
2494 {
2495         if (timer_pending(&reader_timer))
2496                 return;
2497         if (mod_timer(&reader_timer, jiffies+(READERTIME*HZ/1000)) != 0)
2498                 PRINTK("Timer pending while modifying reader timer\n");
2499 }
2500
2501 static void
2502 z90crypt_reader_task(unsigned long ptr)
2503 {
2504         int workavail, remaining, index, rc, buff_len;
2505         unsigned char   psmid[8], *resp_addr;
2506         static unsigned char buff[1024];
2507
2508         PDEBUG("jiffies %ld\n", jiffies);
2509
2510         /**
2511          * we use workavail = 2 to ensure 2 passes with nothing dequeued before
2512          * exiting the loop. If remaining == 0 after the loop, there is no work
2513          * remaining on the queues.
2514          */
2515         resp_addr = 0;
2516         workavail = 2;
2517         remaining = 0;
2518         buff_len = 0;
2519         while (workavail) {
2520                 workavail--;
2521                 rc = 0;
2522                 spin_lock_irq(&queuespinlock);
2523                 memset(buff, 0x00, sizeof(buff));
2524
2525                 /* Dequeue once from each device in round robin. */
2526                 for (index = 0; index < z90crypt.mask.st_count; index++) {
2527                         PDEBUG("About to receive.\n");
2528                         rc = receive_from_crypto_device(SHRT2LONG(index),
2529                                                         psmid,
2530                                                         &buff_len,
2531                                                         buff,
2532                                                         &resp_addr);
2533                         PDEBUG("Dequeued: rc = %d.\n", rc);
2534
2535                         if (helper_receive_rc(index, &rc, &workavail)) {
2536                                 if (rc != REC_NO_RESPONSE) {
2537                                         helper_send_work(index);
2538                                         workavail = 2;
2539                                 }
2540
2541                                 helper_handle_work_element(index, psmid, rc,
2542                                                            buff_len, buff,
2543                                                            resp_addr);
2544                         }
2545
2546                         if (rc == REC_FATAL_ERROR)
2547                                 remaining = 0;
2548                         else if (rc != REC_NO_RESPONSE)
2549                                 remaining +=
2550                                         SHRT2DEVPTR(index)->dev_caller_count;
2551                 }
2552                 spin_unlock_irq(&queuespinlock);
2553         }
2554
2555         if (remaining) {
2556                 spin_lock_irq(&queuespinlock);
2557                 z90crypt_schedule_reader_timer();
2558                 spin_unlock_irq(&queuespinlock);
2559         }
2560 }
2561
2562 static inline void
2563 z90crypt_schedule_config_task(unsigned int expiration)
2564 {
2565         if (timer_pending(&config_timer))
2566                 return;
2567         if (mod_timer(&config_timer, jiffies+(expiration*HZ)) != 0)
2568                 PRINTK("Timer pending while modifying config timer\n");
2569 }
2570
2571 static void
2572 z90crypt_config_task(unsigned long ptr)
2573 {
2574         int rc;
2575
2576         PDEBUG("jiffies %ld\n", jiffies);
2577
2578         if ((rc = refresh_z90crypt(&z90crypt.cdx)))
2579                 PRINTK("Error %d detected in refresh_z90crypt.\n", rc);
2580         /* If return was fatal, don't bother reconfiguring */
2581         if ((rc != TSQ_FATAL_ERROR) && (rc != RSQ_FATAL_ERROR))
2582                 z90crypt_schedule_config_task(CONFIGTIME);
2583 }
2584
2585 static inline void
2586 z90crypt_schedule_cleanup_task(void)
2587 {
2588         if (timer_pending(&cleanup_timer))
2589                 return;
2590         if (mod_timer(&cleanup_timer, jiffies+(CLEANUPTIME*HZ)) != 0)
2591                 PRINTK("Timer pending while modifying cleanup timer\n");
2592 }
2593
2594 static inline void
2595 helper_drain_queues(void)
2596 {
2597         struct work_element *pq_p;
2598         struct list_head *lptr, *tptr;
2599
2600         list_for_each_safe(lptr, tptr, &pending_list) {
2601                 pq_p = list_entry(lptr, struct work_element, liste);
2602                 pq_p->retcode = -ENODEV;
2603                 pq_p->status[0] |= STAT_FAILED;
2604                 unbuild_caller(LONG2DEVPTR(pq_p->devindex),
2605                                (struct caller *)pq_p->requestptr);
2606                 list_del(lptr);
2607                 pendingq_count--;
2608                 pq_p->audit[1] |= FP_NOTPENDING;
2609                 pq_p->audit[1] |= FP_AWAKENING;
2610                 atomic_set(&pq_p->alarmrung, 1);
2611                 wake_up(&pq_p->waitq);
2612         }
2613
2614         list_for_each_safe(lptr, tptr, &request_list) {
2615                 pq_p = list_entry(lptr, struct work_element, liste);
2616                 pq_p->retcode = -ENODEV;
2617                 pq_p->status[0] |= STAT_FAILED;
2618                 list_del(lptr);
2619                 requestq_count--;
2620                 pq_p->audit[1] |= FP_REMREQUEST;
2621                 pq_p->audit[1] |= FP_AWAKENING;
2622                 atomic_set(&pq_p->alarmrung, 1);
2623                 wake_up(&pq_p->waitq);
2624         }
2625 }
2626
2627 static inline void
2628 helper_timeout_requests(void)
2629 {
2630         struct work_element *pq_p;
2631         struct list_head *lptr, *tptr;
2632         long timelimit;
2633
2634         timelimit = jiffies - (CLEANUPTIME * HZ);
2635         /* The list is in strict chronological order */
2636         list_for_each_safe(lptr, tptr, &pending_list) {
2637                 pq_p = list_entry(lptr, struct work_element, liste);
2638                 if (pq_p->requestsent >= timelimit)
2639                         break;
2640                 pq_p->retcode = -ETIMEOUT;
2641                 pq_p->status[0] |= STAT_FAILED;
2642                 /* get this off any caller queue it may be on */
2643                 unbuild_caller(LONG2DEVPTR(pq_p->devindex),
2644                                (struct caller *) pq_p->requestptr);
2645                 list_del(lptr);
2646                 pendingq_count--;
2647                 pq_p->audit[1] |= FP_TIMEDOUT;
2648                 pq_p->audit[1] |= FP_NOTPENDING;
2649                 pq_p->audit[1] |= FP_AWAKENING;
2650                 atomic_set(&pq_p->alarmrung, 1);
2651                 wake_up(&pq_p->waitq);
2652         }
2653
2654         /**
2655          * If pending count is zero, items left on the request queue may
2656          * never be processed.
2657          */
2658         if (pendingq_count <= 0) {
2659                 list_for_each_safe(lptr, tptr, &request_list) {
2660                         pq_p = list_entry(lptr, struct work_element, liste);
2661                         if (pq_p->requestsent >= timelimit)
2662                                 break;
2663                         pq_p->retcode = -ETIMEOUT;
2664                         pq_p->status[0] |= STAT_FAILED;
2665                         list_del(lptr);
2666                         requestq_count--;
2667                         pq_p->audit[1] |= FP_TIMEDOUT;
2668                         pq_p->audit[1] |= FP_REMREQUEST;
2669                         pq_p->audit[1] |= FP_AWAKENING;
2670                         atomic_set(&pq_p->alarmrung, 1);
2671                         wake_up(&pq_p->waitq);
2672                 }
2673         }
2674 }
2675
2676 static void
2677 z90crypt_cleanup_task(unsigned long ptr)
2678 {
2679         PDEBUG("jiffies %ld\n", jiffies);
2680         spin_lock_irq(&queuespinlock);
2681         if (z90crypt.mask.st_count <= 0) // no devices!
2682                 helper_drain_queues();
2683         else
2684                 helper_timeout_requests();
2685         spin_unlock_irq(&queuespinlock);
2686         z90crypt_schedule_cleanup_task();
2687 }
2688
2689 static void
2690 z90crypt_schedule_reader_task(unsigned long ptr)
2691 {
2692         tasklet_schedule(&reader_tasklet);
2693 }
2694
2695 /**
2696  * Lowlevel Functions:
2697  *
2698  *   create_z90crypt:  creates and initializes basic data structures
2699  *   refresh_z90crypt:  re-initializes basic data structures
2700  *   find_crypto_devices: returns a count and mask of hardware status
2701  *   create_crypto_device:  builds the descriptor for a device
2702  *   destroy_crypto_device:  unallocates the descriptor for a device
2703  *   destroy_z90crypt:  drains all work, unallocates structs
2704  */
2705
2706 /**
2707  * build the z90crypt root structure using the given domain index
2708  */
2709 static int
2710 create_z90crypt(int *cdx_p)
2711 {
2712         struct hdware_block *hdware_blk_p;
2713
2714         memset(&z90crypt, 0x00, sizeof(struct z90crypt));
2715         z90crypt.domain_established = 0;
2716         z90crypt.len = sizeof(struct z90crypt);
2717         z90crypt.max_count = Z90CRYPT_NUM_DEVS;
2718         z90crypt.cdx = *cdx_p;
2719
2720         hdware_blk_p = (struct hdware_block *)
2721                 kmalloc(sizeof(struct hdware_block), GFP_ATOMIC);
2722         if (!hdware_blk_p) {
2723                 PDEBUG("kmalloc for hardware block failed\n");
2724                 return ENOMEM;
2725         }
2726         memset(hdware_blk_p, 0x00, sizeof(struct hdware_block));
2727         z90crypt.hdware_info = hdware_blk_p;
2728
2729         return 0;
2730 }
2731
2732 static inline int
2733 helper_scan_devices(int cdx_array[16], int *cdx_p, int *correct_cdx_found)
2734 {
2735         enum hdstat hd_stat;
2736         int q_depth, dev_type;
2737         int i, j, k;
2738
2739         q_depth = dev_type = k = 0;
2740         for (i = 0; i < z90crypt.max_count; i++) {
2741                 hd_stat = HD_NOT_THERE;
2742                 for (j = 0; j <= 15; cdx_array[j++] = -1);
2743                 k = 0;
2744                 for (j = 0; j <= 15; j++) {
2745                         hd_stat = query_online(i, j, MAX_RESET,
2746                                                &q_depth, &dev_type);
2747                         if (hd_stat == HD_TSQ_EXCEPTION) {
2748                                 z90crypt.terminating = 1;
2749                                 PRINTKC("exception taken!\n");
2750                                 break;
2751                         }
2752                         if (hd_stat == HD_ONLINE) {
2753                                 cdx_array[k++] = j;
2754                                 if (*cdx_p == j) {
2755                                         *correct_cdx_found  = 1;
2756                                         break;
2757                                 }
2758                         }
2759                 }
2760                 if ((*correct_cdx_found == 1) || (k != 0))
2761                         break;
2762                 if (z90crypt.terminating)
2763                         break;
2764         }
2765         return k;
2766 }
2767
2768 static inline int
2769 probe_crypto_domain(int *cdx_p)
2770 {
2771         int cdx_array[16];
2772         int correct_cdx_found, k;
2773
2774         correct_cdx_found = 0;
2775         k = helper_scan_devices(cdx_array, cdx_p, &correct_cdx_found);
2776
2777         if (z90crypt.terminating)
2778                 return TSQ_FATAL_ERROR;
2779
2780         if (correct_cdx_found)
2781                 return 0;
2782
2783         if (k == 0) {
2784                 *cdx_p = 0;
2785                 return 0;
2786         }
2787
2788         if (k == 1) {
2789                 if ((*cdx_p == -1) || !z90crypt.domain_established) {
2790                         *cdx_p = cdx_array[0];
2791                         return 0;
2792                 }
2793                 if (*cdx_p != cdx_array[0]) {
2794                         PRINTK("incorrect domain: specified = %d, found = %d\n",
2795                                *cdx_p, cdx_array[0]);
2796                         return Z90C_INCORRECT_DOMAIN;
2797                 }
2798         }
2799
2800         return Z90C_AMBIGUOUS_DOMAIN;
2801 }
2802
2803 static int
2804 refresh_z90crypt(int *cdx_p)
2805 {
2806         int i, j, indx, rv;
2807         struct status local_mask;
2808         struct device *devPtr;
2809         unsigned char oldStat, newStat;
2810         int return_unchanged;
2811
2812         if (z90crypt.len != sizeof(z90crypt))
2813                 return ENOTINIT;
2814         if (z90crypt.terminating)
2815                 return TSQ_FATAL_ERROR;
2816         rv = 0;
2817         if (!z90crypt.hdware_info->hdware_mask.st_count &&
2818             !z90crypt.domain_established)
2819                 rv = probe_crypto_domain(cdx_p);
2820         if (z90crypt.terminating)
2821                 return TSQ_FATAL_ERROR;
2822         if (rv) {
2823                 switch (rv) {
2824                 case Z90C_AMBIGUOUS_DOMAIN:
2825                         PRINTK("ambiguous domain detected\n");
2826                         break;
2827                 case Z90C_INCORRECT_DOMAIN:
2828                         PRINTK("incorrect domain specified\n");
2829                         break;
2830                 default:
2831                         PRINTK("probe domain returned %d\n", rv);
2832                         break;
2833                 }
2834                 return rv;
2835         }
2836         if (*cdx_p) {
2837                 z90crypt.cdx = *cdx_p;
2838                 z90crypt.domain_established = 1;
2839         }
2840         rv = find_crypto_devices(&local_mask);
2841         if (rv) {
2842                 PRINTK("find crypto devices returned %d\n", rv);
2843                 return rv;
2844         }
2845         if (!memcmp(&local_mask, &z90crypt.hdware_info->hdware_mask,
2846                     sizeof(struct status))) {
2847                 return_unchanged = 1;
2848                 for (i = 0; i < Z90CRYPT_NUM_TYPES; i++) {
2849                         /**
2850                          * Check for disabled cards.  If any device is marked
2851                          * disabled, destroy it.
2852                          */
2853                         for (j = 0;
2854                              j < z90crypt.hdware_info->type_mask[i].st_count;
2855                              j++) {
2856                                 indx = z90crypt.hdware_info->type_x_addr[i].
2857                                                                 device_index[j];
2858                                 devPtr = z90crypt.device_p[indx];
2859                                 if (devPtr && devPtr->disabled) {
2860                                         local_mask.st_mask[indx] = HD_NOT_THERE;
2861                                         return_unchanged = 0;
2862                                 }
2863                         }
2864                 }
2865                 if (return_unchanged == 1)
2866                         return 0;
2867         }
2868
2869         spin_lock_irq(&queuespinlock);
2870         for (i = 0; i < z90crypt.max_count; i++) {
2871                 oldStat = z90crypt.hdware_info->hdware_mask.st_mask[i];
2872                 newStat = local_mask.st_mask[i];
2873                 if ((oldStat == HD_ONLINE) && (newStat != HD_ONLINE))
2874                         destroy_crypto_device(i);
2875                 else if ((oldStat != HD_ONLINE) && (newStat == HD_ONLINE)) {
2876                         rv = create_crypto_device(i);
2877                         if (rv >= REC_FATAL_ERROR)
2878                                 return rv;
2879                         if (rv != 0) {
2880                                 local_mask.st_mask[i] = HD_NOT_THERE;
2881                                 local_mask.st_count--;
2882                         }
2883                 }
2884         }
2885         memcpy(z90crypt.hdware_info->hdware_mask.st_mask, local_mask.st_mask,
2886                sizeof(local_mask.st_mask));
2887         z90crypt.hdware_info->hdware_mask.st_count = local_mask.st_count;
2888         z90crypt.hdware_info->hdware_mask.disabled_count =
2889                                                       local_mask.disabled_count;
2890         refresh_index_array(&z90crypt.mask, &z90crypt.overall_device_x);
2891         for (i = 0; i < Z90CRYPT_NUM_TYPES; i++)
2892                 refresh_index_array(&(z90crypt.hdware_info->type_mask[i]),
2893                                     &(z90crypt.hdware_info->type_x_addr[i]));
2894         spin_unlock_irq(&queuespinlock);
2895
2896         return rv;
2897 }
2898
2899 static int
2900 find_crypto_devices(struct status *deviceMask)
2901 {
2902         int i, q_depth, dev_type;
2903         enum hdstat hd_stat;
2904
2905         deviceMask->st_count = 0;
2906         deviceMask->disabled_count = 0;
2907         deviceMask->user_disabled_count = 0;
2908
2909         for (i = 0; i < z90crypt.max_count; i++) {
2910                 hd_stat = query_online(i, z90crypt.cdx, MAX_RESET, &q_depth,
2911                                        &dev_type);
2912                 if (hd_stat == HD_TSQ_EXCEPTION) {
2913                         z90crypt.terminating = 1;
2914                         PRINTKC("Exception during probe for crypto devices\n");
2915                         return TSQ_FATAL_ERROR;
2916                 }
2917                 deviceMask->st_mask[i] = hd_stat;
2918                 if (hd_stat == HD_ONLINE) {
2919                         PDEBUG("Got an online crypto!: %d\n", i);
2920                         PDEBUG("Got a queue depth of %d\n", q_depth);
2921                         PDEBUG("Got a device type of %d\n", dev_type);
2922                         if (q_depth <= 0)
2923                                 return TSQ_FATAL_ERROR;
2924                         deviceMask->st_count++;
2925                         z90crypt.q_depth_array[i] = q_depth;
2926                         z90crypt.dev_type_array[i] = dev_type;
2927                 }
2928         }
2929
2930         return 0;
2931 }
2932
2933 static int
2934 refresh_index_array(struct status *status_str, struct device_x *index_array)
2935 {
2936         int i, count;
2937         enum devstat stat;
2938
2939         i = -1;
2940         count = 0;
2941         do {
2942                 stat = status_str->st_mask[++i];
2943                 if (stat == DEV_ONLINE)
2944                         index_array->device_index[count++] = i;
2945         } while ((i < Z90CRYPT_NUM_DEVS) && (count < status_str->st_count));
2946
2947         return count;
2948 }
2949
2950 static int
2951 create_crypto_device(int index)
2952 {
2953         int rv, devstat, total_size;
2954         struct device *dev_ptr;
2955         struct status *type_str_p;
2956         int deviceType;
2957
2958         dev_ptr = z90crypt.device_p[index];
2959         if (!dev_ptr) {
2960                 total_size = sizeof(struct device) +
2961                              z90crypt.q_depth_array[index] * sizeof(int);
2962
2963                 dev_ptr = (struct device *) kmalloc(total_size, GFP_ATOMIC);
2964                 if (!dev_ptr) {
2965                         PRINTK("kmalloc device %d failed\n", index);
2966                         return ENOMEM;
2967                 }
2968                 memset(dev_ptr, 0, total_size);
2969                 dev_ptr->dev_resp_p = kmalloc(MAX_RESPONSE_SIZE, GFP_ATOMIC);
2970                 if (!dev_ptr->dev_resp_p) {
2971                         kfree(dev_ptr);
2972                         PRINTK("kmalloc device %d rec buffer failed\n", index);
2973                         return ENOMEM;
2974                 }
2975                 dev_ptr->dev_resp_l = MAX_RESPONSE_SIZE;
2976                 INIT_LIST_HEAD(&(dev_ptr->dev_caller_list));
2977         }
2978
2979         devstat = reset_device(index, z90crypt.cdx, MAX_RESET);
2980         if (devstat == DEV_RSQ_EXCEPTION) {
2981                 PRINTK("exception during reset device %d\n", index);
2982                 kfree(dev_ptr->dev_resp_p);
2983                 kfree(dev_ptr);
2984                 return RSQ_FATAL_ERROR;
2985         }
2986         if (devstat == DEV_ONLINE) {
2987                 dev_ptr->dev_self_x = index;
2988                 dev_ptr->dev_type = z90crypt.dev_type_array[index];
2989                 if (dev_ptr->dev_type == NILDEV) {
2990                         rv = probe_device_type(dev_ptr);
2991                         if (rv) {
2992                                 PRINTK("rv = %d from probe_device_type %d\n",
2993                                        rv, index);
2994                                 kfree(dev_ptr->dev_resp_p);
2995                                 kfree(dev_ptr);
2996                                 return rv;
2997                         }
2998                 }
2999                 deviceType = dev_ptr->dev_type;
3000                 z90crypt.dev_type_array[index] = deviceType;
3001                 if (deviceType == PCICA)
3002                         z90crypt.hdware_info->device_type_array[index] = 1;
3003                 else if (deviceType == PCICC)
3004                         z90crypt.hdware_info->device_type_array[index] = 2;
3005                 else if (deviceType == PCIXCC)
3006                         z90crypt.hdware_info->device_type_array[index] = 3;
3007                 else
3008                         z90crypt.hdware_info->device_type_array[index] = -1;
3009         }
3010
3011         /**
3012          * 'q_depth' returned by the hardware is one less than
3013          * the actual depth
3014          */
3015         dev_ptr->dev_q_depth = z90crypt.q_depth_array[index];
3016         dev_ptr->dev_type = z90crypt.dev_type_array[index];
3017         dev_ptr->dev_stat = devstat;
3018         dev_ptr->disabled = 0;
3019         z90crypt.device_p[index] = dev_ptr;
3020
3021         if (devstat == DEV_ONLINE) {
3022                 if (z90crypt.mask.st_mask[index] != DEV_ONLINE) {
3023                         z90crypt.mask.st_mask[index] = DEV_ONLINE;
3024                         z90crypt.mask.st_count++;
3025                 }
3026                 deviceType = dev_ptr->dev_type;
3027                 type_str_p = &z90crypt.hdware_info->type_mask[deviceType];
3028                 if (type_str_p->st_mask[index] != DEV_ONLINE) {
3029                         type_str_p->st_mask[index] = DEV_ONLINE;
3030                         type_str_p->st_count++;
3031                 }
3032         }
3033
3034         return 0;
3035 }
3036
3037 static int
3038 destroy_crypto_device(int index)
3039 {
3040         struct device *dev_ptr;
3041         int t, disabledFlag;
3042
3043         dev_ptr = z90crypt.device_p[index];
3044
3045         /* remember device type; get rid of device struct */
3046         if (dev_ptr) {
3047                 disabledFlag = dev_ptr->disabled;
3048                 t = dev_ptr->dev_type;
3049                 if (dev_ptr->dev_resp_p)
3050                         kfree(dev_ptr->dev_resp_p);
3051                 kfree(dev_ptr);
3052         } else {
3053                 disabledFlag = 0;
3054                 t = -1;
3055         }
3056         z90crypt.device_p[index] = 0;
3057
3058         /* if the type is valid, remove the device from the type_mask */
3059         if ((t != -1) && z90crypt.hdware_info->type_mask[t].st_mask[index]) {
3060                   z90crypt.hdware_info->type_mask[t].st_mask[index] = 0x00;
3061                   z90crypt.hdware_info->type_mask[t].st_count--;
3062                   if (disabledFlag == 1)
3063                         z90crypt.hdware_info->type_mask[t].disabled_count--;
3064         }
3065         if (z90crypt.mask.st_mask[index] != DEV_GONE) {
3066                 z90crypt.mask.st_mask[index] = DEV_GONE;
3067                 z90crypt.mask.st_count--;
3068         }
3069         z90crypt.hdware_info->device_type_array[index] = 0;
3070
3071         return 0;
3072 }
3073
3074 static void
3075 destroy_z90crypt(void)
3076 {
3077         int i;
3078         for (i = 0; i < z90crypt.max_count; i++)
3079                 if (z90crypt.device_p[i])
3080                         destroy_crypto_device(i);
3081         if (z90crypt.hdware_info)
3082                 kfree((void *)z90crypt.hdware_info);
3083         memset((void *)&z90crypt, 0, sizeof(z90crypt));
3084 }
3085
3086 static unsigned char static_testmsg[] = {
3087 0x00,0x00,0x00,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x00,0x06,0x00,0x00,
3088 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x58,
3089 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x43,0x43,
3090 0x41,0x2d,0x41,0x50,0x50,0x4c,0x20,0x20,0x20,0x01,0x01,0x01,0x00,0x00,0x00,0x00,
3091 0x50,0x4b,0x00,0x00,0x00,0x00,0x01,0x1c,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
3092 0x00,0x00,0x00,0x00,0x00,0x00,0x05,0xb8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
3093 0x00,0x00,0x00,0x00,0x70,0x00,0x41,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x54,0x32,
3094 0x01,0x00,0xa0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
3095 0xb8,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
3096 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
3097 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
3098 0x00,0x00,0x00,0x00,0x00,0x00,0x0a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
3099 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x49,0x43,0x53,0x46,
3100 0x20,0x20,0x20,0x20,0x50,0x4b,0x0a,0x00,0x50,0x4b,0x43,0x53,0x2d,0x31,0x2e,0x32,
3101 0x37,0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0x00,0x11,0x22,0x33,0x44,
3102 0x55,0x66,0x77,0x88,0x99,0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0x00,
3103 0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0x00,0x11,0x22,0x33,0x44,0x55,0x66,
3104 0x77,0x88,0x99,0x00,0x11,0x22,0x33,0x5d,0x00,0x5b,0x00,0x77,0x88,0x1e,0x00,0x00,
3105 0x57,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x4f,0x00,0x00,0x00,0x03,0x02,0x00,0x00,
3106 0x40,0x01,0x00,0x01,0xce,0x02,0x68,0x2d,0x5f,0xa9,0xde,0x0c,0xf6,0xd2,0x7b,0x58,
3107 0x4b,0xf9,0x28,0x68,0x3d,0xb4,0xf4,0xef,0x78,0xd5,0xbe,0x66,0x63,0x42,0xef,0xf8,
3108 0xfd,0xa4,0xf8,0xb0,0x8e,0x29,0xc2,0xc9,0x2e,0xd8,0x45,0xb8,0x53,0x8c,0x6f,0x4e,
3109 0x72,0x8f,0x6c,0x04,0x9c,0x88,0xfc,0x1e,0xc5,0x83,0x55,0x57,0xf7,0xdd,0xfd,0x4f,
3110 0x11,0x36,0x95,0x5d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
3111 };
3112
3113 static int
3114 probe_device_type(struct device *devPtr)
3115 {
3116         int rv, dv, i, index, length;
3117         unsigned char psmid[8];
3118         static unsigned char loc_testmsg[384];
3119
3120         index = devPtr->dev_self_x;
3121         rv = 0;
3122         do {
3123                 memcpy(loc_testmsg, static_testmsg, sizeof(static_testmsg));
3124                 length = sizeof(static_testmsg) - 24;
3125                 /* the -24 allows for the header */
3126                 dv = send_to_AP(index, z90crypt.cdx, length, loc_testmsg);
3127                 if (dv) {
3128                         PDEBUG("dv returned by send during probe: %d\n", dv);
3129                         if (dv == DEV_SEN_EXCEPTION) {
3130                                 rv = SEN_FATAL_ERROR;
3131                                 PRINTKC("exception in send to AP %d\n", index);
3132                                 break;
3133                         }
3134                         PDEBUG("return value from send_to_AP: %d\n", rv);
3135                         switch (dv) {
3136                         case DEV_GONE:
3137                                 PDEBUG("dev %d not available\n", index);
3138                                 rv = SEN_NOT_AVAIL;
3139                                 break;
3140                         case DEV_ONLINE:
3141                                 rv = 0;
3142                                 break;
3143                         case DEV_EMPTY:
3144                                 rv = SEN_NOT_AVAIL;
3145                                 break;
3146                         case DEV_NO_WORK:
3147                                 rv = SEN_FATAL_ERROR;
3148                                 break;
3149                         case DEV_BAD_MESSAGE:
3150                                 rv = SEN_USER_ERROR;
3151                                 break;
3152                         case DEV_QUEUE_FULL:
3153                                 rv = SEN_QUEUE_FULL;
3154                                 break;
3155                         default:
3156                                 PRINTK("unknown dv=%d for dev %d\n", dv, index);
3157                                 rv = SEN_NOT_AVAIL;
3158                                 break;
3159                         }
3160                 }
3161
3162                 if (rv)
3163                         break;
3164
3165                 for (i = 0; i < 6; i++) {
3166                         mdelay(300);
3167                         dv = receive_from_AP(index, z90crypt.cdx,
3168                                              devPtr->dev_resp_l,
3169                                              devPtr->dev_resp_p, psmid);
3170                         PDEBUG("dv returned by DQ = %d\n", dv);
3171                         if (dv == DEV_REC_EXCEPTION) {
3172                                 rv = REC_FATAL_ERROR;
3173                                 PRINTKC("exception in dequeue %d\n",
3174                                         index);
3175                                 break;
3176                         }
3177                         switch (dv) {
3178                         case DEV_ONLINE:
3179                                 rv = 0;
3180                                 break;
3181                         case DEV_EMPTY:
3182                                 rv = REC_EMPTY;
3183                                 break;
3184                         case DEV_NO_WORK:
3185                                 rv = REC_NO_WORK;
3186                                 break;
3187                         case DEV_BAD_MESSAGE:
3188                         case DEV_GONE:
3189                         default:
3190                                 rv = REC_NO_RESPONSE;
3191                                 break;
3192                         }
3193                         if ((rv != 0) && (rv != REC_NO_WORK))
3194                                 break;
3195                         if (rv == 0)
3196                                 break;
3197                 }
3198                 if (rv)
3199                         break;
3200                 rv = (devPtr->dev_resp_p[0] == 0x00) &&
3201                      (devPtr->dev_resp_p[1] == 0x86);
3202                 if (rv)
3203                         devPtr->dev_type = PCICC;
3204                 else
3205                         devPtr->dev_type = PCICA;
3206                 rv = 0;
3207         } while (0);
3208         /* In a general error case, the card is not marked online */
3209         return rv;
3210 }
3211
3212 #ifdef Z90CRYPT_USE_HOTPLUG
3213 void
3214 z90crypt_hotplug_event(int dev_major, int dev_minor, int action)
3215 {
3216 #ifdef CONFIG_HOTPLUG
3217         char *argv[3];
3218         char *envp[6];
3219         char  major[20];
3220         char  minor[20];
3221
3222         sprintf(major, "MAJOR=%d", dev_major);
3223         sprintf(minor, "MINOR=%d", dev_minor);
3224
3225         argv[0] = hotplug_path;
3226         argv[1] = "z90crypt";
3227         argv[2] = 0;
3228
3229         envp[0] = "HOME=/";
3230         envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
3231
3232         switch (action) {
3233         case Z90CRYPT_HOTPLUG_ADD:
3234                 envp[2] = "ACTION=add";
3235                 break;
3236         case Z90CRYPT_HOTPLUG_REMOVE:
3237                 envp[2] = "ACTION=remove";
3238                 break;
3239         default:
3240                 BUG();
3241         }
3242         envp[3] = major;
3243         envp[4] = minor;
3244         envp[5] = 0;
3245
3246         call_usermodehelper(argv[0], argv, envp, 0);
3247 #endif
3248 }
3249 #endif
3250
3251 module_init(z90crypt_init_module);
3252 module_exit(z90crypt_cleanup_module);