xref: /linux/drivers/gpu/drm/xe/xe_pxp.c (revision 5c9deba5578db5a3ea05be8a3e4a59ecb08ee76f)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright(c) 2024 Intel Corporation.
4  */
5 
6 #include "xe_pxp.h"
7 
8 #include <drm/drm_managed.h>
9 #include <uapi/drm/xe_drm.h>
10 
11 #include "xe_bo.h"
12 #include "xe_bo_types.h"
13 #include "xe_device_types.h"
14 #include "xe_exec_queue.h"
15 #include "xe_force_wake.h"
16 #include "xe_guc_exec_queue_types.h"
17 #include "xe_guc_submit.h"
18 #include "xe_gsc_proxy.h"
19 #include "xe_gt_types.h"
20 #include "xe_huc.h"
21 #include "xe_hw_engine.h"
22 #include "xe_mmio.h"
23 #include "xe_pm.h"
24 #include "xe_pxp_submit.h"
25 #include "xe_pxp_types.h"
26 #include "xe_uc_fw.h"
27 #include "regs/xe_irq_regs.h"
28 #include "regs/xe_pxp_regs.h"
29 
30 /**
31  * DOC: PXP
32  *
33  * PXP (Protected Xe Path) allows execution and flip to display of protected
34  * (i.e. encrypted) objects. This feature is currently only supported in
35  * integrated parts.
36  */
37 
38 #define ARB_SESSION DRM_XE_PXP_HWDRM_DEFAULT_SESSION /* shorter define */
39 
40 /*
41  * A submission to GSC can take up to 250ms to complete, so use a 300ms
42  * timeout for activation where only one of those is involved. Termination
43  * additionally requires a submission to VCS and an interaction with KCR, so
44  * bump the timeout to 500ms for that.
45  */
46 #define PXP_ACTIVATION_TIMEOUT_MS 300
47 #define PXP_TERMINATION_TIMEOUT_MS 500
48 
49 bool xe_pxp_is_supported(const struct xe_device *xe)
50 {
51 	return xe->info.has_pxp && IS_ENABLED(CONFIG_INTEL_MEI_GSC_PROXY);
52 }
53 
54 bool xe_pxp_is_enabled(const struct xe_pxp *pxp)
55 {
56 	return pxp;
57 }
58 
59 static bool pxp_prerequisites_done(const struct xe_pxp *pxp)
60 {
61 	struct xe_gt *gt = pxp->gt;
62 	bool huc_ok;
63 	bool ready;
64 
65 	CLASS(xe_force_wake, fw_ref)(gt_to_fw(gt), XE_FORCEWAKE_ALL);
66 
67 	/*
68 	 * If force_wake fails we could falsely report the prerequisites as not
69 	 * done even if they are; the consequence of this would be that the
70 	 * callers won't go ahead with using PXP, but if force_wake doesn't work
71 	 * the GT is very likely in a bad state so not really a problem to abort
72 	 * PXP. Therefore, we can just log the force_wake error and not escalate
73 	 * it.
74 	 */
75 	XE_WARN_ON(!xe_force_wake_ref_has_domain(fw_ref.domains, XE_FORCEWAKE_ALL));
76 
77 	/*
78 	 * PXP requires GSC proxy to be initialized. On platforms where the HuC
79 	 * is loaded by the kernel driver (i.e., pre media 35) PXP also requires
80 	 * the HuC to be authenticated by GSC.
81 	 */
82 	huc_ok = MEDIA_VER(gt_to_xe(gt)) >= 35 ||
83 		 xe_huc_is_authenticated(&gt->uc.huc, XE_HUC_AUTH_VIA_GSC);
84 	ready = huc_ok && xe_gsc_proxy_init_done(&gt->uc.gsc);
85 
86 	return ready;
87 }
88 
89 /**
90  * xe_pxp_get_readiness_status - check whether PXP is ready for userspace use
91  * @pxp: the xe_pxp pointer (can be NULL if PXP is disabled)
92  *
93  * Returns: 0 if PXP is not ready yet, 1 if it is ready, a negative errno value
94  * if PXP is not supported/enabled or if something went wrong in the
95  * initialization of the prerequisites. Note that the return values of this
96  * function follow the uapi (see drm_xe_query_pxp_status), so they can be used
97  * directly in the query ioctl.
98  */
99 int xe_pxp_get_readiness_status(struct xe_pxp *pxp)
100 {
101 	int ret = 0;
102 
103 	if (!xe_pxp_is_enabled(pxp))
104 		return -ENODEV;
105 
106 	/* If the GSC FW is in an error state, PXP will never work */
107 	if (xe_uc_fw_status_to_error(pxp->gt->uc.gsc.fw.status))
108 		return -EIO;
109 
110 	/* Same for HuC FW, but only if the kernel owns HuC-loading (i.e. pre-NVL) */
111 	if (MEDIA_VER(gt_to_xe(pxp->gt)) < 35 &&
112 	    xe_uc_fw_status_to_error(pxp->gt->uc.huc.fw.status))
113 		return -EIO;
114 
115 	guard(xe_pm_runtime)(pxp->xe);
116 
117 	/* PXP requires both HuC loaded and GSC proxy initialized */
118 	if (pxp_prerequisites_done(pxp))
119 		ret = 1;
120 
121 	return ret;
122 }
123 
124 static bool pxp_session_is_in_play(struct xe_pxp *pxp, u32 id)
125 {
126 	struct xe_gt *gt = pxp->gt;
127 
128 	return xe_mmio_read32(&gt->mmio, KCR_SIP) & BIT(id);
129 }
130 
131 static int pxp_wait_for_session_state(struct xe_pxp *pxp, u32 id, bool in_play)
132 {
133 	struct xe_gt *gt = pxp->gt;
134 	u32 mask = BIT(id);
135 
136 	return xe_mmio_wait32(&gt->mmio, KCR_SIP, mask, in_play ? mask : 0,
137 			      250, NULL, false);
138 }
139 
140 static void pxp_invalidate_queues(struct xe_pxp *pxp);
141 
142 static int pxp_terminate_hw(struct xe_pxp *pxp)
143 {
144 	struct xe_gt *gt = pxp->gt;
145 	int ret = 0;
146 
147 	drm_dbg(&pxp->xe->drm, "Terminating PXP\n");
148 
149 	CLASS(xe_force_wake, fw_ref)(gt_to_fw(gt), XE_FW_GT);
150 	if (!xe_force_wake_ref_has_domain(fw_ref.domains, XE_FW_GT))
151 		return -EIO;
152 
153 	/* terminate the hw session */
154 	ret = xe_pxp_submit_session_termination(pxp, ARB_SESSION);
155 	if (ret)
156 		return ret;
157 
158 	ret = pxp_wait_for_session_state(pxp, ARB_SESSION, false);
159 	if (ret)
160 		return ret;
161 
162 	/* Trigger full HW cleanup */
163 	xe_mmio_write32(&gt->mmio, KCR_GLOBAL_TERMINATE, 1);
164 
165 	/* now we can tell the GSC to clean up its own state */
166 	return xe_pxp_submit_session_invalidation(&pxp->gsc_res, ARB_SESSION);
167 }
168 
169 static void mark_termination_in_progress(struct xe_pxp *pxp)
170 {
171 	lockdep_assert_held(&pxp->mutex);
172 
173 	reinit_completion(&pxp->termination);
174 	pxp->status = XE_PXP_TERMINATION_IN_PROGRESS;
175 }
176 
177 static void pxp_terminate(struct xe_pxp *pxp)
178 {
179 	int ret = 0;
180 	struct xe_device *xe = pxp->xe;
181 
182 	if (!wait_for_completion_timeout(&pxp->activation,
183 					 msecs_to_jiffies(PXP_ACTIVATION_TIMEOUT_MS)))
184 		drm_err(&xe->drm, "failed to wait for PXP start before termination\n");
185 
186 	mutex_lock(&pxp->mutex);
187 
188 	if (pxp->status == XE_PXP_ACTIVE)
189 		pxp->key_instance++;
190 
191 	/*
192 	 * we'll mark the status as needing termination on resume, so no need to
193 	 * emit a termination now.
194 	 */
195 	if (pxp->status == XE_PXP_SUSPENDED) {
196 		mutex_unlock(&pxp->mutex);
197 		return;
198 	}
199 
200 	/*
201 	 * If we have a termination already in progress, we need to wait for
202 	 * it to complete before queueing another one. Once the first
203 	 * termination is completed we'll set the state back to
204 	 * NEEDS_TERMINATION and leave it to the pxp start code to issue it.
205 	 */
206 	if (pxp->status == XE_PXP_TERMINATION_IN_PROGRESS) {
207 		pxp->status = XE_PXP_NEEDS_ADDITIONAL_TERMINATION;
208 		mutex_unlock(&pxp->mutex);
209 		return;
210 	}
211 
212 	mark_termination_in_progress(pxp);
213 
214 	mutex_unlock(&pxp->mutex);
215 
216 	pxp_invalidate_queues(pxp);
217 
218 	ret = pxp_terminate_hw(pxp);
219 	if (ret) {
220 		drm_err(&xe->drm, "PXP termination failed: %pe\n", ERR_PTR(ret));
221 		mutex_lock(&pxp->mutex);
222 		pxp->status = XE_PXP_ERROR;
223 		complete_all(&pxp->termination);
224 		mutex_unlock(&pxp->mutex);
225 	}
226 }
227 
228 static void pxp_terminate_complete(struct xe_pxp *pxp)
229 {
230 	/*
231 	 * We expect PXP to be in one of 3 states when we get here:
232 	 * - XE_PXP_TERMINATION_IN_PROGRESS: a single termination event was
233 	 * requested and it is now completing, so we're ready to start.
234 	 * - XE_PXP_NEEDS_ADDITIONAL_TERMINATION: a second termination was
235 	 * requested while the first one was still being processed.
236 	 * - XE_PXP_SUSPENDED: PXP is now suspended, so we defer everything to
237 	 * when we come back on resume.
238 	 */
239 	mutex_lock(&pxp->mutex);
240 
241 	switch (pxp->status) {
242 	case XE_PXP_TERMINATION_IN_PROGRESS:
243 		pxp->status = XE_PXP_READY_TO_START;
244 		break;
245 	case XE_PXP_NEEDS_ADDITIONAL_TERMINATION:
246 		pxp->status = XE_PXP_NEEDS_TERMINATION;
247 		break;
248 	case XE_PXP_SUSPENDED:
249 		/* Nothing to do */
250 		break;
251 	default:
252 		drm_err(&pxp->xe->drm,
253 			"PXP termination complete while status was %u\n",
254 			pxp->status);
255 	}
256 
257 	complete_all(&pxp->termination);
258 
259 	mutex_unlock(&pxp->mutex);
260 }
261 
262 static void pxp_irq_work(struct work_struct *work)
263 {
264 	struct xe_pxp *pxp = container_of(work, typeof(*pxp), irq.work);
265 	struct xe_device *xe = pxp->xe;
266 	u32 events = 0;
267 
268 	spin_lock_irq(&xe->irq.lock);
269 	events = pxp->irq.events;
270 	pxp->irq.events = 0;
271 	spin_unlock_irq(&xe->irq.lock);
272 
273 	if (!events)
274 		return;
275 
276 	/*
277 	 * If we're processing a termination irq while suspending then don't
278 	 * bother, we're going to re-init everything on resume anyway.
279 	 */
280 	if ((events & PXP_TERMINATION_REQUEST) && !xe_pm_runtime_get_if_active(xe))
281 		return;
282 
283 	if (events & PXP_TERMINATION_REQUEST) {
284 		events &= ~PXP_TERMINATION_COMPLETE;
285 		pxp_terminate(pxp);
286 	}
287 
288 	if (events & PXP_TERMINATION_COMPLETE)
289 		pxp_terminate_complete(pxp);
290 
291 	if (events & PXP_TERMINATION_REQUEST)
292 		xe_pm_runtime_put(xe);
293 }
294 
295 /**
296  * xe_pxp_irq_handler - Handles PXP interrupts.
297  * @xe: the xe_device structure
298  * @iir: interrupt vector
299  */
300 void xe_pxp_irq_handler(struct xe_device *xe, u16 iir)
301 {
302 	struct xe_pxp *pxp = xe->pxp;
303 
304 	if (!xe_pxp_is_enabled(pxp)) {
305 		drm_err(&xe->drm, "PXP irq 0x%x received with PXP disabled!\n", iir);
306 		return;
307 	}
308 
309 	lockdep_assert_held(&xe->irq.lock);
310 
311 	if (unlikely(!iir))
312 		return;
313 
314 	if (iir & (KCR_PXP_STATE_TERMINATED_INTERRUPT |
315 		   KCR_APP_TERMINATED_PER_FW_REQ_INTERRUPT))
316 		pxp->irq.events |= PXP_TERMINATION_REQUEST;
317 
318 	if (iir & KCR_PXP_STATE_RESET_COMPLETE_INTERRUPT)
319 		pxp->irq.events |= PXP_TERMINATION_COMPLETE;
320 
321 	if (pxp->irq.events)
322 		queue_work(pxp->irq.wq, &pxp->irq.work);
323 }
324 
325 static int kcr_pxp_set_status(const struct xe_pxp *pxp, bool enable)
326 {
327 	u32 val = enable ? REG_MASKED_FIELD_ENABLE(KCR_INIT_ALLOW_DISPLAY_ME_WRITES) :
328 		  REG_MASKED_FIELD_DISABLE(KCR_INIT_ALLOW_DISPLAY_ME_WRITES);
329 
330 	CLASS(xe_force_wake, fw_ref)(gt_to_fw(pxp->gt), XE_FW_GT);
331 	if (!xe_force_wake_ref_has_domain(fw_ref.domains, XE_FW_GT))
332 		return -EIO;
333 
334 	xe_mmio_write32(&pxp->gt->mmio, KCR_INIT, val);
335 
336 	return 0;
337 }
338 
339 static int kcr_pxp_enable(const struct xe_pxp *pxp)
340 {
341 	return kcr_pxp_set_status(pxp, true);
342 }
343 
344 static int kcr_pxp_disable(const struct xe_pxp *pxp)
345 {
346 	return kcr_pxp_set_status(pxp, false);
347 }
348 
349 static void pxp_fini(void *arg)
350 {
351 	struct xe_pxp *pxp = arg;
352 
353 	destroy_workqueue(pxp->irq.wq);
354 	xe_pxp_destroy_execution_resources(pxp);
355 
356 	/* no need to explicitly disable KCR since we're going to do an FLR */
357 }
358 
359 /**
360  * xe_pxp_init - initialize PXP support
361  * @xe: the xe_device structure
362  *
363  * Initialize the HW state and allocate the objects required for PXP support.
364  * Note that some of the requirement for PXP support (GSC proxy init, HuC auth)
365  * are performed asynchronously as part of the GSC init. PXP can only be used
366  * after both this function and the async worker have completed.
367  *
368  * Returns 0 if PXP is not supported or if PXP initialization is successful,
369  * other errno value if there is an error during the init.
370  */
371 int xe_pxp_init(struct xe_device *xe)
372 {
373 	struct xe_gt *gt = xe->tiles[0].media_gt;
374 	bool gsc_ok, huc_ok;
375 	struct xe_pxp *pxp;
376 	int err;
377 
378 	if (!xe_pxp_is_supported(xe))
379 		return 0;
380 
381 	/* we only support PXP on single tile devices with a media GT */
382 	if (xe->info.tile_count > 1 || !gt)
383 		return 0;
384 
385 	/* The GSCCS is required for submissions to the GSC FW */
386 	if (!(gt->info.engine_mask & BIT(XE_HW_ENGINE_GSCCS0)))
387 		return 0;
388 
389 	/* PXP requires GSC FW to be available. Pre-NVL it also requires HuC FW */
390 	gsc_ok = xe_uc_fw_is_loadable(&gt->uc.gsc.fw);
391 	huc_ok = MEDIA_VER(xe) >= 35 || xe_uc_fw_is_loadable(&gt->uc.huc.fw);
392 
393 	if (!gsc_ok || !huc_ok) {
394 		drm_info(&xe->drm, "Skipping PXP due to unsatisfied FW deps - GSC=%s, HuC=%s\n",
395 			 str_yes_no(gsc_ok),
396 			 MEDIA_VER(xe) >= 35 ? "not needed" : str_yes_no(huc_ok));
397 		return 0;
398 	}
399 
400 	/*
401 	 * On PTL, older GSC FWs have a bug that can cause them to crash during
402 	 * PXP invalidation events, which leads to a complete loss of power
403 	 * management on the media GT. Therefore, we can't use PXP on FWs that
404 	 * have this bug, which was fixed in PTL GSC build 1396.
405 	 */
406 	if (xe->info.platform == XE_PANTHERLAKE &&
407 	    gt->uc.gsc.fw.versions.found[XE_UC_FW_VER_RELEASE].build < 1396) {
408 		drm_info(&xe->drm, "PXP requires PTL GSC build 1396 or newer\n");
409 		return 0;
410 	}
411 
412 	pxp = drmm_kzalloc(&xe->drm, sizeof(struct xe_pxp), GFP_KERNEL);
413 	if (!pxp) {
414 		err = -ENOMEM;
415 		goto out;
416 	}
417 
418 	INIT_LIST_HEAD(&pxp->queues.list);
419 	spin_lock_init(&pxp->queues.lock);
420 	INIT_WORK(&pxp->irq.work, pxp_irq_work);
421 	pxp->xe = xe;
422 	pxp->gt = gt;
423 
424 	pxp->key_instance = 1;
425 	pxp->last_suspend_key_instance = 1;
426 
427 	/*
428 	 * we'll use the completions to check if there is an action pending,
429 	 * so we start them as completed and we reinit it when an action is
430 	 * triggered.
431 	 */
432 	init_completion(&pxp->activation);
433 	init_completion(&pxp->termination);
434 	complete_all(&pxp->termination);
435 	complete_all(&pxp->activation);
436 
437 	mutex_init(&pxp->mutex);
438 
439 	pxp->irq.wq = alloc_ordered_workqueue("pxp-wq", 0);
440 	if (!pxp->irq.wq) {
441 		err = -ENOMEM;
442 		goto out_free;
443 	}
444 
445 	err = kcr_pxp_enable(pxp);
446 	if (err)
447 		goto out_wq;
448 
449 	err = xe_pxp_allocate_execution_resources(pxp);
450 	if (err)
451 		goto out_kcr_disable;
452 
453 	xe->pxp = pxp;
454 
455 	return devm_add_action_or_reset(xe->drm.dev, pxp_fini, pxp);
456 
457 out_kcr_disable:
458 	kcr_pxp_disable(pxp);
459 out_wq:
460 	destroy_workqueue(pxp->irq.wq);
461 out_free:
462 	drmm_kfree(&xe->drm, pxp);
463 out:
464 	drm_err(&xe->drm, "PXP initialization failed: %pe\n", ERR_PTR(err));
465 	return err;
466 }
467 
468 static int __pxp_start_arb_session(struct xe_pxp *pxp)
469 {
470 	int ret;
471 
472 	CLASS(xe_force_wake, fw_ref)(gt_to_fw(pxp->gt), XE_FW_GT);
473 	if (!xe_force_wake_ref_has_domain(fw_ref.domains, XE_FW_GT))
474 		return -EIO;
475 
476 	if (pxp_session_is_in_play(pxp, ARB_SESSION))
477 		return -EEXIST;
478 
479 	ret = xe_pxp_submit_session_init(&pxp->gsc_res, ARB_SESSION);
480 	if (ret) {
481 		drm_err(&pxp->xe->drm, "Failed to init PXP arb session: %pe\n", ERR_PTR(ret));
482 		return ret;
483 	}
484 
485 	ret = pxp_wait_for_session_state(pxp, ARB_SESSION, true);
486 	if (ret) {
487 		drm_err(&pxp->xe->drm, "PXP ARB session failed to go in play%pe\n", ERR_PTR(ret));
488 		return ret;
489 	}
490 
491 	drm_dbg(&pxp->xe->drm, "PXP ARB session is active\n");
492 	return 0;
493 }
494 
495 /**
496  * xe_pxp_exec_queue_set_type - Mark a queue as using PXP
497  * @pxp: the xe->pxp pointer (it will be NULL if PXP is disabled)
498  * @q: the queue to mark as using PXP
499  * @type: the type of PXP session this queue will use
500  *
501  * Returns 0 if the selected PXP type is supported, -ENODEV otherwise.
502  */
503 int xe_pxp_exec_queue_set_type(struct xe_pxp *pxp, struct xe_exec_queue *q, u8 type)
504 {
505 	if (!xe_pxp_is_enabled(pxp))
506 		return -ENODEV;
507 
508 	/* we only support HWDRM sessions right now */
509 	xe_assert(pxp->xe, type == DRM_XE_PXP_TYPE_HWDRM);
510 
511 	q->pxp.type = type;
512 
513 	return 0;
514 }
515 
516 static int __exec_queue_add(struct xe_pxp *pxp, struct xe_exec_queue *q)
517 {
518 	int ret = 0;
519 
520 	/*
521 	 * A queue can be added to the list only if the PXP is in active status,
522 	 * otherwise the termination might not handle it correctly.
523 	 */
524 	mutex_lock(&pxp->mutex);
525 
526 	if (pxp->status == XE_PXP_ACTIVE) {
527 		spin_lock_irq(&pxp->queues.lock);
528 		list_add_tail(&q->pxp.link, &pxp->queues.list);
529 		spin_unlock_irq(&pxp->queues.lock);
530 	} else if (pxp->status == XE_PXP_ERROR || pxp->status == XE_PXP_SUSPENDED) {
531 		ret = -EIO;
532 	} else {
533 		ret = -EBUSY; /* try again later */
534 	}
535 
536 	mutex_unlock(&pxp->mutex);
537 
538 	return ret;
539 }
540 
541 static int pxp_start(struct xe_pxp *pxp, u8 type)
542 {
543 	int ret = 0;
544 	bool restart;
545 
546 	if (!xe_pxp_is_enabled(pxp))
547 		return -ENODEV;
548 
549 	/* we only support HWDRM sessions right now */
550 	xe_assert(pxp->xe, type == DRM_XE_PXP_TYPE_HWDRM);
551 
552 	/* get_readiness_status() returns 0 for in-progress and 1 for done */
553 	ret = xe_pxp_get_readiness_status(pxp);
554 	if (ret <= 0)
555 		return ret ?: -EBUSY;
556 
557 	ret = 0;
558 
559 wait_for_idle:
560 	/*
561 	 * if there is an action in progress, wait for it. We need to wait
562 	 * outside the lock because the completion is done from within the lock.
563 	 * Note that the two actions should never be pending at the same time.
564 	 */
565 	if (!wait_for_completion_timeout(&pxp->termination,
566 					 msecs_to_jiffies(PXP_TERMINATION_TIMEOUT_MS)))
567 		return -ETIMEDOUT;
568 
569 	if (!wait_for_completion_timeout(&pxp->activation,
570 					 msecs_to_jiffies(PXP_ACTIVATION_TIMEOUT_MS)))
571 		return -ETIMEDOUT;
572 
573 	restart = false;
574 
575 	mutex_lock(&pxp->mutex);
576 
577 	/* If PXP is not already active, turn it on */
578 	switch (pxp->status) {
579 	case XE_PXP_ERROR:
580 		ret = -EIO;
581 		goto out_unlock;
582 	case XE_PXP_ACTIVE:
583 		goto out_unlock;
584 	case XE_PXP_READY_TO_START:
585 		pxp->status = XE_PXP_START_IN_PROGRESS;
586 		reinit_completion(&pxp->activation);
587 		break;
588 	case XE_PXP_START_IN_PROGRESS:
589 		/* If a start is in progress then the completion must not be done */
590 		XE_WARN_ON(completion_done(&pxp->activation));
591 		restart = true;
592 		goto out_unlock;
593 	case XE_PXP_NEEDS_TERMINATION:
594 		mark_termination_in_progress(pxp);
595 		break;
596 	case XE_PXP_TERMINATION_IN_PROGRESS:
597 	case XE_PXP_NEEDS_ADDITIONAL_TERMINATION:
598 		/* If a termination is in progress then the completion must not be done */
599 		XE_WARN_ON(completion_done(&pxp->termination));
600 		restart = true;
601 		goto out_unlock;
602 	case XE_PXP_SUSPENDED:
603 	default:
604 		drm_err(&pxp->xe->drm, "unexpected state during PXP start: %u\n", pxp->status);
605 		ret = -EIO;
606 		goto out_unlock;
607 	}
608 
609 	mutex_unlock(&pxp->mutex);
610 
611 	if (!completion_done(&pxp->termination)) {
612 		ret = pxp_terminate_hw(pxp);
613 		if (ret) {
614 			drm_err(&pxp->xe->drm, "PXP termination failed before start\n");
615 			mutex_lock(&pxp->mutex);
616 			pxp->status = XE_PXP_ERROR;
617 			complete_all(&pxp->termination);
618 
619 			goto out_unlock;
620 		}
621 
622 		goto wait_for_idle;
623 	}
624 
625 	/* All the cases except for start should have exited earlier */
626 	XE_WARN_ON(completion_done(&pxp->activation));
627 	ret = __pxp_start_arb_session(pxp);
628 
629 	mutex_lock(&pxp->mutex);
630 
631 	complete_all(&pxp->activation);
632 
633 	/*
634 	 * Any other process should wait until the state goes away from
635 	 * XE_PXP_START_IN_PROGRESS, so if the state is not that something went
636 	 * wrong. Mark the status as needing termination and try again.
637 	 */
638 	if (pxp->status != XE_PXP_START_IN_PROGRESS) {
639 		drm_err(&pxp->xe->drm, "unexpected state after PXP start: %u\n", pxp->status);
640 		pxp->status = XE_PXP_NEEDS_TERMINATION;
641 		restart = true;
642 		goto out_unlock;
643 	}
644 
645 	/* If everything went ok, update the status and add the queue to the list */
646 	if (!ret)
647 		pxp->status = XE_PXP_ACTIVE;
648 	else
649 		pxp->status = XE_PXP_ERROR;
650 
651 out_unlock:
652 	mutex_unlock(&pxp->mutex);
653 
654 	if (restart)
655 		goto wait_for_idle;
656 
657 	return ret;
658 }
659 
660 /**
661  * xe_pxp_exec_queue_add - add a queue to the PXP list
662  * @pxp: the xe->pxp pointer (it will be NULL if PXP is disabled)
663  * @q: the queue to add to the list
664  *
665  * If PXP is enabled and the prerequisites are done, start the PXP default
666  * session (if not already running) and add the queue to the PXP list.
667  *
668  * Returns 0 if the PXP session is running and the queue is in the list,
669  * -ENODEV if PXP is disabled, -EBUSY if the PXP prerequisites are not done,
670  * other errno value if something goes wrong during the session start.
671  */
672 int xe_pxp_exec_queue_add(struct xe_pxp *pxp, struct xe_exec_queue *q)
673 {
674 	int ret;
675 
676 	if (!xe_pxp_is_enabled(pxp))
677 		return -ENODEV;
678 
679 	/*
680 	 * Runtime suspend kills PXP, so we take a reference to prevent it from
681 	 * happening while we have active queues that use PXP
682 	 */
683 	xe_pm_runtime_get(pxp->xe);
684 
685 start:
686 	ret = pxp_start(pxp, q->pxp.type);
687 
688 	if (!ret) {
689 		ret = __exec_queue_add(pxp, q);
690 		if (ret == -EBUSY)
691 			goto start;
692 	}
693 
694 	/*
695 	 * in the successful case the PM ref is released from
696 	 * xe_pxp_exec_queue_remove
697 	 */
698 	if (ret)
699 		xe_pm_runtime_put(pxp->xe);
700 
701 	return ret;
702 }
703 ALLOW_ERROR_INJECTION(xe_pxp_exec_queue_add, ERRNO);
704 
705 static void __pxp_exec_queue_remove(struct xe_pxp *pxp, struct xe_exec_queue *q, bool lock)
706 {
707 	bool need_pm_put = false;
708 
709 	if (!xe_pxp_is_enabled(pxp))
710 		return;
711 
712 	if (lock)
713 		spin_lock_irq(&pxp->queues.lock);
714 
715 	if (!list_empty(&q->pxp.link)) {
716 		list_del_init(&q->pxp.link);
717 		need_pm_put = true;
718 	}
719 
720 	q->pxp.type = DRM_XE_PXP_TYPE_NONE;
721 
722 	if (lock)
723 		spin_unlock_irq(&pxp->queues.lock);
724 
725 	if (need_pm_put)
726 		xe_pm_runtime_put(pxp->xe);
727 }
728 
729 /**
730  * xe_pxp_exec_queue_remove - remove a queue from the PXP list
731  * @pxp: the xe->pxp pointer (it will be NULL if PXP is disabled)
732  * @q: the queue to remove from the list
733  *
734  * If PXP is enabled and the exec_queue is in the list, the queue will be
735  * removed from the list and its PM reference will be released. It is safe to
736  * call this function multiple times for the same queue.
737  */
738 void xe_pxp_exec_queue_remove(struct xe_pxp *pxp, struct xe_exec_queue *q)
739 {
740 	__pxp_exec_queue_remove(pxp, q, true);
741 }
742 
743 static void pxp_invalidate_queues(struct xe_pxp *pxp)
744 {
745 	struct xe_exec_queue *tmp, *q;
746 	LIST_HEAD(to_clean);
747 
748 	spin_lock_irq(&pxp->queues.lock);
749 
750 	list_for_each_entry_safe(q, tmp, &pxp->queues.list, pxp.link) {
751 		q = xe_exec_queue_get_unless_zero(q);
752 		if (!q)
753 			continue;
754 
755 		list_move_tail(&q->pxp.link, &to_clean);
756 	}
757 	spin_unlock_irq(&pxp->queues.lock);
758 
759 	list_for_each_entry_safe(q, tmp, &to_clean, pxp.link) {
760 		drm_dbg(&pxp->xe->drm,
761 			"Killing queue due to PXP termination: eclass=%s, guc_id=%d\n",
762 			xe_hw_engine_class_to_str(q->class), q->guc->id);
763 
764 		xe_exec_queue_kill(q);
765 
766 		/*
767 		 * We hold a ref to the queue so there is no risk of racing with
768 		 * the calls to exec_queue_remove coming from exec_queue_destroy.
769 		 */
770 		__pxp_exec_queue_remove(pxp, q, false);
771 
772 		xe_exec_queue_put(q);
773 	}
774 }
775 
776 /**
777  * xe_pxp_key_assign - mark a BO as using the current PXP key iteration
778  * @pxp: the xe->pxp pointer (it will be NULL if PXP is disabled)
779  * @bo: the BO to mark
780  *
781  * Returns: -ENODEV if PXP is disabled, 0 otherwise.
782  */
783 int xe_pxp_key_assign(struct xe_pxp *pxp, struct xe_bo *bo)
784 {
785 	if (!xe_pxp_is_enabled(pxp))
786 		return -ENODEV;
787 
788 	xe_assert(pxp->xe, !bo->pxp_key_instance);
789 
790 	/*
791 	 * Note that the PXP key handling is inherently racey, because the key
792 	 * can theoretically change at any time (although it's unlikely to do
793 	 * so without triggers), even right after we copy it. Taking a lock
794 	 * wouldn't help because the value might still change as soon as we
795 	 * release the lock.
796 	 * Userspace needs to handle the fact that their BOs can go invalid at
797 	 * any point.
798 	 */
799 	bo->pxp_key_instance = pxp->key_instance;
800 
801 	return 0;
802 }
803 
804 /**
805  * xe_pxp_bo_key_check - check if the key used by a xe_bo is valid
806  * @pxp: the xe->pxp pointer (it will be NULL if PXP is disabled)
807  * @bo: the BO we want to check
808  *
809  * Checks whether a BO was encrypted with the current key or an obsolete one.
810  *
811  * Returns: 0 if the key is valid, -ENODEV if PXP is disabled, -EINVAL if the
812  * BO is not using PXP,  -ENOEXEC if the key is not valid.
813  */
814 int xe_pxp_bo_key_check(struct xe_pxp *pxp, struct xe_bo *bo)
815 {
816 	if (!xe_pxp_is_enabled(pxp))
817 		return -ENODEV;
818 
819 	if (!xe_bo_is_protected(bo))
820 		return -EINVAL;
821 
822 	xe_assert(pxp->xe, bo->pxp_key_instance);
823 
824 	/*
825 	 * Note that the PXP key handling is inherently racey, because the key
826 	 * can theoretically change at any time (although it's unlikely to do
827 	 * so without triggers), even right after we check it. Taking a lock
828 	 * wouldn't help because the value might still change as soon as we
829 	 * release the lock.
830 	 * We mitigate the risk by checking the key at multiple points (on each
831 	 * submission involving the BO and right before flipping it on the
832 	 * display), but there is still a very small chance that we could
833 	 * operate on an invalid BO for a single submission or a single frame
834 	 * flip. This is a compromise made to protect the encrypted data (which
835 	 * is what the key termination is for).
836 	 */
837 	if (bo->pxp_key_instance != pxp->key_instance)
838 		return -ENOEXEC;
839 
840 	return 0;
841 }
842 
843 /**
844  * xe_pxp_obj_key_check - check if the key used by a drm_gem_obj is valid
845  * @obj: the drm_gem_obj we want to check
846  *
847  * Checks whether a drm_gem_obj was encrypted with the current key or an
848  * obsolete one.
849  *
850  * Returns: 0 if the key is valid, -ENODEV if PXP is disabled, -EINVAL if the
851  * obj is not using PXP,  -ENOEXEC if the key is not valid.
852  */
853 int xe_pxp_obj_key_check(struct drm_gem_object *obj)
854 {
855 	struct xe_bo *bo = gem_to_xe_bo(obj);
856 	struct xe_device *xe = xe_bo_device(bo);
857 	struct xe_pxp *pxp = xe->pxp;
858 
859 	return xe_pxp_bo_key_check(pxp, bo);
860 }
861 
862 /**
863  * xe_pxp_pm_suspend - prepare PXP for HW suspend
864  * @pxp: the xe->pxp pointer (it will be NULL if PXP is disabled)
865  *
866  * Makes sure all PXP actions have completed and invalidates all PXP queues
867  * and objects before we go into a suspend state.
868  *
869  * Returns: 0 if successful, a negative errno value otherwise.
870  */
871 int xe_pxp_pm_suspend(struct xe_pxp *pxp)
872 {
873 	bool needs_queue_inval = false;
874 	int ret = 0;
875 
876 	if (!xe_pxp_is_enabled(pxp))
877 		return 0;
878 
879 wait_for_activation:
880 	if (!wait_for_completion_timeout(&pxp->activation,
881 					 msecs_to_jiffies(PXP_ACTIVATION_TIMEOUT_MS)))
882 		ret = -ETIMEDOUT;
883 
884 	mutex_lock(&pxp->mutex);
885 
886 	switch (pxp->status) {
887 	case XE_PXP_ERROR:
888 	case XE_PXP_READY_TO_START:
889 	case XE_PXP_SUSPENDED:
890 	case XE_PXP_TERMINATION_IN_PROGRESS:
891 	case XE_PXP_NEEDS_ADDITIONAL_TERMINATION:
892 		/*
893 		 * If PXP is not running there is nothing to cleanup. If there
894 		 * is a termination pending then no need to issue another one.
895 		 */
896 		break;
897 	case XE_PXP_START_IN_PROGRESS:
898 		mutex_unlock(&pxp->mutex);
899 		goto wait_for_activation;
900 	case XE_PXP_NEEDS_TERMINATION:
901 		/* If PXP was never used we can skip the cleanup */
902 		if (pxp->key_instance == pxp->last_suspend_key_instance)
903 			break;
904 		fallthrough;
905 	case XE_PXP_ACTIVE:
906 		pxp->key_instance++;
907 		needs_queue_inval = true;
908 		break;
909 	}
910 
911 	/*
912 	 * We set this even if we were in error state, hoping the suspend clears
913 	 * the error. Worse case we fail again and go in error state again.
914 	 */
915 	pxp->status = XE_PXP_SUSPENDED;
916 
917 	mutex_unlock(&pxp->mutex);
918 
919 	if (needs_queue_inval)
920 		pxp_invalidate_queues(pxp);
921 
922 	/*
923 	 * if there is a termination in progress, wait for it.
924 	 * We need to wait outside the lock because the completion is done from
925 	 * within the lock
926 	 */
927 	if (!wait_for_completion_timeout(&pxp->termination,
928 					 msecs_to_jiffies(PXP_TERMINATION_TIMEOUT_MS)))
929 		ret = -ETIMEDOUT;
930 
931 	pxp->last_suspend_key_instance = pxp->key_instance;
932 
933 	return ret;
934 }
935 
936 /**
937  * xe_pxp_pm_resume - re-init PXP after HW suspend
938  * @pxp: the xe->pxp pointer (it will be NULL if PXP is disabled)
939  */
940 void xe_pxp_pm_resume(struct xe_pxp *pxp)
941 {
942 	int err;
943 
944 	if (!xe_pxp_is_enabled(pxp))
945 		return;
946 
947 	err = kcr_pxp_enable(pxp);
948 
949 	mutex_lock(&pxp->mutex);
950 
951 	xe_assert(pxp->xe, pxp->status == XE_PXP_SUSPENDED);
952 
953 	if (err)
954 		pxp->status = XE_PXP_ERROR;
955 	else
956 		pxp->status = XE_PXP_NEEDS_TERMINATION;
957 
958 	mutex_unlock(&pxp->mutex);
959 }
960