xref: /titanic_52/usr/src/uts/common/crypto/spi/kcf_spi.c (revision d67944fbe3fa0b31893a7116a09b0718eecf6078)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * This file is part of the core Kernel Cryptographic Framework.
28  * It implements the SPI functions exported to cryptographic
29  * providers.
30  */
31 
32 #include <sys/ksynch.h>
33 #include <sys/cmn_err.h>
34 #include <sys/ddi.h>
35 #include <sys/sunddi.h>
36 #include <sys/modctl.h>
37 #include <sys/crypto/common.h>
38 #include <sys/crypto/impl.h>
39 #include <sys/crypto/sched_impl.h>
40 #include <sys/crypto/spi.h>
41 #include <sys/taskq.h>
42 #include <sys/disp.h>
43 #include <sys/kstat.h>
44 #include <sys/policy.h>
45 #include <sys/cpuvar.h>
46 
47 /*
48  * minalloc and maxalloc values to be used for taskq_create().
49  */
50 int crypto_taskq_threads = CRYPTO_TASKQ_THREADS;
51 int crypto_taskq_minalloc = CYRPTO_TASKQ_MIN;
52 int crypto_taskq_maxalloc = CRYPTO_TASKQ_MAX;
53 
54 static void remove_provider(kcf_provider_desc_t *);
55 static void process_logical_providers(crypto_provider_info_t *,
56     kcf_provider_desc_t *);
57 static int init_prov_mechs(crypto_provider_info_t *, kcf_provider_desc_t *);
58 static int kcf_prov_kstat_update(kstat_t *, int);
59 static void undo_register_provider_extra(kcf_provider_desc_t *);
60 static void delete_kstat(kcf_provider_desc_t *);
61 
62 static kcf_prov_stats_t kcf_stats_ks_data_template = {
63 	{ "kcf_ops_total",		KSTAT_DATA_UINT64 },
64 	{ "kcf_ops_passed",		KSTAT_DATA_UINT64 },
65 	{ "kcf_ops_failed",		KSTAT_DATA_UINT64 },
66 	{ "kcf_ops_returned_busy",	KSTAT_DATA_UINT64 }
67 };
68 
69 #define	KCF_SPI_COPY_OPS(src, dst, ops) if ((src)->ops != NULL) \
70 	*((dst)->ops) = *((src)->ops);
71 
72 /*
73  * Copy an ops vector from src to dst. Used during provider registration
74  * to copy the ops vector from the provider info structure to the
75  * provider descriptor maintained by KCF.
76  * Copying the ops vector specified by the provider is needed since the
77  * framework does not require the provider info structure to be
78  * persistent.
79  */
80 static void
81 copy_ops_vector_v1(crypto_ops_t *src_ops, crypto_ops_t *dst_ops)
82 {
83 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_control_ops);
84 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_digest_ops);
85 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_cipher_ops);
86 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_mac_ops);
87 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_sign_ops);
88 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_verify_ops);
89 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_dual_ops);
90 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_dual_cipher_mac_ops);
91 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_random_ops);
92 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_session_ops);
93 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_object_ops);
94 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_key_ops);
95 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_provider_ops);
96 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_ctx_ops);
97 }
98 
99 static void
100 copy_ops_vector_v2(crypto_ops_t *src_ops, crypto_ops_t *dst_ops)
101 {
102 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_mech_ops);
103 }
104 
105 static void
106 copy_ops_vector_v3(crypto_ops_t *src_ops, crypto_ops_t *dst_ops)
107 {
108 	KCF_SPI_COPY_OPS(src_ops, dst_ops, co_nostore_key_ops);
109 }
110 
111 /*
112  * This routine is used to add cryptographic providers to the KEF framework.
113  * Providers pass a crypto_provider_info structure to crypto_register_provider()
114  * and get back a handle.  The crypto_provider_info structure contains a
115  * list of mechanisms supported by the provider and an ops vector containing
116  * provider entry points.  Hardware providers call this routine in their attach
117  * routines.  Software providers call this routine in their _init() routine.
118  */
119 int
120 crypto_register_provider(crypto_provider_info_t *info,
121     crypto_kcf_provider_handle_t *handle)
122 {
123 	int need_verify;
124 	struct modctl *mcp;
125 	char *name;
126 	char ks_name[KSTAT_STRLEN];
127 
128 	kcf_provider_desc_t *prov_desc = NULL;
129 	int ret = CRYPTO_ARGUMENTS_BAD;
130 
131 	if (info->pi_interface_version > CRYPTO_SPI_VERSION_3)
132 		return (CRYPTO_VERSION_MISMATCH);
133 
134 	/*
135 	 * Check provider type, must be software, hardware, or logical.
136 	 */
137 	if (info->pi_provider_type != CRYPTO_HW_PROVIDER &&
138 	    info->pi_provider_type != CRYPTO_SW_PROVIDER &&
139 	    info->pi_provider_type != CRYPTO_LOGICAL_PROVIDER)
140 		return (CRYPTO_ARGUMENTS_BAD);
141 
142 	/*
143 	 * Allocate and initialize a new provider descriptor. We also
144 	 * hold it and release it when done.
145 	 */
146 	prov_desc = kcf_alloc_provider_desc(info);
147 	KCF_PROV_REFHOLD(prov_desc);
148 
149 	prov_desc->pd_prov_type = info->pi_provider_type;
150 
151 	/* provider-private handle, opaque to KCF */
152 	prov_desc->pd_prov_handle = info->pi_provider_handle;
153 
154 	/* copy provider description string */
155 	if (info->pi_provider_description != NULL) {
156 		/*
157 		 * pi_provider_descriptor is a string that can contain
158 		 * up to CRYPTO_PROVIDER_DESCR_MAX_LEN + 1 characters
159 		 * INCLUDING the terminating null character. A bcopy()
160 		 * is necessary here as pd_description should not have
161 		 * a null character. See comments in kcf_alloc_provider_desc()
162 		 * for details on pd_description field.
163 		 */
164 		bcopy(info->pi_provider_description, prov_desc->pd_description,
165 		    min(strlen(info->pi_provider_description),
166 		    CRYPTO_PROVIDER_DESCR_MAX_LEN));
167 	}
168 
169 	if (info->pi_provider_type != CRYPTO_LOGICAL_PROVIDER) {
170 		if (info->pi_ops_vector == NULL) {
171 			goto bail;
172 		}
173 		copy_ops_vector_v1(info->pi_ops_vector,
174 		    prov_desc->pd_ops_vector);
175 		if (info->pi_interface_version >= CRYPTO_SPI_VERSION_2) {
176 			copy_ops_vector_v2(info->pi_ops_vector,
177 			    prov_desc->pd_ops_vector);
178 			prov_desc->pd_flags = info->pi_flags;
179 		}
180 		if (info->pi_interface_version == CRYPTO_SPI_VERSION_3) {
181 			copy_ops_vector_v3(info->pi_ops_vector,
182 			    prov_desc->pd_ops_vector);
183 		}
184 	}
185 
186 	/* object_ops and nostore_key_ops are mutually exclusive */
187 	if (prov_desc->pd_ops_vector->co_object_ops &&
188 	    prov_desc->pd_ops_vector->co_nostore_key_ops) {
189 		goto bail;
190 	}
191 	/*
192 	 * For software providers, copy the module name and module ID.
193 	 * For hardware providers, copy the driver name and instance.
194 	 */
195 	switch (info->pi_provider_type) {
196 	case  CRYPTO_SW_PROVIDER:
197 		if (info->pi_provider_dev.pd_sw == NULL)
198 			goto bail;
199 
200 		if ((mcp = mod_getctl(info->pi_provider_dev.pd_sw)) == NULL)
201 			goto bail;
202 
203 		prov_desc->pd_module_id = mcp->mod_id;
204 		name = mcp->mod_modname;
205 		break;
206 
207 	case CRYPTO_HW_PROVIDER:
208 	case CRYPTO_LOGICAL_PROVIDER:
209 		if (info->pi_provider_dev.pd_hw == NULL)
210 			goto bail;
211 
212 		prov_desc->pd_instance =
213 		    ddi_get_instance(info->pi_provider_dev.pd_hw);
214 		name = (char *)ddi_driver_name(info->pi_provider_dev.pd_hw);
215 		break;
216 	}
217 	if (name == NULL)
218 		goto bail;
219 
220 	prov_desc->pd_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
221 	(void) strcpy(prov_desc->pd_name, name);
222 
223 	if ((prov_desc->pd_mctlp = kcf_get_modctl(info)) == NULL)
224 		goto bail;
225 
226 	/* process the mechanisms supported by the provider */
227 	if ((ret = init_prov_mechs(info, prov_desc)) != CRYPTO_SUCCESS)
228 		goto bail;
229 
230 	/*
231 	 * Add provider to providers tables, also sets the descriptor
232 	 * pd_prov_id field.
233 	 */
234 	if ((ret = kcf_prov_tab_add_provider(prov_desc)) != CRYPTO_SUCCESS) {
235 		undo_register_provider(prov_desc, B_FALSE);
236 		goto bail;
237 	}
238 
239 	if ((need_verify = kcf_need_signature_verification(prov_desc)) == -1) {
240 		undo_register_provider(prov_desc, B_TRUE);
241 		ret = CRYPTO_MODVERIFICATION_FAILED;
242 		goto bail;
243 	}
244 
245 	/*
246 	 * We create a taskq only for a hardware provider. The global
247 	 * software queue is used for software providers. We handle ordering
248 	 * of multi-part requests in the taskq routine. So, it is safe to
249 	 * have multiple threads for the taskq. We pass TASKQ_PREPOPULATE flag
250 	 * to keep some entries cached to improve performance.
251 	 */
252 	if (prov_desc->pd_prov_type == CRYPTO_HW_PROVIDER)
253 		prov_desc->pd_taskq = taskq_create("kcf_taskq",
254 		    crypto_taskq_threads, minclsyspri,
255 		    crypto_taskq_minalloc, crypto_taskq_maxalloc,
256 		    TASKQ_PREPOPULATE);
257 	else
258 		prov_desc->pd_taskq = NULL;
259 
260 	/* no kernel session to logical providers */
261 	if (prov_desc->pd_prov_type != CRYPTO_LOGICAL_PROVIDER) {
262 		/*
263 		 * Open a session for session-oriented providers. This session
264 		 * is used for all kernel consumers. This is fine as a provider
265 		 * is required to support multiple thread access to a session.
266 		 * We can do this only after the taskq has been created as we
267 		 * do a kcf_submit_request() to open the session.
268 		 */
269 		if (KCF_PROV_SESSION_OPS(prov_desc) != NULL) {
270 			kcf_req_params_t params;
271 
272 			KCF_WRAP_SESSION_OPS_PARAMS(&params,
273 			    KCF_OP_SESSION_OPEN, &prov_desc->pd_sid, 0,
274 			    CRYPTO_USER, NULL, 0, prov_desc);
275 			ret = kcf_submit_request(prov_desc, NULL, NULL, &params,
276 			    B_FALSE);
277 
278 			if (ret != CRYPTO_SUCCESS) {
279 				undo_register_provider(prov_desc, B_TRUE);
280 				ret = CRYPTO_FAILED;
281 				goto bail;
282 			}
283 		}
284 	}
285 
286 	if (prov_desc->pd_prov_type != CRYPTO_LOGICAL_PROVIDER) {
287 		/*
288 		 * Create the kstat for this provider. There is a kstat
289 		 * installed for each successfully registered provider.
290 		 * This kstat is deleted, when the provider unregisters.
291 		 */
292 		if (prov_desc->pd_prov_type == CRYPTO_SW_PROVIDER) {
293 			(void) snprintf(ks_name, KSTAT_STRLEN, "%s_%s",
294 			    prov_desc->pd_name, "provider_stats");
295 		} else {
296 			(void) snprintf(ks_name, KSTAT_STRLEN, "%s_%d_%u_%s",
297 			    prov_desc->pd_name, prov_desc->pd_instance,
298 			    prov_desc->pd_prov_id, "provider_stats");
299 		}
300 
301 		prov_desc->pd_kstat = kstat_create("kcf", 0, ks_name, "crypto",
302 		    KSTAT_TYPE_NAMED, sizeof (kcf_prov_stats_t) /
303 		    sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
304 
305 		if (prov_desc->pd_kstat != NULL) {
306 			bcopy(&kcf_stats_ks_data_template,
307 			    &prov_desc->pd_ks_data,
308 			    sizeof (kcf_stats_ks_data_template));
309 			prov_desc->pd_kstat->ks_data = &prov_desc->pd_ks_data;
310 			KCF_PROV_REFHOLD(prov_desc);
311 			prov_desc->pd_kstat->ks_private = prov_desc;
312 			prov_desc->pd_kstat->ks_update = kcf_prov_kstat_update;
313 			kstat_install(prov_desc->pd_kstat);
314 		}
315 	}
316 
317 	if (prov_desc->pd_prov_type == CRYPTO_HW_PROVIDER)
318 		process_logical_providers(info, prov_desc);
319 
320 	if (need_verify == 1) {
321 		/* kcf_verify_signature routine will release this hold */
322 		KCF_PROV_REFHOLD(prov_desc);
323 
324 		if (prov_desc->pd_prov_type == CRYPTO_HW_PROVIDER) {
325 			/*
326 			 * It is not safe to make the door upcall to kcfd from
327 			 * this context since the kcfd thread could reenter
328 			 * devfs. So, we dispatch a taskq job to do the
329 			 * verification and return to the provider.
330 			 */
331 			(void) taskq_dispatch(system_taskq,
332 			    kcf_verify_signature, (void *)prov_desc, TQ_SLEEP);
333 		} else if (prov_desc->pd_prov_type == CRYPTO_SW_PROVIDER) {
334 			kcf_verify_signature(prov_desc);
335 			if (prov_desc->pd_state ==
336 			    KCF_PROV_VERIFICATION_FAILED) {
337 				undo_register_provider_extra(prov_desc);
338 				ret = CRYPTO_MODVERIFICATION_FAILED;
339 				goto bail;
340 			}
341 		}
342 	} else {
343 		mutex_enter(&prov_desc->pd_lock);
344 		prov_desc->pd_state = KCF_PROV_READY;
345 		mutex_exit(&prov_desc->pd_lock);
346 		kcf_do_notify(prov_desc, B_TRUE);
347 	}
348 
349 	*handle = prov_desc->pd_kcf_prov_handle;
350 	ret = CRYPTO_SUCCESS;
351 
352 bail:
353 	KCF_PROV_REFRELE(prov_desc);
354 	return (ret);
355 }
356 
357 /* Return the number of holds on a provider. */
358 int
359 kcf_get_refcnt(kcf_provider_desc_t *pd, boolean_t do_lock)
360 {
361 	int i;
362 	int refcnt = 0;
363 
364 	if (do_lock)
365 		for (i = 0; i < pd->pd_nbins; i++)
366 			mutex_enter(&(pd->pd_percpu_bins[i].kp_lock));
367 
368 	for (i = 0; i < pd->pd_nbins; i++)
369 		refcnt += pd->pd_percpu_bins[i].kp_holdcnt;
370 
371 	if (do_lock)
372 		for (i = 0; i < pd->pd_nbins; i++)
373 			mutex_exit(&(pd->pd_percpu_bins[i].kp_lock));
374 
375 	return (refcnt);
376 }
377 
378 /*
379  * This routine is used to notify the framework when a provider is being
380  * removed.  Hardware providers call this routine in their detach routines.
381  * Software providers call this routine in their _fini() routine.
382  */
383 int
384 crypto_unregister_provider(crypto_kcf_provider_handle_t handle)
385 {
386 	uint_t mech_idx;
387 	kcf_provider_desc_t *desc;
388 	kcf_prov_state_t saved_state;
389 
390 	/* lookup provider descriptor */
391 	if ((desc = kcf_prov_tab_lookup((crypto_provider_id_t)handle)) == NULL)
392 		return (CRYPTO_UNKNOWN_PROVIDER);
393 
394 	mutex_enter(&desc->pd_lock);
395 	/*
396 	 * Check if any other thread is disabling or removing
397 	 * this provider. We return if this is the case.
398 	 */
399 	if (desc->pd_state >= KCF_PROV_DISABLED) {
400 		mutex_exit(&desc->pd_lock);
401 		/* Release reference held by kcf_prov_tab_lookup(). */
402 		KCF_PROV_REFRELE(desc);
403 		return (CRYPTO_BUSY);
404 	}
405 
406 	saved_state = desc->pd_state;
407 	desc->pd_state = KCF_PROV_UNREGISTERING;
408 
409 	if (saved_state == KCF_PROV_BUSY) {
410 		/*
411 		 * The per-provider taskq threads may be waiting. We
412 		 * signal them so that they can start failing requests.
413 		 */
414 		cv_broadcast(&desc->pd_resume_cv);
415 	}
416 
417 	mutex_exit(&desc->pd_lock);
418 
419 	if (desc->pd_prov_type != CRYPTO_SW_PROVIDER) {
420 		remove_provider(desc);
421 	}
422 
423 	if (desc->pd_prov_type != CRYPTO_LOGICAL_PROVIDER) {
424 		/* remove the provider from the mechanisms tables */
425 		for (mech_idx = 0; mech_idx < desc->pd_mech_list_count;
426 		    mech_idx++) {
427 			kcf_remove_mech_provider(
428 			    desc->pd_mechanisms[mech_idx].cm_mech_name, desc);
429 		}
430 	}
431 
432 	/* remove provider from providers table */
433 	if (kcf_prov_tab_rem_provider((crypto_provider_id_t)handle) !=
434 	    CRYPTO_SUCCESS) {
435 		/* Release reference held by kcf_prov_tab_lookup(). */
436 		KCF_PROV_REFRELE(desc);
437 		return (CRYPTO_UNKNOWN_PROVIDER);
438 	}
439 
440 	delete_kstat(desc);
441 
442 	if (desc->pd_prov_type == CRYPTO_SW_PROVIDER) {
443 		/*
444 		 * Wait till the existing requests with the provider complete
445 		 * and all the holds are released. All the holds on a software
446 		 * provider are from kernel clients and the hold time
447 		 * is expected to be short. So, we won't be stuck here forever.
448 		 */
449 		while (kcf_get_refcnt(desc, B_TRUE) > 1) {
450 			/* wait 1 second and try again. */
451 			delay(1 * drv_usectohz(1000000));
452 		}
453 	} else {
454 		int i;
455 		kcf_prov_cpu_t *mp;
456 
457 		/*
458 		 * Wait until requests that have been sent to the provider
459 		 * complete.
460 		 */
461 		for (i = 0; i < desc->pd_nbins; i++) {
462 			mp = &(desc->pd_percpu_bins[i]);
463 
464 			mutex_enter(&mp->kp_lock);
465 			while (mp->kp_jobcnt > 0) {
466 				cv_wait(&mp->kp_cv, &mp->kp_lock);
467 			}
468 			mutex_exit(&mp->kp_lock);
469 		}
470 	}
471 
472 	mutex_enter(&desc->pd_lock);
473 	desc->pd_state = KCF_PROV_UNREGISTERED;
474 	mutex_exit(&desc->pd_lock);
475 
476 	kcf_do_notify(desc, B_FALSE);
477 
478 	/* Release reference held by kcf_prov_tab_lookup(). */
479 	KCF_PROV_REFRELE(desc);
480 
481 	if (kcf_get_refcnt(desc, B_TRUE) == 0) {
482 		kcf_free_provider_desc(desc);
483 	} else {
484 		ASSERT(desc->pd_prov_type != CRYPTO_SW_PROVIDER);
485 		/*
486 		 * We could avoid this if /dev/crypto can proactively
487 		 * remove any holds on us from a dormant PKCS #11 app.
488 		 * For now, a kcfd thread does a periodic check of the
489 		 * provider table for KCF_PROV_UNREGISTERED entries
490 		 * and frees them when refcnt reaches zero.
491 		 */
492 		mutex_enter(&prov_tab_mutex);
493 		kcf_need_provtab_walk = B_TRUE;
494 		mutex_exit(&prov_tab_mutex);
495 	}
496 
497 	return (CRYPTO_SUCCESS);
498 }
499 
500 /*
501  * This routine is used to notify the framework that the state of
502  * a cryptographic provider has changed. Valid state codes are:
503  *
504  * CRYPTO_PROVIDER_READY
505  * 	The provider indicates that it can process more requests. A provider
506  *	will notify with this event if it previously has notified us with a
507  *	CRYPTO_PROVIDER_BUSY.
508  *
509  * CRYPTO_PROVIDER_BUSY
510  * 	The provider can not take more requests.
511  *
512  * CRYPTO_PROVIDER_FAILED
513  *	The provider encountered an internal error. The framework will not
514  * 	be sending any more requests to the provider. The provider may notify
515  *	with a CRYPTO_PROVIDER_READY, if it is able to recover from the error.
516  *
517  * This routine can be called from user or interrupt context.
518  */
519 void
520 crypto_provider_notification(crypto_kcf_provider_handle_t handle, uint_t state)
521 {
522 	kcf_provider_desc_t *pd;
523 
524 	/* lookup the provider from the given handle */
525 	if ((pd = kcf_prov_tab_lookup((crypto_provider_id_t)handle)) == NULL)
526 		return;
527 
528 	mutex_enter(&pd->pd_lock);
529 
530 	if (pd->pd_state <= KCF_PROV_VERIFICATION_FAILED)
531 		goto out;
532 
533 	if (pd->pd_prov_type == CRYPTO_LOGICAL_PROVIDER) {
534 		cmn_err(CE_WARN, "crypto_provider_notification: "
535 		    "logical provider (%x) ignored\n", handle);
536 		goto out;
537 	}
538 	switch (state) {
539 	case CRYPTO_PROVIDER_READY:
540 		switch (pd->pd_state) {
541 		case KCF_PROV_BUSY:
542 			pd->pd_state = KCF_PROV_READY;
543 			/*
544 			 * Signal the per-provider taskq threads that they
545 			 * can start submitting requests.
546 			 */
547 			cv_broadcast(&pd->pd_resume_cv);
548 			break;
549 
550 		case KCF_PROV_FAILED:
551 			/*
552 			 * The provider recovered from the error. Let us
553 			 * use it now.
554 			 */
555 			pd->pd_state = KCF_PROV_READY;
556 			break;
557 		}
558 		break;
559 
560 	case CRYPTO_PROVIDER_BUSY:
561 		switch (pd->pd_state) {
562 		case KCF_PROV_READY:
563 			pd->pd_state = KCF_PROV_BUSY;
564 			break;
565 		}
566 		break;
567 
568 	case CRYPTO_PROVIDER_FAILED:
569 		/*
570 		 * We note the failure and return. The per-provider taskq
571 		 * threads check this flag and start failing the
572 		 * requests, if it is set. See process_req_hwp() for details.
573 		 */
574 		switch (pd->pd_state) {
575 		case KCF_PROV_READY:
576 			pd->pd_state = KCF_PROV_FAILED;
577 			break;
578 
579 		case KCF_PROV_BUSY:
580 			pd->pd_state = KCF_PROV_FAILED;
581 			/*
582 			 * The per-provider taskq threads may be waiting. We
583 			 * signal them so that they can start failing requests.
584 			 */
585 			cv_broadcast(&pd->pd_resume_cv);
586 			break;
587 		}
588 		break;
589 	}
590 out:
591 	mutex_exit(&pd->pd_lock);
592 	KCF_PROV_REFRELE(pd);
593 }
594 
595 /*
596  * This routine is used to notify the framework the result of
597  * an asynchronous request handled by a provider. Valid error
598  * codes are the same as the CRYPTO_* errors defined in common.h.
599  *
600  * This routine can be called from user or interrupt context.
601  */
602 void
603 crypto_op_notification(crypto_req_handle_t handle, int error)
604 {
605 	kcf_call_type_t ctype;
606 
607 	if (handle == NULL)
608 		return;
609 
610 	if ((ctype = GET_REQ_TYPE(handle)) == CRYPTO_SYNCH) {
611 		kcf_sreq_node_t *sreq = (kcf_sreq_node_t *)handle;
612 
613 		KCF_PROV_JOB_RELE_STAT(sreq->sn_mp, (error != CRYPTO_SUCCESS));
614 		kcf_sop_done(sreq, error);
615 	} else {
616 		kcf_areq_node_t *areq = (kcf_areq_node_t *)handle;
617 
618 		ASSERT(ctype == CRYPTO_ASYNCH);
619 		KCF_PROV_JOB_RELE_STAT(areq->an_mp, (error != CRYPTO_SUCCESS));
620 		kcf_aop_done(areq, error);
621 	}
622 }
623 
624 /*
625  * This routine is used by software providers to determine
626  * whether to use KM_SLEEP or KM_NOSLEEP during memory allocation.
627  * Note that hardware providers can always use KM_SLEEP. So,
628  * they do not need to call this routine.
629  *
630  * This routine can be called from user or interrupt context.
631  */
632 int
633 crypto_kmflag(crypto_req_handle_t handle)
634 {
635 	return (REQHNDL2_KMFLAG(handle));
636 }
637 
638 /*
639  * Process the mechanism info structures specified by the provider
640  * during registration. A NULL crypto_provider_info_t indicates
641  * an already initialized provider descriptor.
642  *
643  * Mechanisms are not added to the kernel's mechanism table if the
644  * provider is a logical provider.
645  *
646  * Returns CRYPTO_SUCCESS on success, CRYPTO_ARGUMENTS if one
647  * of the specified mechanisms was malformed, or CRYPTO_HOST_MEMORY
648  * if the table of mechanisms is full.
649  */
650 static int
651 init_prov_mechs(crypto_provider_info_t *info, kcf_provider_desc_t *desc)
652 {
653 	uint_t mech_idx;
654 	uint_t cleanup_idx;
655 	int err = CRYPTO_SUCCESS;
656 	kcf_prov_mech_desc_t *pmd;
657 	int desc_use_count = 0;
658 	int mcount = desc->pd_mech_list_count;
659 
660 	if (desc->pd_prov_type == CRYPTO_LOGICAL_PROVIDER) {
661 		if (info != NULL) {
662 			ASSERT(info->pi_mechanisms != NULL);
663 			bcopy(info->pi_mechanisms, desc->pd_mechanisms,
664 			    sizeof (crypto_mech_info_t) * mcount);
665 		}
666 		return (CRYPTO_SUCCESS);
667 	}
668 
669 	/*
670 	 * Copy the mechanism list from the provider info to the provider
671 	 * descriptor. desc->pd_mechanisms has an extra crypto_mech_info_t
672 	 * element if the provider has random_ops since we keep an internal
673 	 * mechanism, SUN_RANDOM, in this case.
674 	 */
675 	if (info != NULL) {
676 		if (info->pi_ops_vector->co_random_ops != NULL) {
677 			crypto_mech_info_t *rand_mi;
678 
679 			/*
680 			 * Need the following check as it is possible to have
681 			 * a provider that implements just random_ops and has
682 			 * pi_mechanisms == NULL.
683 			 */
684 			if (info->pi_mechanisms != NULL) {
685 				bcopy(info->pi_mechanisms, desc->pd_mechanisms,
686 				    sizeof (crypto_mech_info_t) * (mcount - 1));
687 			}
688 			rand_mi = &desc->pd_mechanisms[mcount - 1];
689 
690 			bzero(rand_mi, sizeof (crypto_mech_info_t));
691 			(void) strncpy(rand_mi->cm_mech_name, SUN_RANDOM,
692 			    CRYPTO_MAX_MECH_NAME);
693 			rand_mi->cm_func_group_mask = CRYPTO_FG_RANDOM;
694 		} else {
695 			ASSERT(info->pi_mechanisms != NULL);
696 			bcopy(info->pi_mechanisms, desc->pd_mechanisms,
697 			    sizeof (crypto_mech_info_t) * mcount);
698 		}
699 	}
700 
701 	/*
702 	 * For each mechanism support by the provider, add the provider
703 	 * to the corresponding KCF mechanism mech_entry chain.
704 	 */
705 	for (mech_idx = 0; mech_idx < desc->pd_mech_list_count; mech_idx++) {
706 		crypto_mech_info_t *mi = &desc->pd_mechanisms[mech_idx];
707 
708 		if ((mi->cm_mech_flags & CRYPTO_KEYSIZE_UNIT_IN_BITS) &&
709 		    (mi->cm_mech_flags & CRYPTO_KEYSIZE_UNIT_IN_BYTES)) {
710 			err = CRYPTO_ARGUMENTS_BAD;
711 			break;
712 		}
713 
714 		if (desc->pd_flags & CRYPTO_HASH_NO_UPDATE &&
715 		    mi->cm_func_group_mask & CRYPTO_FG_DIGEST) {
716 			/*
717 			 * We ask the provider to specify the limit
718 			 * per hash mechanism. But, in practice, a
719 			 * hardware limitation means all hash mechanisms
720 			 * will have the same maximum size allowed for
721 			 * input data. So, we make it a per provider
722 			 * limit to keep it simple.
723 			 */
724 			if (mi->cm_max_input_length == 0) {
725 				err = CRYPTO_ARGUMENTS_BAD;
726 				break;
727 			} else {
728 				desc->pd_hash_limit = mi->cm_max_input_length;
729 			}
730 		}
731 
732 		if ((err = kcf_add_mech_provider(mech_idx, desc, &pmd)) !=
733 		    KCF_SUCCESS)
734 			break;
735 
736 		if (pmd == NULL)
737 			continue;
738 
739 		/* The provider will be used for this mechanism */
740 		desc_use_count++;
741 	}
742 
743 	/*
744 	 * Don't allow multiple software providers with disabled mechanisms
745 	 * to register. Subsequent enabling of mechanisms will result in
746 	 * an unsupported configuration, i.e. multiple software providers
747 	 * per mechanism.
748 	 */
749 	if (desc_use_count == 0 && desc->pd_prov_type == CRYPTO_SW_PROVIDER)
750 		return (CRYPTO_ARGUMENTS_BAD);
751 
752 	if (err == KCF_SUCCESS)
753 		return (CRYPTO_SUCCESS);
754 
755 	/*
756 	 * An error occurred while adding the mechanism, cleanup
757 	 * and bail.
758 	 */
759 	for (cleanup_idx = 0; cleanup_idx < mech_idx; cleanup_idx++) {
760 		kcf_remove_mech_provider(
761 		    desc->pd_mechanisms[cleanup_idx].cm_mech_name, desc);
762 	}
763 
764 	if (err == KCF_MECH_TAB_FULL)
765 		return (CRYPTO_HOST_MEMORY);
766 
767 	return (CRYPTO_ARGUMENTS_BAD);
768 }
769 
770 /*
771  * Update routine for kstat. Only privileged users are allowed to
772  * access this information, since this information is sensitive.
773  * There are some cryptographic attacks (e.g. traffic analysis)
774  * which can use this information.
775  */
776 static int
777 kcf_prov_kstat_update(kstat_t *ksp, int rw)
778 {
779 	kcf_prov_stats_t *ks_data;
780 	kcf_provider_desc_t *pd = (kcf_provider_desc_t *)ksp->ks_private;
781 	int i;
782 
783 	if (rw == KSTAT_WRITE)
784 		return (EACCES);
785 
786 	ks_data = ksp->ks_data;
787 
788 	if (secpolicy_sys_config(CRED(), B_TRUE) != 0) {
789 		ks_data->ps_ops_total.value.ui64 = 0;
790 		ks_data->ps_ops_passed.value.ui64 = 0;
791 		ks_data->ps_ops_failed.value.ui64 = 0;
792 		ks_data->ps_ops_busy_rval.value.ui64 = 0;
793 	} else {
794 		uint64_t dtotal, ftotal, btotal;
795 
796 		dtotal = ftotal = btotal = 0;
797 		/* No locking done since an exact count is not required. */
798 		for (i = 0; i < pd->pd_nbins; i++) {
799 			dtotal += pd->pd_percpu_bins[i].kp_ndispatches;
800 			ftotal += pd->pd_percpu_bins[i].kp_nfails;
801 			btotal += pd->pd_percpu_bins[i].kp_nbusy_rval;
802 		}
803 
804 		ks_data->ps_ops_total.value.ui64 = dtotal;
805 		ks_data->ps_ops_failed.value.ui64 = ftotal;
806 		ks_data->ps_ops_busy_rval.value.ui64 = btotal;
807 		ks_data->ps_ops_passed.value.ui64 = dtotal - ftotal - btotal;
808 	}
809 
810 	return (0);
811 }
812 
813 
814 /*
815  * Utility routine called from failure paths in crypto_register_provider()
816  * and from crypto_load_soft_disabled().
817  */
818 void
819 undo_register_provider(kcf_provider_desc_t *desc, boolean_t remove_prov)
820 {
821 	uint_t mech_idx;
822 
823 	/* remove the provider from the mechanisms tables */
824 	for (mech_idx = 0; mech_idx < desc->pd_mech_list_count;
825 	    mech_idx++) {
826 		kcf_remove_mech_provider(
827 		    desc->pd_mechanisms[mech_idx].cm_mech_name, desc);
828 	}
829 
830 	/* remove provider from providers table */
831 	if (remove_prov)
832 		(void) kcf_prov_tab_rem_provider(desc->pd_prov_id);
833 }
834 
835 static void
836 undo_register_provider_extra(kcf_provider_desc_t *desc)
837 {
838 	delete_kstat(desc);
839 	undo_register_provider(desc, B_TRUE);
840 }
841 
842 /*
843  * Utility routine called from crypto_load_soft_disabled(). Callers
844  * should have done a prior undo_register_provider().
845  */
846 void
847 redo_register_provider(kcf_provider_desc_t *pd)
848 {
849 	/* process the mechanisms supported by the provider */
850 	(void) init_prov_mechs(NULL, pd);
851 
852 	/*
853 	 * Hold provider in providers table. We should not call
854 	 * kcf_prov_tab_add_provider() here as the provider descriptor
855 	 * is still valid which means it has an entry in the provider
856 	 * table.
857 	 */
858 	KCF_PROV_REFHOLD(pd);
859 }
860 
861 /*
862  * Add provider (p1) to another provider's array of providers (p2).
863  * Hardware and logical providers use this array to cross-reference
864  * each other.
865  */
866 static void
867 add_provider_to_array(kcf_provider_desc_t *p1, kcf_provider_desc_t *p2)
868 {
869 	kcf_provider_list_t *new;
870 
871 	new = kmem_alloc(sizeof (kcf_provider_list_t), KM_SLEEP);
872 	mutex_enter(&p2->pd_lock);
873 	new->pl_next = p2->pd_provider_list;
874 	p2->pd_provider_list = new;
875 	new->pl_provider = p1;
876 	mutex_exit(&p2->pd_lock);
877 }
878 
879 /*
880  * Remove provider (p1) from another provider's array of providers (p2).
881  * Hardware and logical providers use this array to cross-reference
882  * each other.
883  */
884 static void
885 remove_provider_from_array(kcf_provider_desc_t *p1, kcf_provider_desc_t *p2)
886 {
887 
888 	kcf_provider_list_t *pl = NULL, **prev;
889 
890 	mutex_enter(&p2->pd_lock);
891 	for (pl = p2->pd_provider_list, prev = &p2->pd_provider_list;
892 	    pl != NULL; prev = &pl->pl_next, pl = pl->pl_next) {
893 		if (pl->pl_provider == p1) {
894 			break;
895 		}
896 	}
897 
898 	if (p1 == NULL) {
899 		mutex_exit(&p2->pd_lock);
900 		return;
901 	}
902 
903 	/* detach and free kcf_provider_list structure */
904 	*prev = pl->pl_next;
905 	kmem_free(pl, sizeof (*pl));
906 	mutex_exit(&p2->pd_lock);
907 }
908 
909 /*
910  * Convert an array of logical provider handles (crypto_provider_id)
911  * stored in a crypto_provider_info structure into an array of provider
912  * descriptors (kcf_provider_desc_t) attached to a logical provider.
913  */
914 static void
915 process_logical_providers(crypto_provider_info_t *info, kcf_provider_desc_t *hp)
916 {
917 	kcf_provider_desc_t *lp;
918 	crypto_provider_id_t handle;
919 	int count = info->pi_logical_provider_count;
920 	int i;
921 
922 	/* add hardware provider to each logical provider */
923 	for (i = 0; i < count; i++) {
924 		handle = info->pi_logical_providers[i];
925 		lp = kcf_prov_tab_lookup((crypto_provider_id_t)handle);
926 		if (lp == NULL) {
927 			continue;
928 		}
929 		add_provider_to_array(hp, lp);
930 		hp->pd_flags |= KCF_LPROV_MEMBER;
931 
932 		/*
933 		 * A hardware provider has to have the provider descriptor of
934 		 * every logical provider it belongs to, so it can be removed
935 		 * from the logical provider if the hardware provider
936 		 * unregisters from the framework.
937 		 */
938 		add_provider_to_array(lp, hp);
939 		KCF_PROV_REFRELE(lp);
940 	}
941 }
942 
943 /*
944  * This routine removes a provider from all of the logical or
945  * hardware providers it belongs to, and frees the provider's
946  * array of pointers to providers.
947  */
948 static void
949 remove_provider(kcf_provider_desc_t *pp)
950 {
951 	kcf_provider_desc_t *p;
952 	kcf_provider_list_t *e, *next;
953 
954 	mutex_enter(&pp->pd_lock);
955 	for (e = pp->pd_provider_list; e != NULL; e = next) {
956 		p = e->pl_provider;
957 		remove_provider_from_array(pp, p);
958 		if (p->pd_prov_type == CRYPTO_HW_PROVIDER &&
959 		    p->pd_provider_list == NULL)
960 			p->pd_flags &= ~KCF_LPROV_MEMBER;
961 		next = e->pl_next;
962 		kmem_free(e, sizeof (*e));
963 	}
964 	pp->pd_provider_list = NULL;
965 	mutex_exit(&pp->pd_lock);
966 }
967 
968 /*
969  * Dispatch events as needed for a provider. is_added flag tells
970  * whether the provider is registering or unregistering.
971  */
972 void
973 kcf_do_notify(kcf_provider_desc_t *prov_desc, boolean_t is_added)
974 {
975 	int i;
976 	crypto_notify_event_change_t ec;
977 
978 	ASSERT(prov_desc->pd_state > KCF_PROV_VERIFICATION_FAILED);
979 
980 	/*
981 	 * Inform interested clients of the mechanisms becoming
982 	 * available/unavailable. We skip this for logical providers
983 	 * as they do not affect mechanisms.
984 	 */
985 	if (prov_desc->pd_prov_type != CRYPTO_LOGICAL_PROVIDER) {
986 		ec.ec_provider_type = prov_desc->pd_prov_type;
987 		ec.ec_change = is_added ? CRYPTO_MECH_ADDED :
988 		    CRYPTO_MECH_REMOVED;
989 		for (i = 0; i < prov_desc->pd_mech_list_count; i++) {
990 			/* Skip any mechanisms not allowed by the policy */
991 			if (is_mech_disabled(prov_desc,
992 			    prov_desc->pd_mechanisms[i].cm_mech_name))
993 				continue;
994 
995 			(void) strncpy(ec.ec_mech_name,
996 			    prov_desc->pd_mechanisms[i].cm_mech_name,
997 			    CRYPTO_MAX_MECH_NAME);
998 			kcf_walk_ntfylist(CRYPTO_EVENT_MECHS_CHANGED, &ec);
999 		}
1000 
1001 	}
1002 
1003 	/*
1004 	 * Inform interested clients about the new or departing provider.
1005 	 * In case of a logical provider, we need to notify the event only
1006 	 * for the logical provider and not for the underlying
1007 	 * providers which are known by the KCF_LPROV_MEMBER bit.
1008 	 */
1009 	if (prov_desc->pd_prov_type == CRYPTO_LOGICAL_PROVIDER ||
1010 	    (prov_desc->pd_flags & KCF_LPROV_MEMBER) == 0) {
1011 		kcf_walk_ntfylist(is_added ? CRYPTO_EVENT_PROVIDER_REGISTERED :
1012 		    CRYPTO_EVENT_PROVIDER_UNREGISTERED, prov_desc);
1013 	}
1014 }
1015 
1016 static void
1017 delete_kstat(kcf_provider_desc_t *desc)
1018 {
1019 	/* destroy the kstat created for this provider */
1020 	if (desc->pd_kstat != NULL) {
1021 		kcf_provider_desc_t *kspd = desc->pd_kstat->ks_private;
1022 
1023 		/* release reference held by desc->pd_kstat->ks_private */
1024 		ASSERT(desc == kspd);
1025 		kstat_delete(kspd->pd_kstat);
1026 		desc->pd_kstat = NULL;
1027 		KCF_PROV_REFRELE(kspd);
1028 	}
1029 }
1030