1 /*
2  * Copyright (c) 2017-2018, ARM Limited and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 /*
8  * Exception handlers at EL3, their priority levels, and management.
9  */
10 
11 #include <assert.h>
12 #include <stdbool.h>
13 
14 #include <bl31/ehf.h>
15 #include <bl31/interrupt_mgmt.h>
16 #include <context.h>
17 #include <common/debug.h>
18 #include <drivers/arm/gic_common.h>
19 #include <lib/el3_runtime/context_mgmt.h>
20 #include <lib/el3_runtime/cpu_data.h>
21 #include <lib/el3_runtime/pubsub_events.h>
22 #include <plat/common/platform.h>
23 
24 /* Output EHF logs as verbose */
25 #define EHF_LOG(...)	VERBOSE("EHF: " __VA_ARGS__)
26 
27 #define EHF_INVALID_IDX	(-1)
28 
29 /* For a valid handler, return the actual function pointer; otherwise, 0. */
30 #define RAW_HANDLER(h) \
31 	((ehf_handler_t) ((((h) & EHF_PRI_VALID_) != 0U) ? \
32 		((h) & ~EHF_PRI_VALID_) : 0U))
33 
34 #define PRI_BIT(idx)	(((ehf_pri_bits_t) 1u) << (idx))
35 
36 /*
37  * Convert index into secure priority using the platform-defined priority bits
38  * field.
39  */
40 #define IDX_TO_PRI(idx) \
41 	((((unsigned) idx) << (7u - exception_data.pri_bits)) & 0x7fU)
42 
43 /* Check whether a given index is valid */
44 #define IS_IDX_VALID(idx) \
45 	((exception_data.ehf_priorities[idx].ehf_handler & EHF_PRI_VALID_) != 0U)
46 
47 /* Returns whether given priority is in secure priority range */
48 #define IS_PRI_SECURE(pri)	(((pri) & 0x80U) == 0U)
49 
50 /* To be defined by the platform */
51 extern const ehf_priorities_t exception_data;
52 
53 /* Translate priority to the index in the priority array */
pri_to_idx(unsigned int priority)54 static unsigned int pri_to_idx(unsigned int priority)
55 {
56 	unsigned int idx;
57 
58 	idx = EHF_PRI_TO_IDX(priority, exception_data.pri_bits);
59 	assert(idx < exception_data.num_priorities);
60 	assert(IS_IDX_VALID(idx));
61 
62 	return idx;
63 }
64 
65 /* Return whether there are outstanding priority activation */
has_valid_pri_activations(pe_exc_data_t * pe_data)66 static bool has_valid_pri_activations(pe_exc_data_t *pe_data)
67 {
68 	return pe_data->active_pri_bits != 0U;
69 }
70 
this_cpu_data(void)71 static pe_exc_data_t *this_cpu_data(void)
72 {
73 	return &get_cpu_data(ehf_data);
74 }
75 
76 /*
77  * Return the current priority index of this CPU. If no priority is active,
78  * return EHF_INVALID_IDX.
79  */
get_pe_highest_active_idx(pe_exc_data_t * pe_data)80 static int get_pe_highest_active_idx(pe_exc_data_t *pe_data)
81 {
82 	if (!has_valid_pri_activations(pe_data))
83 		return EHF_INVALID_IDX;
84 
85 	/* Current priority is the right-most bit */
86 	return (int) __builtin_ctz(pe_data->active_pri_bits);
87 }
88 
89 /*
90  * Mark priority active by setting the corresponding bit in active_pri_bits and
91  * programming the priority mask.
92  *
93  * This API is to be used as part of delegating to lower ELs other than for
94  * interrupts; e.g. while handling synchronous exceptions.
95  *
96  * This API is expected to be invoked before restoring context (Secure or
97  * Non-secure) in preparation for the respective dispatch.
98  */
ehf_activate_priority(unsigned int priority)99 void ehf_activate_priority(unsigned int priority)
100 {
101 	int cur_pri_idx;
102 	unsigned int old_mask, run_pri, idx;
103 	pe_exc_data_t *pe_data = this_cpu_data();
104 
105 	/*
106 	 * Query interrupt controller for the running priority, or idle priority
107 	 * if no interrupts are being handled. The requested priority must be
108 	 * less (higher priority) than the active running priority.
109 	 */
110 	run_pri = plat_ic_get_running_priority();
111 	if (priority >= run_pri) {
112 		ERROR("Running priority higher (0x%x) than requested (0x%x)\n",
113 				run_pri, priority);
114 		panic();
115 	}
116 
117 	/*
118 	 * If there were priority activations already, the requested priority
119 	 * must be less (higher priority) than the current highest priority
120 	 * activation so far.
121 	 */
122 	cur_pri_idx = get_pe_highest_active_idx(pe_data);
123 	idx = pri_to_idx(priority);
124 	if ((cur_pri_idx != EHF_INVALID_IDX) &&
125 			(idx >= ((unsigned int) cur_pri_idx))) {
126 		ERROR("Activation priority mismatch: req=0x%x current=0x%x\n",
127 				priority, IDX_TO_PRI(cur_pri_idx));
128 		panic();
129 	}
130 
131 	/* Set the bit corresponding to the requested priority */
132 	pe_data->active_pri_bits |= PRI_BIT(idx);
133 
134 	/*
135 	 * Program priority mask for the activated level. Check that the new
136 	 * priority mask is setting a higher priority level than the existing
137 	 * mask.
138 	 */
139 	old_mask = plat_ic_set_priority_mask(priority);
140 	if (priority >= old_mask) {
141 		ERROR("Requested priority (0x%x) lower than Priority Mask (0x%x)\n",
142 				priority, old_mask);
143 		panic();
144 	}
145 
146 	/*
147 	 * If this is the first activation, save the priority mask. This will be
148 	 * restored after the last deactivation.
149 	 */
150 	if (cur_pri_idx == EHF_INVALID_IDX)
151 		pe_data->init_pri_mask = (uint8_t) old_mask;
152 
153 	EHF_LOG("activate prio=%d\n", get_pe_highest_active_idx(pe_data));
154 }
155 
156 /*
157  * Mark priority inactive by clearing the corresponding bit in active_pri_bits,
158  * and programming the priority mask.
159  *
160  * This API is expected to be used as part of delegating to to lower ELs other
161  * than for interrupts; e.g. while handling synchronous exceptions.
162  *
163  * This API is expected to be invoked after saving context (Secure or
164  * Non-secure), having concluded the respective dispatch.
165  */
ehf_deactivate_priority(unsigned int priority)166 void ehf_deactivate_priority(unsigned int priority)
167 {
168 	int cur_pri_idx;
169 	pe_exc_data_t *pe_data = this_cpu_data();
170 	unsigned int old_mask, run_pri, idx;
171 
172 	/*
173 	 * Query interrupt controller for the running priority, or idle priority
174 	 * if no interrupts are being handled. The requested priority must be
175 	 * less (higher priority) than the active running priority.
176 	 */
177 	run_pri = plat_ic_get_running_priority();
178 	if (priority >= run_pri) {
179 		ERROR("Running priority higher (0x%x) than requested (0x%x)\n",
180 				run_pri, priority);
181 		panic();
182 	}
183 
184 	/*
185 	 * Deactivation is allowed only when there are priority activations, and
186 	 * the deactivation priority level must match the current activated
187 	 * priority.
188 	 */
189 	cur_pri_idx = get_pe_highest_active_idx(pe_data);
190 	idx = pri_to_idx(priority);
191 	if ((cur_pri_idx == EHF_INVALID_IDX) ||
192 			(idx != ((unsigned int) cur_pri_idx))) {
193 		ERROR("Deactivation priority mismatch: req=0x%x current=0x%x\n",
194 				priority, IDX_TO_PRI(cur_pri_idx));
195 		panic();
196 	}
197 
198 	/* Clear bit corresponding to highest priority */
199 	pe_data->active_pri_bits &= (pe_data->active_pri_bits - 1u);
200 
201 	/*
202 	 * Restore priority mask corresponding to the next priority, or the
203 	 * one stashed earlier if there are no more to deactivate.
204 	 */
205 	cur_pri_idx = get_pe_highest_active_idx(pe_data);
206 	if (cur_pri_idx == EHF_INVALID_IDX)
207 		old_mask = plat_ic_set_priority_mask(pe_data->init_pri_mask);
208 	else
209 		old_mask = plat_ic_set_priority_mask(priority);
210 
211 	if (old_mask > priority) {
212 		ERROR("Deactivation priority (0x%x) lower than Priority Mask (0x%x)\n",
213 				priority, old_mask);
214 		panic();
215 	}
216 
217 	EHF_LOG("deactivate prio=%d\n", get_pe_highest_active_idx(pe_data));
218 }
219 
220 /*
221  * After leaving Non-secure world, stash current Non-secure Priority Mask, and
222  * set Priority Mask to the highest Non-secure priority so that Non-secure
223  * interrupts cannot preempt Secure execution.
224  *
225  * If the current running priority is in the secure range, or if there are
226  * outstanding priority activations, this function does nothing.
227  *
228  * This function subscribes to the 'cm_exited_normal_world' event published by
229  * the Context Management Library.
230  */
ehf_exited_normal_world(const void * arg)231 static void *ehf_exited_normal_world(const void *arg)
232 {
233 	unsigned int run_pri;
234 	pe_exc_data_t *pe_data = this_cpu_data();
235 
236 	/* If the running priority is in the secure range, do nothing */
237 	run_pri = plat_ic_get_running_priority();
238 	if (IS_PRI_SECURE(run_pri))
239 		return NULL;
240 
241 	/* Do nothing if there are explicit activations */
242 	if (has_valid_pri_activations(pe_data))
243 		return NULL;
244 
245 	assert(pe_data->ns_pri_mask == 0u);
246 
247 	pe_data->ns_pri_mask =
248 		(uint8_t) plat_ic_set_priority_mask(GIC_HIGHEST_NS_PRIORITY);
249 
250 	/* The previous Priority Mask is not expected to be in secure range */
251 	if (IS_PRI_SECURE(pe_data->ns_pri_mask)) {
252 		ERROR("Priority Mask (0x%x) already in secure range\n",
253 				pe_data->ns_pri_mask);
254 		panic();
255 	}
256 
257 	EHF_LOG("Priority Mask: 0x%x => 0x%x\n", pe_data->ns_pri_mask,
258 			GIC_HIGHEST_NS_PRIORITY);
259 
260 	return NULL;
261 }
262 
263 /*
264  * Conclude Secure execution and prepare for return to Non-secure world. Restore
265  * the Non-secure Priority Mask previously stashed upon leaving Non-secure
266  * world.
267  *
268  * If there the current running priority is in the secure range, or if there are
269  * outstanding priority activations, this function does nothing.
270  *
271  * This function subscribes to the 'cm_entering_normal_world' event published by
272  * the Context Management Library.
273  */
ehf_entering_normal_world(const void * arg)274 static void *ehf_entering_normal_world(const void *arg)
275 {
276 	unsigned int old_pmr, run_pri;
277 	pe_exc_data_t *pe_data = this_cpu_data();
278 
279 	/* If the running priority is in the secure range, do nothing */
280 	run_pri = plat_ic_get_running_priority();
281 	if (IS_PRI_SECURE(run_pri))
282 		return NULL;
283 
284 	/*
285 	 * If there are explicit activations, do nothing. The Priority Mask will
286 	 * be restored upon the last deactivation.
287 	 */
288 	if (has_valid_pri_activations(pe_data))
289 		return NULL;
290 
291 	/* Do nothing if we don't have a valid Priority Mask to restore */
292 	if (pe_data->ns_pri_mask == 0U)
293 		return NULL;
294 
295 	old_pmr = plat_ic_set_priority_mask(pe_data->ns_pri_mask);
296 
297 	/*
298 	 * When exiting secure world, the current Priority Mask must be
299 	 * GIC_HIGHEST_NS_PRIORITY (as set during entry), or the Non-secure
300 	 * priority mask set upon calling ehf_allow_ns_preemption()
301 	 */
302 	if ((old_pmr != GIC_HIGHEST_NS_PRIORITY) &&
303 			(old_pmr != pe_data->ns_pri_mask)) {
304 		ERROR("Invalid Priority Mask (0x%x) restored\n", old_pmr);
305 		panic();
306 	}
307 
308 	EHF_LOG("Priority Mask: 0x%x => 0x%x\n", old_pmr, pe_data->ns_pri_mask);
309 
310 	pe_data->ns_pri_mask = 0;
311 
312 	return NULL;
313 }
314 
315 /*
316  * Program Priority Mask to the original Non-secure priority such that
317  * Non-secure interrupts may preempt Secure execution (for example, during
318  * Yielding SMC calls). The 'preempt_ret_code' parameter indicates the Yielding
319  * SMC's return value in case the call was preempted.
320  *
321  * This API is expected to be invoked before delegating a yielding SMC to Secure
322  * EL1. I.e. within the window of secure execution after Non-secure context is
323  * saved (after entry into EL3) and Secure context is restored (before entering
324  * Secure EL1).
325  */
ehf_allow_ns_preemption(uint64_t preempt_ret_code)326 void ehf_allow_ns_preemption(uint64_t preempt_ret_code)
327 {
328 	cpu_context_t *ns_ctx;
329 	unsigned int old_pmr __unused;
330 	pe_exc_data_t *pe_data = this_cpu_data();
331 
332 	/*
333 	 * We should have been notified earlier of entering secure world, and
334 	 * therefore have stashed the Non-secure priority mask.
335 	 */
336 	assert(pe_data->ns_pri_mask != 0U);
337 
338 	/* Make sure no priority levels are active when requesting this */
339 	if (has_valid_pri_activations(pe_data)) {
340 		ERROR("PE %lx has priority activations: 0x%x\n",
341 				read_mpidr_el1(), pe_data->active_pri_bits);
342 		panic();
343 	}
344 
345 	/*
346 	 * Program preempted return code to x0 right away so that, if the
347 	 * Yielding SMC was indeed preempted before a dispatcher gets a chance
348 	 * to populate it, the caller would find the correct return value.
349 	 */
350 	ns_ctx = cm_get_context(NON_SECURE);
351 	assert(ns_ctx != NULL);
352 	write_ctx_reg(get_gpregs_ctx(ns_ctx), CTX_GPREG_X0, preempt_ret_code);
353 
354 	old_pmr = plat_ic_set_priority_mask(pe_data->ns_pri_mask);
355 
356 	EHF_LOG("Priority Mask: 0x%x => 0x%x\n", old_pmr, pe_data->ns_pri_mask);
357 
358 	pe_data->ns_pri_mask = 0;
359 }
360 
361 /*
362  * Return whether Secure execution has explicitly allowed Non-secure interrupts
363  * to preempt itself (for example, during Yielding SMC calls).
364  */
ehf_is_ns_preemption_allowed(void)365 unsigned int ehf_is_ns_preemption_allowed(void)
366 {
367 	unsigned int run_pri;
368 	pe_exc_data_t *pe_data = this_cpu_data();
369 
370 	/* If running priority is in secure range, return false */
371 	run_pri = plat_ic_get_running_priority();
372 	if (IS_PRI_SECURE(run_pri))
373 		return 0;
374 
375 	/*
376 	 * If Non-secure preemption was permitted by calling
377 	 * ehf_allow_ns_preemption() earlier:
378 	 *
379 	 * - There wouldn't have been priority activations;
380 	 * - We would have cleared the stashed the Non-secure Priority Mask.
381 	 */
382 	if (has_valid_pri_activations(pe_data))
383 		return 0;
384 	if (pe_data->ns_pri_mask != 0U)
385 		return 0;
386 
387 	return 1;
388 }
389 
390 /*
391  * Top-level EL3 interrupt handler.
392  */
ehf_el3_interrupt_handler(uint32_t id,uint32_t flags,void * handle,void * cookie)393 static uint64_t ehf_el3_interrupt_handler(uint32_t id, uint32_t flags,
394 		void *handle, void *cookie)
395 {
396 	int ret = 0;
397 	uint32_t intr_raw;
398 	unsigned int intr, pri, idx;
399 	ehf_handler_t handler;
400 
401 	/*
402 	 * Top-level interrupt type handler from Interrupt Management Framework
403 	 * doesn't acknowledge the interrupt; so the interrupt ID must be
404 	 * invalid.
405 	 */
406 	assert(id == INTR_ID_UNAVAILABLE);
407 
408 	/*
409 	 * Acknowledge interrupt. Proceed with handling only for valid interrupt
410 	 * IDs. This situation may arise because of Interrupt Management
411 	 * Framework identifying an EL3 interrupt, but before it's been
412 	 * acknowledged here, the interrupt was either deasserted, or there was
413 	 * a higher-priority interrupt of another type.
414 	 */
415 	intr_raw = plat_ic_acknowledge_interrupt();
416 	intr = plat_ic_get_interrupt_id(intr_raw);
417 	if (intr == INTR_ID_UNAVAILABLE)
418 		return 0;
419 
420 	/* Having acknowledged the interrupt, get the running priority */
421 	pri = plat_ic_get_running_priority();
422 
423 	/* Check EL3 interrupt priority is in secure range */
424 	assert(IS_PRI_SECURE(pri));
425 
426 	/*
427 	 * Translate the priority to a descriptor index. We do this by masking
428 	 * and shifting the running priority value (platform-supplied).
429 	 */
430 	idx = pri_to_idx(pri);
431 
432 	/* Validate priority */
433 	assert(pri == IDX_TO_PRI(idx));
434 
435 	handler = (ehf_handler_t) RAW_HANDLER(
436 			exception_data.ehf_priorities[idx].ehf_handler);
437 	if (handler == NULL) {
438 		ERROR("No EL3 exception handler for priority 0x%x\n",
439 				IDX_TO_PRI(idx));
440 		panic();
441 	}
442 
443 	/*
444 	 * Call registered handler. Pass the raw interrupt value to registered
445 	 * handlers.
446 	 */
447 	ret = handler(intr_raw, flags, handle, cookie);
448 
449 	return (uint64_t) ret;
450 }
451 
452 /*
453  * Initialize the EL3 exception handling.
454  */
ehf_init(void)455 void __init ehf_init(void)
456 {
457 	unsigned int flags = 0;
458 	int ret __unused;
459 
460 	/* Ensure EL3 interrupts are supported */
461 	assert(plat_ic_has_interrupt_type(INTR_TYPE_EL3) != 0);
462 
463 	/*
464 	 * Make sure that priority water mark has enough bits to represent the
465 	 * whole priority array.
466 	 */
467 	assert(exception_data.num_priorities <= (sizeof(ehf_pri_bits_t) * 8U));
468 
469 	assert(exception_data.ehf_priorities != NULL);
470 
471 	/*
472 	 * Bit 7 of GIC priority must be 0 for secure interrupts. This means
473 	 * platforms must use at least 1 of the remaining 7 bits.
474 	 */
475 	assert((exception_data.pri_bits >= 1U) ||
476 			(exception_data.pri_bits < 8U));
477 
478 	/* Route EL3 interrupts when in Secure and Non-secure. */
479 	set_interrupt_rm_flag(flags, NON_SECURE);
480 	set_interrupt_rm_flag(flags, SECURE);
481 
482 	/* Register handler for EL3 interrupts */
483 	ret = register_interrupt_type_handler(INTR_TYPE_EL3,
484 			ehf_el3_interrupt_handler, flags);
485 	assert(ret == 0);
486 }
487 
488 /*
489  * Register a handler at the supplied priority. Registration is allowed only if
490  * a handler hasn't been registered before, or one wasn't provided at build
491  * time. The priority for which the handler is being registered must also accord
492  * with the platform-supplied data.
493  */
ehf_register_priority_handler(unsigned int pri,ehf_handler_t handler)494 void ehf_register_priority_handler(unsigned int pri, ehf_handler_t handler)
495 {
496 	unsigned int idx;
497 
498 	/* Sanity check for handler */
499 	assert(handler != NULL);
500 
501 	/* Handler ought to be 4-byte aligned */
502 	assert((((uintptr_t) handler) & 3U) == 0U);
503 
504 	/* Ensure we register for valid priority */
505 	idx = pri_to_idx(pri);
506 	assert(idx < exception_data.num_priorities);
507 	assert(IDX_TO_PRI(idx) == pri);
508 
509 	/* Return failure if a handler was already registered */
510 	if (exception_data.ehf_priorities[idx].ehf_handler != EHF_NO_HANDLER_) {
511 		ERROR("Handler already registered for priority 0x%x\n", pri);
512 		panic();
513 	}
514 
515 	/*
516 	 * Install handler, and retain the valid bit. We assume that the handler
517 	 * is 4-byte aligned, which is usually the case.
518 	 */
519 	exception_data.ehf_priorities[idx].ehf_handler =
520 		(((uintptr_t) handler) | EHF_PRI_VALID_);
521 
522 	EHF_LOG("register pri=0x%x handler=%p\n", pri, handler);
523 }
524 
525 SUBSCRIBE_TO_EVENT(cm_entering_normal_world, ehf_entering_normal_world);
526 SUBSCRIBE_TO_EVENT(cm_exited_normal_world, ehf_exited_normal_world);
527