Root/target/linux/generic/files/crypto/ocf/crypto.c

1/*-
2 * Linux port done by David McCullough <david_mccullough@mcafee.com>
3 * Copyright (C) 2006-2010 David McCullough
4 * Copyright (C) 2004-2005 Intel Corporation.
5 * The license and original author are listed below.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * Copyright (c) 2002-2006 Sam Leffler. All rights reserved.
9 *
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30#if 0
31#include <sys/cdefs.h>
32__FBSDID("$FreeBSD: src/sys/opencrypto/crypto.c,v 1.27 2007/03/21 03:42:51 sam Exp $");
33#endif
34
35/*
36 * Cryptographic Subsystem.
37 *
38 * This code is derived from the Openbsd Cryptographic Framework (OCF)
39 * that has the copyright shown below. Very little of the original
40 * code remains.
41 */
42/*-
43 * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
44 *
45 * This code was written by Angelos D. Keromytis in Athens, Greece, in
46 * February 2000. Network Security Technologies Inc. (NSTI) kindly
47 * supported the development of this code.
48 *
49 * Copyright (c) 2000, 2001 Angelos D. Keromytis
50 *
51 * Permission to use, copy, and modify this software with or without fee
52 * is hereby granted, provided that this entire notice is included in
53 * all source code copies of any software which is or includes a copy or
54 * modification of this software.
55 *
56 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
57 * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
58 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
59 * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
60 * PURPOSE.
61 *
62__FBSDID("$FreeBSD: src/sys/opencrypto/crypto.c,v 1.16 2005/01/07 02:29:16 imp Exp $");
63 */
64
65
66#include <linux/version.h>
67#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,33))
68#include <generated/autoconf.h>
69#else
70#include <linux/autoconf.h>
71#endif
72#include <linux/module.h>
73#include <linux/init.h>
74#include <linux/list.h>
75#include <linux/slab.h>
76#include <linux/wait.h>
77#include <linux/sched.h>
78#include <linux/spinlock.h>
79#include <linux/version.h>
80#include <cryptodev.h>
81
82/*
83 * keep track of whether or not we have been initialised, a big
84 * issue if we are linked into the kernel and a driver gets started before
85 * us
86 */
87static int crypto_initted = 0;
88
89/*
90 * Crypto drivers register themselves by allocating a slot in the
91 * crypto_drivers table with crypto_get_driverid() and then registering
92 * each algorithm they support with crypto_register() and crypto_kregister().
93 */
94
95/*
96 * lock on driver table
97 * we track its state as spin_is_locked does not do anything on non-SMP boxes
98 */
99static spinlock_t crypto_drivers_lock;
100static int crypto_drivers_locked; /* for non-SMP boxes */
101
102#define CRYPTO_DRIVER_LOCK() \
103            ({ \
104                spin_lock_irqsave(&crypto_drivers_lock, d_flags); \
105                 crypto_drivers_locked = 1; \
106                dprintk("%s,%d: DRIVER_LOCK()\n", __FILE__, __LINE__); \
107             })
108#define CRYPTO_DRIVER_UNLOCK() \
109            ({ \
110                 dprintk("%s,%d: DRIVER_UNLOCK()\n", __FILE__, __LINE__); \
111                 crypto_drivers_locked = 0; \
112                spin_unlock_irqrestore(&crypto_drivers_lock, d_flags); \
113             })
114#define CRYPTO_DRIVER_ASSERT() \
115            ({ \
116                 if (!crypto_drivers_locked) { \
117                    dprintk("%s,%d: DRIVER_ASSERT!\n", __FILE__, __LINE__); \
118                 } \
119             })
120
121/*
122 * Crypto device/driver capabilities structure.
123 *
124 * Synchronization:
125 * (d) - protected by CRYPTO_DRIVER_LOCK()
126 * (q) - protected by CRYPTO_Q_LOCK()
127 * Not tagged fields are read-only.
128 */
129struct cryptocap {
130    device_t cc_dev; /* (d) device/driver */
131    u_int32_t cc_sessions; /* (d) # of sessions */
132    u_int32_t cc_koperations; /* (d) # os asym operations */
133    /*
134     * Largest possible operator length (in bits) for each type of
135     * encryption algorithm. XXX not used
136     */
137    u_int16_t cc_max_op_len[CRYPTO_ALGORITHM_MAX + 1];
138    u_int8_t cc_alg[CRYPTO_ALGORITHM_MAX + 1];
139    u_int8_t cc_kalg[CRK_ALGORITHM_MAX + 1];
140
141    int cc_flags; /* (d) flags */
142#define CRYPTOCAP_F_CLEANUP 0x80000000 /* needs resource cleanup */
143    int cc_qblocked; /* (q) symmetric q blocked */
144    int cc_kqblocked; /* (q) asymmetric q blocked */
145
146    int cc_unqblocked; /* (q) symmetric q blocked */
147    int cc_unkqblocked; /* (q) asymmetric q blocked */
148};
149static struct cryptocap *crypto_drivers = NULL;
150static int crypto_drivers_num = 0;
151
152/*
153 * There are two queues for crypto requests; one for symmetric (e.g.
154 * cipher) operations and one for asymmetric (e.g. MOD)operations.
155 * A single mutex is used to lock access to both queues. We could
156 * have one per-queue but having one simplifies handling of block/unblock
157 * operations.
158 */
159static int crp_sleep = 0;
160static LIST_HEAD(crp_q); /* request queues */
161static LIST_HEAD(crp_kq);
162
163static spinlock_t crypto_q_lock;
164
165int crypto_all_qblocked = 0; /* protect with Q_LOCK */
166module_param(crypto_all_qblocked, int, 0444);
167MODULE_PARM_DESC(crypto_all_qblocked, "Are all crypto queues blocked");
168
169int crypto_all_kqblocked = 0; /* protect with Q_LOCK */
170module_param(crypto_all_kqblocked, int, 0444);
171MODULE_PARM_DESC(crypto_all_kqblocked, "Are all asym crypto queues blocked");
172
173#define CRYPTO_Q_LOCK() \
174            ({ \
175                spin_lock_irqsave(&crypto_q_lock, q_flags); \
176                 dprintk("%s,%d: Q_LOCK()\n", __FILE__, __LINE__); \
177             })
178#define CRYPTO_Q_UNLOCK() \
179            ({ \
180                 dprintk("%s,%d: Q_UNLOCK()\n", __FILE__, __LINE__); \
181                spin_unlock_irqrestore(&crypto_q_lock, q_flags); \
182             })
183
184/*
185 * There are two queues for processing completed crypto requests; one
186 * for the symmetric and one for the asymmetric ops. We only need one
187 * but have two to avoid type futzing (cryptop vs. cryptkop). A single
188 * mutex is used to lock access to both queues. Note that this lock
189 * must be separate from the lock on request queues to insure driver
190 * callbacks don't generate lock order reversals.
191 */
192static LIST_HEAD(crp_ret_q); /* callback queues */
193static LIST_HEAD(crp_ret_kq);
194
195static spinlock_t crypto_ret_q_lock;
196#define CRYPTO_RETQ_LOCK() \
197            ({ \
198                spin_lock_irqsave(&crypto_ret_q_lock, r_flags); \
199                dprintk("%s,%d: RETQ_LOCK\n", __FILE__, __LINE__); \
200             })
201#define CRYPTO_RETQ_UNLOCK() \
202            ({ \
203                 dprintk("%s,%d: RETQ_UNLOCK\n", __FILE__, __LINE__); \
204                spin_unlock_irqrestore(&crypto_ret_q_lock, r_flags); \
205             })
206#define CRYPTO_RETQ_EMPTY() (list_empty(&crp_ret_q) && list_empty(&crp_ret_kq))
207
208#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20)
209static kmem_cache_t *cryptop_zone;
210static kmem_cache_t *cryptodesc_zone;
211#else
212static struct kmem_cache *cryptop_zone;
213static struct kmem_cache *cryptodesc_zone;
214#endif
215
216#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
217#include <linux/sched.h>
218#define kill_proc(p,s,v) send_sig(s,find_task_by_vpid(p),0)
219#endif
220
221#define debug crypto_debug
222int crypto_debug = 0;
223module_param(crypto_debug, int, 0644);
224MODULE_PARM_DESC(crypto_debug, "Enable debug");
225EXPORT_SYMBOL(crypto_debug);
226
227/*
228 * Maximum number of outstanding crypto requests before we start
229 * failing requests. We need this to prevent DOS when too many
230 * requests are arriving for us to keep up. Otherwise we will
231 * run the system out of memory. Since crypto is slow, we are
232 * usually the bottleneck that needs to say, enough is enough.
233 *
234 * We cannot print errors when this condition occurs, we are already too
235 * slow, printing anything will just kill us
236 */
237
238static int crypto_q_cnt = 0;
239module_param(crypto_q_cnt, int, 0444);
240MODULE_PARM_DESC(crypto_q_cnt,
241        "Current number of outstanding crypto requests");
242
243static int crypto_q_max = 1000;
244module_param(crypto_q_max, int, 0644);
245MODULE_PARM_DESC(crypto_q_max,
246        "Maximum number of outstanding crypto requests");
247
248#define bootverbose crypto_verbose
249static int crypto_verbose = 0;
250module_param(crypto_verbose, int, 0644);
251MODULE_PARM_DESC(crypto_verbose,
252        "Enable verbose crypto startup");
253
254int crypto_usercrypto = 1; /* userland may do crypto reqs */
255module_param(crypto_usercrypto, int, 0644);
256MODULE_PARM_DESC(crypto_usercrypto,
257       "Enable/disable user-mode access to crypto support");
258
259int crypto_userasymcrypto = 1; /* userland may do asym crypto reqs */
260module_param(crypto_userasymcrypto, int, 0644);
261MODULE_PARM_DESC(crypto_userasymcrypto,
262       "Enable/disable user-mode access to asymmetric crypto support");
263
264int crypto_devallowsoft = 0; /* only use hardware crypto */
265module_param(crypto_devallowsoft, int, 0644);
266MODULE_PARM_DESC(crypto_devallowsoft,
267       "Enable/disable use of software crypto support");
268
269/*
270 * This parameter controls the maximum number of crypto operations to
271 * do consecutively in the crypto kernel thread before scheduling to allow
272 * other processes to run. Without it, it is possible to get into a
273 * situation where the crypto thread never allows any other processes to run.
274 * Default to 1000 which should be less than one second.
275 */
276static int crypto_max_loopcount = 1000;
277module_param(crypto_max_loopcount, int, 0644);
278MODULE_PARM_DESC(crypto_max_loopcount,
279       "Maximum number of crypto ops to do before yielding to other processes");
280
281static pid_t cryptoproc = (pid_t) -1;
282static struct completion cryptoproc_exited;
283static DECLARE_WAIT_QUEUE_HEAD(cryptoproc_wait);
284static pid_t cryptoretproc = (pid_t) -1;
285static struct completion cryptoretproc_exited;
286static DECLARE_WAIT_QUEUE_HEAD(cryptoretproc_wait);
287
288static int crypto_proc(void *arg);
289static int crypto_ret_proc(void *arg);
290static int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
291static int crypto_kinvoke(struct cryptkop *krp, int flags);
292static void crypto_exit(void);
293static int crypto_init(void);
294
295static struct cryptostats cryptostats;
296
297static struct cryptocap *
298crypto_checkdriver(u_int32_t hid)
299{
300    if (crypto_drivers == NULL)
301        return NULL;
302    return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
303}
304
305/*
306 * Compare a driver's list of supported algorithms against another
307 * list; return non-zero if all algorithms are supported.
308 */
309static int
310driver_suitable(const struct cryptocap *cap, const struct cryptoini *cri)
311{
312    const struct cryptoini *cr;
313
314    /* See if all the algorithms are supported. */
315    for (cr = cri; cr; cr = cr->cri_next)
316        if (cap->cc_alg[cr->cri_alg] == 0)
317            return 0;
318    return 1;
319}
320
321/*
322 * Select a driver for a new session that supports the specified
323 * algorithms and, optionally, is constrained according to the flags.
324 * The algorithm we use here is pretty stupid; just use the
325 * first driver that supports all the algorithms we need. If there
326 * are multiple drivers we choose the driver with the fewest active
327 * sessions. We prefer hardware-backed drivers to software ones.
328 *
329 * XXX We need more smarts here (in real life too, but that's
330 * XXX another story altogether).
331 */
332static struct cryptocap *
333crypto_select_driver(const struct cryptoini *cri, int flags)
334{
335    struct cryptocap *cap, *best;
336    int match, hid;
337
338    CRYPTO_DRIVER_ASSERT();
339
340    /*
341     * Look first for hardware crypto devices if permitted.
342     */
343    if (flags & CRYPTOCAP_F_HARDWARE)
344        match = CRYPTOCAP_F_HARDWARE;
345    else
346        match = CRYPTOCAP_F_SOFTWARE;
347    best = NULL;
348again:
349    for (hid = 0; hid < crypto_drivers_num; hid++) {
350        cap = &crypto_drivers[hid];
351        /*
352         * If it's not initialized, is in the process of
353         * going away, or is not appropriate (hardware
354         * or software based on match), then skip.
355         */
356        if (cap->cc_dev == NULL ||
357            (cap->cc_flags & CRYPTOCAP_F_CLEANUP) ||
358            (cap->cc_flags & match) == 0)
359            continue;
360
361        /* verify all the algorithms are supported. */
362        if (driver_suitable(cap, cri)) {
363            if (best == NULL ||
364                cap->cc_sessions < best->cc_sessions)
365                best = cap;
366        }
367    }
368    if (best != NULL)
369        return best;
370    if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
371        /* sort of an Algol 68-style for loop */
372        match = CRYPTOCAP_F_SOFTWARE;
373        goto again;
374    }
375    return best;
376}
377
378/*
379 * Create a new session. The crid argument specifies a crypto
380 * driver to use or constraints on a driver to select (hardware
381 * only, software only, either). Whatever driver is selected
382 * must be capable of the requested crypto algorithms.
383 */
384int
385crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int crid)
386{
387    struct cryptocap *cap;
388    u_int32_t hid, lid;
389    int err;
390    unsigned long d_flags;
391
392    CRYPTO_DRIVER_LOCK();
393    if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
394        /*
395         * Use specified driver; verify it is capable.
396         */
397        cap = crypto_checkdriver(crid);
398        if (cap != NULL && !driver_suitable(cap, cri))
399            cap = NULL;
400    } else {
401        /*
402         * No requested driver; select based on crid flags.
403         */
404        cap = crypto_select_driver(cri, crid);
405        /*
406         * if NULL then can't do everything in one session.
407         * XXX Fix this. We need to inject a "virtual" session
408         * XXX layer right about here.
409         */
410    }
411    if (cap != NULL) {
412        /* Call the driver initialization routine. */
413        hid = cap - crypto_drivers;
414        lid = hid; /* Pass the driver ID. */
415        cap->cc_sessions++;
416        CRYPTO_DRIVER_UNLOCK();
417        err = CRYPTODEV_NEWSESSION(cap->cc_dev, &lid, cri);
418        CRYPTO_DRIVER_LOCK();
419        if (err == 0) {
420            (*sid) = (cap->cc_flags & 0xff000000)
421                   | (hid & 0x00ffffff);
422            (*sid) <<= 32;
423            (*sid) |= (lid & 0xffffffff);
424        } else
425            cap->cc_sessions--;
426    } else
427        err = EINVAL;
428    CRYPTO_DRIVER_UNLOCK();
429    return err;
430}
431
432static void
433crypto_remove(struct cryptocap *cap)
434{
435    CRYPTO_DRIVER_ASSERT();
436    if (cap->cc_sessions == 0 && cap->cc_koperations == 0)
437        bzero(cap, sizeof(*cap));
438}
439
440/*
441 * Delete an existing session (or a reserved session on an unregistered
442 * driver).
443 */
444int
445crypto_freesession(u_int64_t sid)
446{
447    struct cryptocap *cap;
448    u_int32_t hid;
449    int err = 0;
450    unsigned long d_flags;
451
452    dprintk("%s()\n", __FUNCTION__);
453    CRYPTO_DRIVER_LOCK();
454
455    if (crypto_drivers == NULL) {
456        err = EINVAL;
457        goto done;
458    }
459
460    /* Determine two IDs. */
461    hid = CRYPTO_SESID2HID(sid);
462
463    if (hid >= crypto_drivers_num) {
464        dprintk("%s - INVALID DRIVER NUM %d\n", __FUNCTION__, hid);
465        err = ENOENT;
466        goto done;
467    }
468    cap = &crypto_drivers[hid];
469
470    if (cap->cc_dev) {
471        CRYPTO_DRIVER_UNLOCK();
472        /* Call the driver cleanup routine, if available, unlocked. */
473        err = CRYPTODEV_FREESESSION(cap->cc_dev, sid);
474        CRYPTO_DRIVER_LOCK();
475    }
476
477    if (cap->cc_sessions)
478        cap->cc_sessions--;
479
480    if (cap->cc_flags & CRYPTOCAP_F_CLEANUP)
481        crypto_remove(cap);
482
483done:
484    CRYPTO_DRIVER_UNLOCK();
485    return err;
486}
487
488/*
489 * Return an unused driver id. Used by drivers prior to registering
490 * support for the algorithms they handle.
491 */
492int32_t
493crypto_get_driverid(device_t dev, int flags)
494{
495    struct cryptocap *newdrv;
496    int i;
497    unsigned long d_flags;
498
499    if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
500        printf("%s: no flags specified when registering driver\n",
501            device_get_nameunit(dev));
502        return -1;
503    }
504
505    CRYPTO_DRIVER_LOCK();
506
507    for (i = 0; i < crypto_drivers_num; i++) {
508        if (crypto_drivers[i].cc_dev == NULL &&
509            (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP) == 0) {
510            break;
511        }
512    }
513
514    /* Out of entries, allocate some more. */
515    if (i == crypto_drivers_num) {
516        /* Be careful about wrap-around. */
517        if (2 * crypto_drivers_num <= crypto_drivers_num) {
518            CRYPTO_DRIVER_UNLOCK();
519            printk("crypto: driver count wraparound!\n");
520            return -1;
521        }
522
523        newdrv = kmalloc(2 * crypto_drivers_num * sizeof(struct cryptocap),
524                GFP_KERNEL);
525        if (newdrv == NULL) {
526            CRYPTO_DRIVER_UNLOCK();
527            printk("crypto: no space to expand driver table!\n");
528            return -1;
529        }
530
531        memcpy(newdrv, crypto_drivers,
532                crypto_drivers_num * sizeof(struct cryptocap));
533        memset(&newdrv[crypto_drivers_num], 0,
534                crypto_drivers_num * sizeof(struct cryptocap));
535
536        crypto_drivers_num *= 2;
537
538        kfree(crypto_drivers);
539        crypto_drivers = newdrv;
540    }
541
542    /* NB: state is zero'd on free */
543    crypto_drivers[i].cc_sessions = 1; /* Mark */
544    crypto_drivers[i].cc_dev = dev;
545    crypto_drivers[i].cc_flags = flags;
546    if (bootverbose)
547        printf("crypto: assign %s driver id %u, flags %u\n",
548            device_get_nameunit(dev), i, flags);
549
550    CRYPTO_DRIVER_UNLOCK();
551
552    return i;
553}
554
555/*
556 * Lookup a driver by name. We match against the full device
557 * name and unit, and against just the name. The latter gives
558 * us a simple widlcarding by device name. On success return the
559 * driver/hardware identifier; otherwise return -1.
560 */
561int
562crypto_find_driver(const char *match)
563{
564    int i, len = strlen(match);
565    unsigned long d_flags;
566
567    CRYPTO_DRIVER_LOCK();
568    for (i = 0; i < crypto_drivers_num; i++) {
569        device_t dev = crypto_drivers[i].cc_dev;
570        if (dev == NULL ||
571            (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP))
572            continue;
573        if (strncmp(match, device_get_nameunit(dev), len) == 0 ||
574            strncmp(match, device_get_name(dev), len) == 0)
575            break;
576    }
577    CRYPTO_DRIVER_UNLOCK();
578    return i < crypto_drivers_num ? i : -1;
579}
580
581/*
582 * Return the device_t for the specified driver or NULL
583 * if the driver identifier is invalid.
584 */
585device_t
586crypto_find_device_byhid(int hid)
587{
588    struct cryptocap *cap = crypto_checkdriver(hid);
589    return cap != NULL ? cap->cc_dev : NULL;
590}
591
592/*
593 * Return the device/driver capabilities.
594 */
595int
596crypto_getcaps(int hid)
597{
598    struct cryptocap *cap = crypto_checkdriver(hid);
599    return cap != NULL ? cap->cc_flags : 0;
600}
601
602/*
603 * Register support for a key-related algorithm. This routine
604 * is called once for each algorithm supported a driver.
605 */
606int
607crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags)
608{
609    struct cryptocap *cap;
610    int err;
611    unsigned long d_flags;
612
613    dprintk("%s()\n", __FUNCTION__);
614    CRYPTO_DRIVER_LOCK();
615
616    cap = crypto_checkdriver(driverid);
617    if (cap != NULL &&
618        (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
619        /*
620         * XXX Do some performance testing to determine placing.
621         * XXX We probably need an auxiliary data structure that
622         * XXX describes relative performances.
623         */
624
625        cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
626        if (bootverbose)
627            printf("crypto: %s registers key alg %u flags %u\n"
628                , device_get_nameunit(cap->cc_dev)
629                , kalg
630                , flags
631            );
632        err = 0;
633    } else
634        err = EINVAL;
635
636    CRYPTO_DRIVER_UNLOCK();
637    return err;
638}
639
640/*
641 * Register support for a non-key-related algorithm. This routine
642 * is called once for each such algorithm supported by a driver.
643 */
644int
645crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
646    u_int32_t flags)
647{
648    struct cryptocap *cap;
649    int err;
650    unsigned long d_flags;
651
652    dprintk("%s(id=0x%x, alg=%d, maxoplen=%d, flags=0x%x)\n", __FUNCTION__,
653            driverid, alg, maxoplen, flags);
654
655    CRYPTO_DRIVER_LOCK();
656
657    cap = crypto_checkdriver(driverid);
658    /* NB: algorithms are in the range [1..max] */
659    if (cap != NULL &&
660        (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX)) {
661        /*
662         * XXX Do some performance testing to determine placing.
663         * XXX We probably need an auxiliary data structure that
664         * XXX describes relative performances.
665         */
666
667        cap->cc_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
668        cap->cc_max_op_len[alg] = maxoplen;
669        if (bootverbose)
670            printf("crypto: %s registers alg %u flags %u maxoplen %u\n"
671                , device_get_nameunit(cap->cc_dev)
672                , alg
673                , flags
674                , maxoplen
675            );
676        cap->cc_sessions = 0; /* Unmark */
677        err = 0;
678    } else
679        err = EINVAL;
680
681    CRYPTO_DRIVER_UNLOCK();
682    return err;
683}
684
685static void
686driver_finis(struct cryptocap *cap)
687{
688    u_int32_t ses, kops;
689
690    CRYPTO_DRIVER_ASSERT();
691
692    ses = cap->cc_sessions;
693    kops = cap->cc_koperations;
694    bzero(cap, sizeof(*cap));
695    if (ses != 0 || kops != 0) {
696        /*
697         * If there are pending sessions,
698         * just mark as invalid.
699         */
700        cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
701        cap->cc_sessions = ses;
702        cap->cc_koperations = kops;
703    }
704}
705
706/*
707 * Unregister a crypto driver. If there are pending sessions using it,
708 * leave enough information around so that subsequent calls using those
709 * sessions will correctly detect the driver has been unregistered and
710 * reroute requests.
711 */
712int
713crypto_unregister(u_int32_t driverid, int alg)
714{
715    struct cryptocap *cap;
716    int i, err;
717    unsigned long d_flags;
718
719    dprintk("%s()\n", __FUNCTION__);
720    CRYPTO_DRIVER_LOCK();
721
722    cap = crypto_checkdriver(driverid);
723    if (cap != NULL &&
724        (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) &&
725        cap->cc_alg[alg] != 0) {
726        cap->cc_alg[alg] = 0;
727        cap->cc_max_op_len[alg] = 0;
728
729        /* Was this the last algorithm ? */
730        for (i = 1; i <= CRYPTO_ALGORITHM_MAX; i++)
731            if (cap->cc_alg[i] != 0)
732                break;
733
734        if (i == CRYPTO_ALGORITHM_MAX + 1)
735            driver_finis(cap);
736        err = 0;
737    } else
738        err = EINVAL;
739    CRYPTO_DRIVER_UNLOCK();
740    return err;
741}
742
743/*
744 * Unregister all algorithms associated with a crypto driver.
745 * If there are pending sessions using it, leave enough information
746 * around so that subsequent calls using those sessions will
747 * correctly detect the driver has been unregistered and reroute
748 * requests.
749 */
750int
751crypto_unregister_all(u_int32_t driverid)
752{
753    struct cryptocap *cap;
754    int err;
755    unsigned long d_flags;
756
757    dprintk("%s()\n", __FUNCTION__);
758    CRYPTO_DRIVER_LOCK();
759    cap = crypto_checkdriver(driverid);
760    if (cap != NULL) {
761        driver_finis(cap);
762        err = 0;
763    } else
764        err = EINVAL;
765    CRYPTO_DRIVER_UNLOCK();
766
767    return err;
768}
769
770/*
771 * Clear blockage on a driver. The what parameter indicates whether
772 * the driver is now ready for cryptop's and/or cryptokop's.
773 */
774int
775crypto_unblock(u_int32_t driverid, int what)
776{
777    struct cryptocap *cap;
778    int err;
779    unsigned long q_flags;
780
781    CRYPTO_Q_LOCK();
782    cap = crypto_checkdriver(driverid);
783    if (cap != NULL) {
784        if (what & CRYPTO_SYMQ) {
785            cap->cc_qblocked = 0;
786            cap->cc_unqblocked = 0;
787            crypto_all_qblocked = 0;
788        }
789        if (what & CRYPTO_ASYMQ) {
790            cap->cc_kqblocked = 0;
791            cap->cc_unkqblocked = 0;
792            crypto_all_kqblocked = 0;
793        }
794        if (crp_sleep)
795            wake_up_interruptible(&cryptoproc_wait);
796        err = 0;
797    } else
798        err = EINVAL;
799    CRYPTO_Q_UNLOCK(); //DAVIDM should this be a driver lock
800
801    return err;
802}
803
804/*
805 * Add a crypto request to a queue, to be processed by the kernel thread.
806 */
807int
808crypto_dispatch(struct cryptop *crp)
809{
810    struct cryptocap *cap;
811    int result = -1;
812    unsigned long q_flags;
813
814    dprintk("%s()\n", __FUNCTION__);
815
816    cryptostats.cs_ops++;
817
818    CRYPTO_Q_LOCK();
819    if (crypto_q_cnt >= crypto_q_max) {
820        CRYPTO_Q_UNLOCK();
821        cryptostats.cs_drops++;
822        return ENOMEM;
823    }
824    crypto_q_cnt++;
825
826    /* make sure we are starting a fresh run on this crp. */
827    crp->crp_flags &= ~CRYPTO_F_DONE;
828    crp->crp_etype = 0;
829
830    /*
831     * Caller marked the request to be processed immediately; dispatch
832     * it directly to the driver unless the driver is currently blocked.
833     */
834    if ((crp->crp_flags & CRYPTO_F_BATCH) == 0) {
835        int hid = CRYPTO_SESID2HID(crp->crp_sid);
836        cap = crypto_checkdriver(hid);
837        /* Driver cannot disappear when there is an active session. */
838        KASSERT(cap != NULL, ("%s: Driver disappeared.", __func__));
839        if (!cap->cc_qblocked) {
840            crypto_all_qblocked = 0;
841            crypto_drivers[hid].cc_unqblocked = 1;
842            CRYPTO_Q_UNLOCK();
843            result = crypto_invoke(cap, crp, 0);
844            CRYPTO_Q_LOCK();
845            if (result == ERESTART)
846                if (crypto_drivers[hid].cc_unqblocked)
847                    crypto_drivers[hid].cc_qblocked = 1;
848            crypto_drivers[hid].cc_unqblocked = 0;
849        }
850    }
851    if (result == ERESTART) {
852        /*
853         * The driver ran out of resources, mark the
854         * driver ``blocked'' for cryptop's and put
855         * the request back in the queue. It would
856         * best to put the request back where we got
857         * it but that's hard so for now we put it
858         * at the front. This should be ok; putting
859         * it at the end does not work.
860         */
861        list_add(&crp->crp_next, &crp_q);
862        cryptostats.cs_blocks++;
863        result = 0;
864    } else if (result == -1) {
865        TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
866        result = 0;
867    }
868    if (crp_sleep)
869        wake_up_interruptible(&cryptoproc_wait);
870    CRYPTO_Q_UNLOCK();
871    return result;
872}
873
874/*
875 * Add an asymetric crypto request to a queue,
876 * to be processed by the kernel thread.
877 */
878int
879crypto_kdispatch(struct cryptkop *krp)
880{
881    int error;
882    unsigned long q_flags;
883
884    cryptostats.cs_kops++;
885
886    error = crypto_kinvoke(krp, krp->krp_crid);
887    if (error == ERESTART) {
888        CRYPTO_Q_LOCK();
889        TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
890        if (crp_sleep)
891            wake_up_interruptible(&cryptoproc_wait);
892        CRYPTO_Q_UNLOCK();
893        error = 0;
894    }
895    return error;
896}
897
898/*
899 * Verify a driver is suitable for the specified operation.
900 */
901static __inline int
902kdriver_suitable(const struct cryptocap *cap, const struct cryptkop *krp)
903{
904    return (cap->cc_kalg[krp->krp_op] & CRYPTO_ALG_FLAG_SUPPORTED) != 0;
905}
906
907/*
908 * Select a driver for an asym operation. The driver must
909 * support the necessary algorithm. The caller can constrain
910 * which device is selected with the flags parameter. The
911 * algorithm we use here is pretty stupid; just use the first
912 * driver that supports the algorithms we need. If there are
913 * multiple suitable drivers we choose the driver with the
914 * fewest active operations. We prefer hardware-backed
915 * drivers to software ones when either may be used.
916 */
917static struct cryptocap *
918crypto_select_kdriver(const struct cryptkop *krp, int flags)
919{
920    struct cryptocap *cap, *best, *blocked;
921    int match, hid;
922
923    CRYPTO_DRIVER_ASSERT();
924
925    /*
926     * Look first for hardware crypto devices if permitted.
927     */
928    if (flags & CRYPTOCAP_F_HARDWARE)
929        match = CRYPTOCAP_F_HARDWARE;
930    else
931        match = CRYPTOCAP_F_SOFTWARE;
932    best = NULL;
933    blocked = NULL;
934again:
935    for (hid = 0; hid < crypto_drivers_num; hid++) {
936        cap = &crypto_drivers[hid];
937        /*
938         * If it's not initialized, is in the process of
939         * going away, or is not appropriate (hardware
940         * or software based on match), then skip.
941         */
942        if (cap->cc_dev == NULL ||
943            (cap->cc_flags & CRYPTOCAP_F_CLEANUP) ||
944            (cap->cc_flags & match) == 0)
945            continue;
946
947        /* verify all the algorithms are supported. */
948        if (kdriver_suitable(cap, krp)) {
949            if (best == NULL ||
950                cap->cc_koperations < best->cc_koperations)
951                best = cap;
952        }
953    }
954    if (best != NULL)
955        return best;
956    if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
957        /* sort of an Algol 68-style for loop */
958        match = CRYPTOCAP_F_SOFTWARE;
959        goto again;
960    }
961    return best;
962}
963
964/*
965 * Dispatch an assymetric crypto request.
966 */
967static int
968crypto_kinvoke(struct cryptkop *krp, int crid)
969{
970    struct cryptocap *cap = NULL;
971    int error;
972    unsigned long d_flags;
973
974    KASSERT(krp != NULL, ("%s: krp == NULL", __func__));
975    KASSERT(krp->krp_callback != NULL,
976        ("%s: krp->crp_callback == NULL", __func__));
977
978    CRYPTO_DRIVER_LOCK();
979    if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
980        cap = crypto_checkdriver(crid);
981        if (cap != NULL) {
982            /*
983             * Driver present, it must support the necessary
984             * algorithm and, if s/w drivers are excluded,
985             * it must be registered as hardware-backed.
986             */
987            if (!kdriver_suitable(cap, krp) ||
988                (!crypto_devallowsoft &&
989                 (cap->cc_flags & CRYPTOCAP_F_HARDWARE) == 0))
990                cap = NULL;
991        }
992    } else {
993        /*
994         * No requested driver; select based on crid flags.
995         */
996        if (!crypto_devallowsoft) /* NB: disallow s/w drivers */
997            crid &= ~CRYPTOCAP_F_SOFTWARE;
998        cap = crypto_select_kdriver(krp, crid);
999    }
1000    if (cap != NULL && !cap->cc_kqblocked) {
1001        krp->krp_hid = cap - crypto_drivers;
1002        cap->cc_koperations++;
1003        CRYPTO_DRIVER_UNLOCK();
1004        error = CRYPTODEV_KPROCESS(cap->cc_dev, krp, 0);
1005        CRYPTO_DRIVER_LOCK();
1006        if (error == ERESTART) {
1007            cap->cc_koperations--;
1008            CRYPTO_DRIVER_UNLOCK();
1009            return (error);
1010        }
1011        /* return the actual device used */
1012        krp->krp_crid = krp->krp_hid;
1013    } else {
1014        /*
1015         * NB: cap is !NULL if device is blocked; in
1016         * that case return ERESTART so the operation
1017         * is resubmitted if possible.
1018         */
1019        error = (cap == NULL) ? ENODEV : ERESTART;
1020    }
1021    CRYPTO_DRIVER_UNLOCK();
1022
1023    if (error) {
1024        krp->krp_status = error;
1025        crypto_kdone(krp);
1026    }
1027    return 0;
1028}
1029
1030
1031/*
1032 * Dispatch a crypto request to the appropriate crypto devices.
1033 */
1034static int
1035crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1036{
1037    KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1038    KASSERT(crp->crp_callback != NULL,
1039        ("%s: crp->crp_callback == NULL", __func__));
1040    KASSERT(crp->crp_desc != NULL, ("%s: crp->crp_desc == NULL", __func__));
1041
1042    dprintk("%s()\n", __FUNCTION__);
1043
1044#ifdef CRYPTO_TIMING
1045    if (crypto_timing)
1046        crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
1047#endif
1048    if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1049        struct cryptodesc *crd;
1050        u_int64_t nid;
1051
1052        /*
1053         * Driver has unregistered; migrate the session and return
1054         * an error to the caller so they'll resubmit the op.
1055         *
1056         * XXX: What if there are more already queued requests for this
1057         * session?
1058         */
1059        crypto_freesession(crp->crp_sid);
1060
1061        for (crd = crp->crp_desc; crd->crd_next; crd = crd->crd_next)
1062            crd->CRD_INI.cri_next = &(crd->crd_next->CRD_INI);
1063
1064        /* XXX propagate flags from initial session? */
1065        if (crypto_newsession(&nid, &(crp->crp_desc->CRD_INI),
1066            CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1067            crp->crp_sid = nid;
1068
1069        crp->crp_etype = EAGAIN;
1070        crypto_done(crp);
1071        return 0;
1072    } else {
1073        /*
1074         * Invoke the driver to process the request.
1075         */
1076        return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1077    }
1078}
1079
1080/*
1081 * Release a set of crypto descriptors.
1082 */
1083void
1084crypto_freereq(struct cryptop *crp)
1085{
1086    struct cryptodesc *crd;
1087
1088    if (crp == NULL)
1089        return;
1090
1091#ifdef DIAGNOSTIC
1092    {
1093        struct cryptop *crp2;
1094        unsigned long q_flags;
1095
1096        CRYPTO_Q_LOCK();
1097        TAILQ_FOREACH(crp2, &crp_q, crp_next) {
1098            KASSERT(crp2 != crp,
1099                ("Freeing cryptop from the crypto queue (%p).",
1100                crp));
1101        }
1102        CRYPTO_Q_UNLOCK();
1103        CRYPTO_RETQ_LOCK();
1104        TAILQ_FOREACH(crp2, &crp_ret_q, crp_next) {
1105            KASSERT(crp2 != crp,
1106                ("Freeing cryptop from the return queue (%p).",
1107                crp));
1108        }
1109        CRYPTO_RETQ_UNLOCK();
1110    }
1111#endif
1112
1113    while ((crd = crp->crp_desc) != NULL) {
1114        crp->crp_desc = crd->crd_next;
1115        kmem_cache_free(cryptodesc_zone, crd);
1116    }
1117    kmem_cache_free(cryptop_zone, crp);
1118}
1119
1120/*
1121 * Acquire a set of crypto descriptors.
1122 */
1123struct cryptop *
1124crypto_getreq(int num)
1125{
1126    struct cryptodesc *crd;
1127    struct cryptop *crp;
1128
1129    crp = kmem_cache_alloc(cryptop_zone, SLAB_ATOMIC);
1130    if (crp != NULL) {
1131        memset(crp, 0, sizeof(*crp));
1132        INIT_LIST_HEAD(&crp->crp_next);
1133        init_waitqueue_head(&crp->crp_waitq);
1134        while (num--) {
1135            crd = kmem_cache_alloc(cryptodesc_zone, SLAB_ATOMIC);
1136            if (crd == NULL) {
1137                crypto_freereq(crp);
1138                return NULL;
1139            }
1140            memset(crd, 0, sizeof(*crd));
1141            crd->crd_next = crp->crp_desc;
1142            crp->crp_desc = crd;
1143        }
1144    }
1145    return crp;
1146}
1147
1148/*
1149 * Invoke the callback on behalf of the driver.
1150 */
1151void
1152crypto_done(struct cryptop *crp)
1153{
1154    unsigned long q_flags;
1155
1156    dprintk("%s()\n", __FUNCTION__);
1157    if ((crp->crp_flags & CRYPTO_F_DONE) == 0) {
1158        crp->crp_flags |= CRYPTO_F_DONE;
1159        CRYPTO_Q_LOCK();
1160        crypto_q_cnt--;
1161        CRYPTO_Q_UNLOCK();
1162    } else
1163        printk("crypto: crypto_done op already done, flags 0x%x",
1164                crp->crp_flags);
1165    if (crp->crp_etype != 0)
1166        cryptostats.cs_errs++;
1167    /*
1168     * CBIMM means unconditionally do the callback immediately;
1169     * CBIFSYNC means do the callback immediately only if the
1170     * operation was done synchronously. Both are used to avoid
1171     * doing extraneous context switches; the latter is mostly
1172     * used with the software crypto driver.
1173     */
1174    if ((crp->crp_flags & CRYPTO_F_CBIMM) ||
1175        ((crp->crp_flags & CRYPTO_F_CBIFSYNC) &&
1176         (CRYPTO_SESID2CAPS(crp->crp_sid) & CRYPTOCAP_F_SYNC))) {
1177        /*
1178         * Do the callback directly. This is ok when the
1179         * callback routine does very little (e.g. the
1180         * /dev/crypto callback method just does a wakeup).
1181         */
1182        crp->crp_callback(crp);
1183    } else {
1184        unsigned long r_flags;
1185        /*
1186         * Normal case; queue the callback for the thread.
1187         */
1188        CRYPTO_RETQ_LOCK();
1189        if (CRYPTO_RETQ_EMPTY())
1190            wake_up_interruptible(&cryptoretproc_wait);/* shared wait channel */
1191        TAILQ_INSERT_TAIL(&crp_ret_q, crp, crp_next);
1192        CRYPTO_RETQ_UNLOCK();
1193    }
1194}
1195
1196/*
1197 * Invoke the callback on behalf of the driver.
1198 */
1199void
1200crypto_kdone(struct cryptkop *krp)
1201{
1202    struct cryptocap *cap;
1203    unsigned long d_flags;
1204
1205    if ((krp->krp_flags & CRYPTO_KF_DONE) != 0)
1206        printk("crypto: crypto_kdone op already done, flags 0x%x",
1207                krp->krp_flags);
1208    krp->krp_flags |= CRYPTO_KF_DONE;
1209    if (krp->krp_status != 0)
1210        cryptostats.cs_kerrs++;
1211
1212    CRYPTO_DRIVER_LOCK();
1213    /* XXX: What if driver is loaded in the meantime? */
1214    if (krp->krp_hid < crypto_drivers_num) {
1215        cap = &crypto_drivers[krp->krp_hid];
1216        cap->cc_koperations--;
1217        KASSERT(cap->cc_koperations >= 0, ("cc_koperations < 0"));
1218        if (cap->cc_flags & CRYPTOCAP_F_CLEANUP)
1219            crypto_remove(cap);
1220    }
1221    CRYPTO_DRIVER_UNLOCK();
1222
1223    /*
1224     * CBIMM means unconditionally do the callback immediately;
1225     * This is used to avoid doing extraneous context switches
1226     */
1227    if ((krp->krp_flags & CRYPTO_KF_CBIMM)) {
1228        /*
1229         * Do the callback directly. This is ok when the
1230         * callback routine does very little (e.g. the
1231         * /dev/crypto callback method just does a wakeup).
1232         */
1233        krp->krp_callback(krp);
1234    } else {
1235        unsigned long r_flags;
1236        /*
1237         * Normal case; queue the callback for the thread.
1238         */
1239        CRYPTO_RETQ_LOCK();
1240        if (CRYPTO_RETQ_EMPTY())
1241            wake_up_interruptible(&cryptoretproc_wait);/* shared wait channel */
1242        TAILQ_INSERT_TAIL(&crp_ret_kq, krp, krp_next);
1243        CRYPTO_RETQ_UNLOCK();
1244    }
1245}
1246
1247int
1248crypto_getfeat(int *featp)
1249{
1250    int hid, kalg, feat = 0;
1251    unsigned long d_flags;
1252
1253    CRYPTO_DRIVER_LOCK();
1254    for (hid = 0; hid < crypto_drivers_num; hid++) {
1255        const struct cryptocap *cap = &crypto_drivers[hid];
1256
1257        if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1258            !crypto_devallowsoft) {
1259            continue;
1260        }
1261        for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1262            if (cap->cc_kalg[kalg] & CRYPTO_ALG_FLAG_SUPPORTED)
1263                feat |= 1 << kalg;
1264    }
1265    CRYPTO_DRIVER_UNLOCK();
1266    *featp = feat;
1267    return (0);
1268}
1269
1270/*
1271 * Crypto thread, dispatches crypto requests.
1272 */
1273static int
1274crypto_proc(void *arg)
1275{
1276    struct cryptop *crp, *submit;
1277    struct cryptkop *krp, *krpp;
1278    struct cryptocap *cap;
1279    u_int32_t hid;
1280    int result, hint;
1281    unsigned long q_flags;
1282    int loopcount = 0;
1283
1284    ocf_daemonize("crypto");
1285
1286    CRYPTO_Q_LOCK();
1287    for (;;) {
1288        /*
1289         * we need to make sure we don't get into a busy loop with nothing
1290         * to do, the two crypto_all_*blocked vars help us find out when
1291         * we are all full and can do nothing on any driver or Q. If so we
1292         * wait for an unblock.
1293         */
1294        crypto_all_qblocked = !list_empty(&crp_q);
1295
1296        /*
1297         * Find the first element in the queue that can be
1298         * processed and look-ahead to see if multiple ops
1299         * are ready for the same driver.
1300         */
1301        submit = NULL;
1302        hint = 0;
1303        list_for_each_entry(crp, &crp_q, crp_next) {
1304            hid = CRYPTO_SESID2HID(crp->crp_sid);
1305            cap = crypto_checkdriver(hid);
1306            /*
1307             * Driver cannot disappear when there is an active
1308             * session.
1309             */
1310            KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1311                __func__, __LINE__));
1312            if (cap == NULL || cap->cc_dev == NULL) {
1313                /* Op needs to be migrated, process it. */
1314                if (submit == NULL)
1315                    submit = crp;
1316                break;
1317            }
1318            if (!cap->cc_qblocked) {
1319                if (submit != NULL) {
1320                    /*
1321                     * We stop on finding another op,
1322                     * regardless whether its for the same
1323                     * driver or not. We could keep
1324                     * searching the queue but it might be
1325                     * better to just use a per-driver
1326                     * queue instead.
1327                     */
1328                    if (CRYPTO_SESID2HID(submit->crp_sid) == hid)
1329                        hint = CRYPTO_HINT_MORE;
1330                    break;
1331                } else {
1332                    submit = crp;
1333                    if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
1334                        break;
1335                    /* keep scanning for more are q'd */
1336                }
1337            }
1338        }
1339        if (submit != NULL) {
1340            hid = CRYPTO_SESID2HID(submit->crp_sid);
1341            crypto_all_qblocked = 0;
1342            list_del(&submit->crp_next);
1343            crypto_drivers[hid].cc_unqblocked = 1;
1344            cap = crypto_checkdriver(hid);
1345            CRYPTO_Q_UNLOCK();
1346            KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1347                __func__, __LINE__));
1348            result = crypto_invoke(cap, submit, hint);
1349            CRYPTO_Q_LOCK();
1350            if (result == ERESTART) {
1351                /*
1352                 * The driver ran out of resources, mark the
1353                 * driver ``blocked'' for cryptop's and put
1354                 * the request back in the queue. It would
1355                 * best to put the request back where we got
1356                 * it but that's hard so for now we put it
1357                 * at the front. This should be ok; putting
1358                 * it at the end does not work.
1359                 */
1360                /* XXX validate sid again? */
1361                list_add(&submit->crp_next, &crp_q);
1362                cryptostats.cs_blocks++;
1363                if (crypto_drivers[hid].cc_unqblocked)
1364                    crypto_drivers[hid].cc_qblocked=0;
1365                crypto_drivers[hid].cc_unqblocked=0;
1366            }
1367            crypto_drivers[hid].cc_unqblocked = 0;
1368        }
1369
1370        crypto_all_kqblocked = !list_empty(&crp_kq);
1371
1372        /* As above, but for key ops */
1373        krp = NULL;
1374        list_for_each_entry(krpp, &crp_kq, krp_next) {
1375            cap = crypto_checkdriver(krpp->krp_hid);
1376            if (cap == NULL || cap->cc_dev == NULL) {
1377                /*
1378                 * Operation needs to be migrated, invalidate
1379                 * the assigned device so it will reselect a
1380                 * new one below. Propagate the original
1381                 * crid selection flags if supplied.
1382                 */
1383                krp->krp_hid = krp->krp_crid &
1384                    (CRYPTOCAP_F_SOFTWARE|CRYPTOCAP_F_HARDWARE);
1385                if (krp->krp_hid == 0)
1386                    krp->krp_hid =
1387                    CRYPTOCAP_F_SOFTWARE|CRYPTOCAP_F_HARDWARE;
1388                break;
1389            }
1390            if (!cap->cc_kqblocked) {
1391                krp = krpp;
1392                break;
1393            }
1394        }
1395        if (krp != NULL) {
1396            crypto_all_kqblocked = 0;
1397            list_del(&krp->krp_next);
1398            crypto_drivers[krp->krp_hid].cc_kqblocked = 1;
1399            CRYPTO_Q_UNLOCK();
1400            result = crypto_kinvoke(krp, krp->krp_hid);
1401            CRYPTO_Q_LOCK();
1402            if (result == ERESTART) {
1403                /*
1404                 * The driver ran out of resources, mark the
1405                 * driver ``blocked'' for cryptkop's and put
1406                 * the request back in the queue. It would
1407                 * best to put the request back where we got
1408                 * it but that's hard so for now we put it
1409                 * at the front. This should be ok; putting
1410                 * it at the end does not work.
1411                 */
1412                /* XXX validate sid again? */
1413                list_add(&krp->krp_next, &crp_kq);
1414                cryptostats.cs_kblocks++;
1415            } else
1416                crypto_drivers[krp->krp_hid].cc_kqblocked = 0;
1417        }
1418
1419        if (submit == NULL && krp == NULL) {
1420            /*
1421             * Nothing more to be processed. Sleep until we're
1422             * woken because there are more ops to process.
1423             * This happens either by submission or by a driver
1424             * becoming unblocked and notifying us through
1425             * crypto_unblock. Note that when we wakeup we
1426             * start processing each queue again from the
1427             * front. It's not clear that it's important to
1428             * preserve this ordering since ops may finish
1429             * out of order if dispatched to different devices
1430             * and some become blocked while others do not.
1431             */
1432            dprintk("%s - sleeping (qe=%d qb=%d kqe=%d kqb=%d)\n",
1433                    __FUNCTION__,
1434                    list_empty(&crp_q), crypto_all_qblocked,
1435                    list_empty(&crp_kq), crypto_all_kqblocked);
1436            loopcount = 0;
1437            CRYPTO_Q_UNLOCK();
1438            crp_sleep = 1;
1439            wait_event_interruptible(cryptoproc_wait,
1440                    !(list_empty(&crp_q) || crypto_all_qblocked) ||
1441                    !(list_empty(&crp_kq) || crypto_all_kqblocked) ||
1442                    cryptoproc == (pid_t) -1);
1443            crp_sleep = 0;
1444            if (signal_pending (current)) {
1445#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
1446                spin_lock_irq(&current->sigmask_lock);
1447#endif
1448                flush_signals(current);
1449#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
1450                spin_unlock_irq(&current->sigmask_lock);
1451#endif
1452            }
1453            CRYPTO_Q_LOCK();
1454            dprintk("%s - awake\n", __FUNCTION__);
1455            if (cryptoproc == (pid_t) -1)
1456                break;
1457            cryptostats.cs_intrs++;
1458        } else if (loopcount > crypto_max_loopcount) {
1459            /*
1460             * Give other processes a chance to run if we've
1461             * been using the CPU exclusively for a while.
1462             */
1463            loopcount = 0;
1464            schedule();
1465        }
1466        loopcount++;
1467    }
1468    CRYPTO_Q_UNLOCK();
1469    complete_and_exit(&cryptoproc_exited, 0);
1470}
1471
1472/*
1473 * Crypto returns thread, does callbacks for processed crypto requests.
1474 * Callbacks are done here, rather than in the crypto drivers, because
1475 * callbacks typically are expensive and would slow interrupt handling.
1476 */
1477static int
1478crypto_ret_proc(void *arg)
1479{
1480    struct cryptop *crpt;
1481    struct cryptkop *krpt;
1482    unsigned long r_flags;
1483
1484    ocf_daemonize("crypto_ret");
1485
1486    CRYPTO_RETQ_LOCK();
1487    for (;;) {
1488        /* Harvest return q's for completed ops */
1489        crpt = NULL;
1490        if (!list_empty(&crp_ret_q))
1491            crpt = list_entry(crp_ret_q.next, typeof(*crpt), crp_next);
1492        if (crpt != NULL)
1493            list_del(&crpt->crp_next);
1494
1495        krpt = NULL;
1496        if (!list_empty(&crp_ret_kq))
1497            krpt = list_entry(crp_ret_kq.next, typeof(*krpt), krp_next);
1498        if (krpt != NULL)
1499            list_del(&krpt->krp_next);
1500
1501        if (crpt != NULL || krpt != NULL) {
1502            CRYPTO_RETQ_UNLOCK();
1503            /*
1504             * Run callbacks unlocked.
1505             */
1506            if (crpt != NULL)
1507                crpt->crp_callback(crpt);
1508            if (krpt != NULL)
1509                krpt->krp_callback(krpt);
1510            CRYPTO_RETQ_LOCK();
1511        } else {
1512            /*
1513             * Nothing more to be processed. Sleep until we're
1514             * woken because there are more returns to process.
1515             */
1516            dprintk("%s - sleeping\n", __FUNCTION__);
1517            CRYPTO_RETQ_UNLOCK();
1518            wait_event_interruptible(cryptoretproc_wait,
1519                    cryptoretproc == (pid_t) -1 ||
1520                    !list_empty(&crp_ret_q) ||
1521                    !list_empty(&crp_ret_kq));
1522            if (signal_pending (current)) {
1523#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
1524                spin_lock_irq(&current->sigmask_lock);
1525#endif
1526                flush_signals(current);
1527#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
1528                spin_unlock_irq(&current->sigmask_lock);
1529#endif
1530            }
1531            CRYPTO_RETQ_LOCK();
1532            dprintk("%s - awake\n", __FUNCTION__);
1533            if (cryptoretproc == (pid_t) -1) {
1534                dprintk("%s - EXITING!\n", __FUNCTION__);
1535                break;
1536            }
1537            cryptostats.cs_rets++;
1538        }
1539    }
1540    CRYPTO_RETQ_UNLOCK();
1541    complete_and_exit(&cryptoretproc_exited, 0);
1542}
1543
1544
1545#if 0 /* should put this into /proc or something */
1546static void
1547db_show_drivers(void)
1548{
1549    int hid;
1550
1551    db_printf("%12s %4s %4s %8s %2s %2s\n"
1552        , "Device"
1553        , "Ses"
1554        , "Kops"
1555        , "Flags"
1556        , "QB"
1557        , "KB"
1558    );
1559    for (hid = 0; hid < crypto_drivers_num; hid++) {
1560        const struct cryptocap *cap = &crypto_drivers[hid];
1561        if (cap->cc_dev == NULL)
1562            continue;
1563        db_printf("%-12s %4u %4u %08x %2u %2u\n"
1564            , device_get_nameunit(cap->cc_dev)
1565            , cap->cc_sessions
1566            , cap->cc_koperations
1567            , cap->cc_flags
1568            , cap->cc_qblocked
1569            , cap->cc_kqblocked
1570        );
1571    }
1572}
1573
1574DB_SHOW_COMMAND(crypto, db_show_crypto)
1575{
1576    struct cryptop *crp;
1577
1578    db_show_drivers();
1579    db_printf("\n");
1580
1581    db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
1582        "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
1583        "Desc", "Callback");
1584    TAILQ_FOREACH(crp, &crp_q, crp_next) {
1585        db_printf("%4u %08x %4u %4u %4u %04x %8p %8p\n"
1586            , (int) CRYPTO_SESID2HID(crp->crp_sid)
1587            , (int) CRYPTO_SESID2CAPS(crp->crp_sid)
1588            , crp->crp_ilen, crp->crp_olen
1589            , crp->crp_etype
1590            , crp->crp_flags
1591            , crp->crp_desc
1592            , crp->crp_callback
1593        );
1594    }
1595    if (!TAILQ_EMPTY(&crp_ret_q)) {
1596        db_printf("\n%4s %4s %4s %8s\n",
1597            "HID", "Etype", "Flags", "Callback");
1598        TAILQ_FOREACH(crp, &crp_ret_q, crp_next) {
1599            db_printf("%4u %4u %04x %8p\n"
1600                , (int) CRYPTO_SESID2HID(crp->crp_sid)
1601                , crp->crp_etype
1602                , crp->crp_flags
1603                , crp->crp_callback
1604            );
1605        }
1606    }
1607}
1608
1609DB_SHOW_COMMAND(kcrypto, db_show_kcrypto)
1610{
1611    struct cryptkop *krp;
1612
1613    db_show_drivers();
1614    db_printf("\n");
1615
1616    db_printf("%4s %5s %4s %4s %8s %4s %8s\n",
1617        "Op", "Status", "#IP", "#OP", "CRID", "HID", "Callback");
1618    TAILQ_FOREACH(krp, &crp_kq, krp_next) {
1619        db_printf("%4u %5u %4u %4u %08x %4u %8p\n"
1620            , krp->krp_op
1621            , krp->krp_status
1622            , krp->krp_iparams, krp->krp_oparams
1623            , krp->krp_crid, krp->krp_hid
1624            , krp->krp_callback
1625        );
1626    }
1627    if (!TAILQ_EMPTY(&crp_ret_q)) {
1628        db_printf("%4s %5s %8s %4s %8s\n",
1629            "Op", "Status", "CRID", "HID", "Callback");
1630        TAILQ_FOREACH(krp, &crp_ret_kq, krp_next) {
1631            db_printf("%4u %5u %08x %4u %8p\n"
1632                , krp->krp_op
1633                , krp->krp_status
1634                , krp->krp_crid, krp->krp_hid
1635                , krp->krp_callback
1636            );
1637        }
1638    }
1639}
1640#endif
1641
1642
1643static int
1644crypto_init(void)
1645{
1646    int error;
1647
1648    dprintk("%s(%p)\n", __FUNCTION__, (void *) crypto_init);
1649
1650    if (crypto_initted)
1651        return 0;
1652    crypto_initted = 1;
1653
1654    spin_lock_init(&crypto_drivers_lock);
1655    spin_lock_init(&crypto_q_lock);
1656    spin_lock_init(&crypto_ret_q_lock);
1657
1658    cryptop_zone = kmem_cache_create("cryptop", sizeof(struct cryptop),
1659                       0, SLAB_HWCACHE_ALIGN, NULL
1660#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
1661                       , NULL
1662#endif
1663                    );
1664
1665    cryptodesc_zone = kmem_cache_create("cryptodesc", sizeof(struct cryptodesc),
1666                       0, SLAB_HWCACHE_ALIGN, NULL
1667#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
1668                       , NULL
1669#endif
1670                    );
1671
1672    if (cryptodesc_zone == NULL || cryptop_zone == NULL) {
1673        printk("crypto: crypto_init cannot setup crypto zones\n");
1674        error = ENOMEM;
1675        goto bad;
1676    }
1677
1678    crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;
1679    crypto_drivers = kmalloc(crypto_drivers_num * sizeof(struct cryptocap),
1680            GFP_KERNEL);
1681    if (crypto_drivers == NULL) {
1682        printk("crypto: crypto_init cannot setup crypto drivers\n");
1683        error = ENOMEM;
1684        goto bad;
1685    }
1686
1687    memset(crypto_drivers, 0, crypto_drivers_num * sizeof(struct cryptocap));
1688
1689    init_completion(&cryptoproc_exited);
1690    init_completion(&cryptoretproc_exited);
1691
1692    cryptoproc = 0; /* to avoid race condition where proc runs first */
1693    cryptoproc = kernel_thread(crypto_proc, NULL, CLONE_FS|CLONE_FILES);
1694    if (cryptoproc < 0) {
1695        error = cryptoproc;
1696        printk("crypto: crypto_init cannot start crypto thread; error %d",
1697            error);
1698        goto bad;
1699    }
1700
1701    cryptoretproc = 0; /* to avoid race condition where proc runs first */
1702    cryptoretproc = kernel_thread(crypto_ret_proc, NULL, CLONE_FS|CLONE_FILES);
1703    if (cryptoretproc < 0) {
1704        error = cryptoretproc;
1705        printk("crypto: crypto_init cannot start cryptoret thread; error %d",
1706                error);
1707        goto bad;
1708    }
1709
1710    return 0;
1711bad:
1712    crypto_exit();
1713    return error;
1714}
1715
1716
1717static void
1718crypto_exit(void)
1719{
1720    pid_t p;
1721    unsigned long d_flags;
1722
1723    dprintk("%s()\n", __FUNCTION__);
1724
1725    /*
1726     * Terminate any crypto threads.
1727     */
1728
1729    CRYPTO_DRIVER_LOCK();
1730    p = cryptoproc;
1731    cryptoproc = (pid_t) -1;
1732    kill_proc(p, SIGTERM, 1);
1733    wake_up_interruptible(&cryptoproc_wait);
1734    CRYPTO_DRIVER_UNLOCK();
1735
1736    wait_for_completion(&cryptoproc_exited);
1737
1738    CRYPTO_DRIVER_LOCK();
1739    p = cryptoretproc;
1740    cryptoretproc = (pid_t) -1;
1741    kill_proc(p, SIGTERM, 1);
1742    wake_up_interruptible(&cryptoretproc_wait);
1743    CRYPTO_DRIVER_UNLOCK();
1744
1745    wait_for_completion(&cryptoretproc_exited);
1746
1747    /* XXX flush queues??? */
1748
1749    /*
1750     * Reclaim dynamically allocated resources.
1751     */
1752    if (crypto_drivers != NULL)
1753        kfree(crypto_drivers);
1754
1755    if (cryptodesc_zone != NULL)
1756        kmem_cache_destroy(cryptodesc_zone);
1757    if (cryptop_zone != NULL)
1758        kmem_cache_destroy(cryptop_zone);
1759}
1760
1761
1762EXPORT_SYMBOL(crypto_newsession);
1763EXPORT_SYMBOL(crypto_freesession);
1764EXPORT_SYMBOL(crypto_get_driverid);
1765EXPORT_SYMBOL(crypto_kregister);
1766EXPORT_SYMBOL(crypto_register);
1767EXPORT_SYMBOL(crypto_unregister);
1768EXPORT_SYMBOL(crypto_unregister_all);
1769EXPORT_SYMBOL(crypto_unblock);
1770EXPORT_SYMBOL(crypto_dispatch);
1771EXPORT_SYMBOL(crypto_kdispatch);
1772EXPORT_SYMBOL(crypto_freereq);
1773EXPORT_SYMBOL(crypto_getreq);
1774EXPORT_SYMBOL(crypto_done);
1775EXPORT_SYMBOL(crypto_kdone);
1776EXPORT_SYMBOL(crypto_getfeat);
1777EXPORT_SYMBOL(crypto_userasymcrypto);
1778EXPORT_SYMBOL(crypto_getcaps);
1779EXPORT_SYMBOL(crypto_find_driver);
1780EXPORT_SYMBOL(crypto_find_device_byhid);
1781
1782module_init(crypto_init);
1783module_exit(crypto_exit);
1784
1785MODULE_LICENSE("BSD");
1786MODULE_AUTHOR("David McCullough <david_mccullough@mcafee.com>");
1787MODULE_DESCRIPTION("OCF (OpenBSD Cryptographic Framework)");
1788

Archive Download this file



interactive