xref: /linux/drivers/gpu/drm/xe/xe_device.c (revision b6f466c509ad2f390b3fc91cd0de4783554f5f98)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2021 Intel Corporation
4  */
5 
6 #include "xe_device.h"
7 
8 #include <linux/aperture.h>
9 #include <linux/delay.h>
10 #include <linux/fault-inject.h>
11 #include <linux/units.h>
12 
13 #include <drm/drm_client.h>
14 #include <drm/drm_gem_ttm_helper.h>
15 #include <drm/drm_ioctl.h>
16 #include <drm/drm_managed.h>
17 #include <drm/drm_pagemap_util.h>
18 #include <drm/drm_print.h>
19 #include <kunit/static_stub.h>
20 #include <uapi/drm/xe_drm.h>
21 
22 #include "display/xe_display.h"
23 #include "instructions/xe_gpu_commands.h"
24 #include "regs/xe_gt_regs.h"
25 #include "regs/xe_regs.h"
26 #include "xe_bo.h"
27 #include "xe_bo_evict.h"
28 #include "xe_configfs.h"
29 #include "xe_debugfs.h"
30 #include "xe_defaults.h"
31 #include "xe_devcoredump.h"
32 #include "xe_device_sysfs.h"
33 #include "xe_dma_buf.h"
34 #include "xe_drm_client.h"
35 #include "xe_drv.h"
36 #include "xe_exec.h"
37 #include "xe_exec_queue.h"
38 #include "xe_force_wake.h"
39 #include "xe_ggtt.h"
40 #include "xe_gt.h"
41 #include "xe_gt_mcr.h"
42 #include "xe_gt_printk.h"
43 #include "xe_gt_sriov_vf.h"
44 #include "xe_guc.h"
45 #include "xe_guc_pc.h"
46 #include "xe_hw_engine_group.h"
47 #include "xe_hwmon.h"
48 #include "xe_i2c.h"
49 #include "xe_irq.h"
50 #include "xe_late_bind_fw.h"
51 #include "xe_mmio.h"
52 #include "xe_module.h"
53 #include "xe_nvm.h"
54 #include "xe_oa.h"
55 #include "xe_observation.h"
56 #include "xe_pagefault.h"
57 #include "xe_pat.h"
58 #include "xe_pcode.h"
59 #include "xe_pm.h"
60 #include "xe_pmu.h"
61 #include "xe_psmi.h"
62 #include "xe_pxp.h"
63 #include "xe_query.h"
64 #include "xe_ras.h"
65 #include "xe_shrinker.h"
66 #include "xe_soc_remapper.h"
67 #include "xe_survivability_mode.h"
68 #include "xe_sriov.h"
69 #include "xe_svm.h"
70 #include "xe_sysctrl.h"
71 #include "xe_tile.h"
72 #include "xe_ttm_stolen_mgr.h"
73 #include "xe_ttm_sys_mgr.h"
74 #include "xe_vm.h"
75 #include "xe_vm_madvise.h"
76 #include "xe_vram.h"
77 #include "xe_vram_types.h"
78 #include "xe_vsec.h"
79 #include "xe_wait_user_fence.h"
80 #include "xe_wa.h"
81 
82 #include <generated/xe_device_wa_oob.h>
83 #include <generated/xe_wa_oob.h>
84 
85 static int xe_file_open(struct drm_device *dev, struct drm_file *file)
86 {
87 	struct xe_device *xe = to_xe_device(dev);
88 	struct xe_drm_client *client;
89 	struct xe_file *xef;
90 	int ret = -ENOMEM;
91 	struct task_struct *task = NULL;
92 
93 	xef = kzalloc_obj(*xef);
94 	if (!xef)
95 		return ret;
96 
97 	client = xe_drm_client_alloc();
98 	if (!client) {
99 		kfree(xef);
100 		return ret;
101 	}
102 
103 	xef->drm = file;
104 	xef->client = client;
105 	xef->xe = xe;
106 
107 	mutex_init(&xef->vm.lock);
108 	xa_init_flags(&xef->vm.xa, XA_FLAGS_ALLOC1);
109 
110 	mutex_init(&xef->exec_queue.lock);
111 	xa_init_flags(&xef->exec_queue.xa, XA_FLAGS_ALLOC1);
112 
113 	file->driver_priv = xef;
114 	kref_init(&xef->refcount);
115 
116 	task = get_pid_task(rcu_access_pointer(file->pid), PIDTYPE_PID);
117 	if (task) {
118 		xef->process_name = kstrdup(task->comm, GFP_KERNEL);
119 		xef->pid = task->pid;
120 		put_task_struct(task);
121 	}
122 
123 	return 0;
124 }
125 
126 static void xe_file_destroy(struct kref *ref)
127 {
128 	struct xe_file *xef = container_of(ref, struct xe_file, refcount);
129 
130 	xa_destroy(&xef->exec_queue.xa);
131 	mutex_destroy(&xef->exec_queue.lock);
132 	xa_destroy(&xef->vm.xa);
133 	mutex_destroy(&xef->vm.lock);
134 
135 	xe_drm_client_put(xef->client);
136 	kfree(xef->process_name);
137 	kfree(xef);
138 }
139 
140 /**
141  * xe_file_get() - Take a reference to the xe file object
142  * @xef: Pointer to the xe file
143  *
144  * Anyone with a pointer to xef must take a reference to the xe file
145  * object using this call.
146  *
147  * Return: xe file pointer
148  */
149 struct xe_file *xe_file_get(struct xe_file *xef)
150 {
151 	kref_get(&xef->refcount);
152 	return xef;
153 }
154 
155 /**
156  * xe_file_put() - Drop a reference to the xe file object
157  * @xef: Pointer to the xe file
158  *
159  * Used to drop reference to the xef object
160  */
161 void xe_file_put(struct xe_file *xef)
162 {
163 	kref_put(&xef->refcount, xe_file_destroy);
164 }
165 
166 static void xe_file_close(struct drm_device *dev, struct drm_file *file)
167 {
168 	struct xe_device *xe = to_xe_device(dev);
169 	struct xe_file *xef = file->driver_priv;
170 	struct xe_vm *vm;
171 	struct xe_exec_queue *q;
172 	unsigned long idx;
173 
174 	guard(xe_pm_runtime)(xe);
175 
176 	/*
177 	 * No need for exec_queue.lock here as there is no contention for it
178 	 * when FD is closing as IOCTLs presumably can't be modifying the
179 	 * xarray. Taking exec_queue.lock here causes undue dependency on
180 	 * vm->lock taken during xe_exec_queue_kill().
181 	 */
182 	xa_for_each(&xef->exec_queue.xa, idx, q) {
183 		if (q->vm && q->hwe->hw_engine_group)
184 			xe_hw_engine_group_del_exec_queue(q->hwe->hw_engine_group, q);
185 		xe_exec_queue_kill(q);
186 		xe_exec_queue_put(q);
187 	}
188 	xa_for_each(&xef->vm.xa, idx, vm)
189 		xe_vm_close_and_put(vm);
190 
191 	xe_file_put(xef);
192 }
193 
194 static const struct drm_ioctl_desc xe_ioctls[] = {
195 	DRM_IOCTL_DEF_DRV(XE_DEVICE_QUERY, xe_query_ioctl, DRM_RENDER_ALLOW),
196 	DRM_IOCTL_DEF_DRV(XE_GEM_CREATE, xe_gem_create_ioctl, DRM_RENDER_ALLOW),
197 	DRM_IOCTL_DEF_DRV(XE_GEM_MMAP_OFFSET, xe_gem_mmap_offset_ioctl,
198 			  DRM_RENDER_ALLOW),
199 	DRM_IOCTL_DEF_DRV(XE_VM_CREATE, xe_vm_create_ioctl, DRM_RENDER_ALLOW),
200 	DRM_IOCTL_DEF_DRV(XE_VM_DESTROY, xe_vm_destroy_ioctl, DRM_RENDER_ALLOW),
201 	DRM_IOCTL_DEF_DRV(XE_VM_BIND, xe_vm_bind_ioctl, DRM_RENDER_ALLOW),
202 	DRM_IOCTL_DEF_DRV(XE_EXEC, xe_exec_ioctl, DRM_RENDER_ALLOW),
203 	DRM_IOCTL_DEF_DRV(XE_EXEC_QUEUE_CREATE, xe_exec_queue_create_ioctl,
204 			  DRM_RENDER_ALLOW),
205 	DRM_IOCTL_DEF_DRV(XE_EXEC_QUEUE_DESTROY, xe_exec_queue_destroy_ioctl,
206 			  DRM_RENDER_ALLOW),
207 	DRM_IOCTL_DEF_DRV(XE_EXEC_QUEUE_GET_PROPERTY, xe_exec_queue_get_property_ioctl,
208 			  DRM_RENDER_ALLOW),
209 	DRM_IOCTL_DEF_DRV(XE_WAIT_USER_FENCE, xe_wait_user_fence_ioctl,
210 			  DRM_RENDER_ALLOW),
211 	DRM_IOCTL_DEF_DRV(XE_OBSERVATION, xe_observation_ioctl, DRM_RENDER_ALLOW),
212 	DRM_IOCTL_DEF_DRV(XE_MADVISE, xe_vm_madvise_ioctl, DRM_RENDER_ALLOW),
213 	DRM_IOCTL_DEF_DRV(XE_VM_QUERY_MEM_RANGE_ATTRS, xe_vm_query_vmas_attrs_ioctl,
214 			  DRM_RENDER_ALLOW),
215 	DRM_IOCTL_DEF_DRV(XE_EXEC_QUEUE_SET_PROPERTY, xe_exec_queue_set_property_ioctl,
216 			  DRM_RENDER_ALLOW),
217 	DRM_IOCTL_DEF_DRV(XE_VM_GET_PROPERTY, xe_vm_get_property_ioctl,
218 			  DRM_RENDER_ALLOW),
219 };
220 
221 static long xe_drm_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
222 {
223 	struct drm_file *file_priv = file->private_data;
224 	struct xe_device *xe = to_xe_device(file_priv->minor->dev);
225 	long ret;
226 
227 	if (xe_device_wedged(xe))
228 		return -ECANCELED;
229 
230 	ACQUIRE(xe_pm_runtime_ioctl, pm)(xe);
231 	ret = ACQUIRE_ERR(xe_pm_runtime_ioctl, &pm);
232 	if (ret >= 0)
233 		ret = drm_ioctl(file, cmd, arg);
234 
235 	return ret;
236 }
237 
238 #ifdef CONFIG_COMPAT
239 static long xe_drm_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
240 {
241 	struct drm_file *file_priv = file->private_data;
242 	struct xe_device *xe = to_xe_device(file_priv->minor->dev);
243 	long ret;
244 
245 	if (xe_device_wedged(xe))
246 		return -ECANCELED;
247 
248 	ACQUIRE(xe_pm_runtime_ioctl, pm)(xe);
249 	ret = ACQUIRE_ERR(xe_pm_runtime_ioctl, &pm);
250 	if (ret >= 0)
251 		ret = drm_compat_ioctl(file, cmd, arg);
252 
253 	return ret;
254 }
255 #else
256 /* similarly to drm_compat_ioctl, let's it be assigned to .compat_ioct unconditionally */
257 #define xe_drm_compat_ioctl NULL
258 #endif
259 
260 static void barrier_open(struct vm_area_struct *vma)
261 {
262 	drm_dev_get(vma->vm_private_data);
263 }
264 
265 static void barrier_close(struct vm_area_struct *vma)
266 {
267 	drm_dev_put(vma->vm_private_data);
268 }
269 
270 static void barrier_release_dummy_page(struct drm_device *dev, void *res)
271 {
272 	struct page *dummy_page = (struct page *)res;
273 
274 	__free_page(dummy_page);
275 }
276 
277 static vm_fault_t barrier_fault(struct vm_fault *vmf)
278 {
279 	struct drm_device *dev = vmf->vma->vm_private_data;
280 	struct vm_area_struct *vma = vmf->vma;
281 	vm_fault_t ret = VM_FAULT_NOPAGE;
282 	pgprot_t prot;
283 	int idx;
284 
285 	prot = vm_get_page_prot(vma->vm_flags);
286 
287 	if (drm_dev_enter(dev, &idx)) {
288 		unsigned long pfn;
289 
290 #define LAST_DB_PAGE_OFFSET 0x7ff001
291 		pfn = PHYS_PFN(pci_resource_start(to_pci_dev(dev->dev), 0) +
292 				LAST_DB_PAGE_OFFSET);
293 		ret = vmf_insert_pfn_prot(vma, vma->vm_start, pfn,
294 					  pgprot_noncached(prot));
295 		drm_dev_exit(idx);
296 	} else {
297 		struct page *page;
298 
299 		/* Allocate new dummy page to map all the VA range in this VMA to it*/
300 		page = alloc_page(GFP_KERNEL | __GFP_ZERO);
301 		if (!page)
302 			return VM_FAULT_OOM;
303 
304 		/* Set the page to be freed using drmm release action */
305 		if (drmm_add_action_or_reset(dev, barrier_release_dummy_page, page))
306 			return VM_FAULT_OOM;
307 
308 		ret = vmf_insert_pfn_prot(vma, vma->vm_start, page_to_pfn(page),
309 					  prot);
310 	}
311 
312 	return ret;
313 }
314 
315 static const struct vm_operations_struct vm_ops_barrier = {
316 	.open = barrier_open,
317 	.close = barrier_close,
318 	.fault = barrier_fault,
319 };
320 
321 static int xe_pci_barrier_mmap(struct file *filp,
322 			       struct vm_area_struct *vma)
323 {
324 	struct drm_file *priv = filp->private_data;
325 	struct drm_device *dev = priv->minor->dev;
326 	struct xe_device *xe = to_xe_device(dev);
327 
328 	if (!IS_DGFX(xe))
329 		return -EINVAL;
330 
331 	if (vma->vm_end - vma->vm_start > SZ_4K)
332 		return -EINVAL;
333 
334 	if (is_cow_mapping(vma->vm_flags))
335 		return -EINVAL;
336 
337 	if (vma->vm_flags & (VM_READ | VM_EXEC))
338 		return -EINVAL;
339 
340 	vm_flags_clear(vma, VM_MAYREAD | VM_MAYEXEC);
341 	vm_flags_set(vma, VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP | VM_IO);
342 	vma->vm_ops = &vm_ops_barrier;
343 	vma->vm_private_data = dev;
344 	drm_dev_get(vma->vm_private_data);
345 
346 	return 0;
347 }
348 
349 static int xe_mmap(struct file *filp, struct vm_area_struct *vma)
350 {
351 	struct drm_file *priv = filp->private_data;
352 	struct drm_device *dev = priv->minor->dev;
353 
354 	if (drm_dev_is_unplugged(dev))
355 		return -ENODEV;
356 
357 	switch (vma->vm_pgoff) {
358 	case XE_PCI_BARRIER_MMAP_OFFSET >> XE_PTE_SHIFT:
359 		return xe_pci_barrier_mmap(filp, vma);
360 	}
361 
362 	return drm_gem_mmap(filp, vma);
363 }
364 
365 static const struct file_operations xe_driver_fops = {
366 	.owner = THIS_MODULE,
367 	.open = drm_open,
368 	.release = drm_release_noglobal,
369 	.unlocked_ioctl = xe_drm_ioctl,
370 	.mmap = xe_mmap,
371 	.poll = drm_poll,
372 	.read = drm_read,
373 	.compat_ioctl = xe_drm_compat_ioctl,
374 	.llseek = noop_llseek,
375 #ifdef CONFIG_PROC_FS
376 	.show_fdinfo = drm_show_fdinfo,
377 #endif
378 	.fop_flags = FOP_UNSIGNED_OFFSET,
379 };
380 
381 /**
382  * xe_is_xe_file() - Is the file an xe device file?
383  * @file: The file.
384  *
385  * Checks whether the file is opened against
386  * an xe device.
387  *
388  * Return: %true if an xe file, %false if not.
389  */
390 bool xe_is_xe_file(const struct file *file)
391 {
392 	return file->f_op == &xe_driver_fops;
393 }
394 
395 static const struct drm_driver regular_driver = {
396 	.driver_features =
397 	    XE_DISPLAY_DRIVER_FEATURES |
398 	    DRIVER_GEM |
399 	    DRIVER_RENDER | DRIVER_SYNCOBJ |
400 	    DRIVER_SYNCOBJ_TIMELINE,
401 	.open = xe_file_open,
402 	.postclose = xe_file_close,
403 
404 	.gem_prime_import = xe_gem_prime_import,
405 
406 	.dumb_create = xe_bo_dumb_create,
407 	.dumb_map_offset = drm_gem_ttm_dumb_map_offset,
408 #ifdef CONFIG_PROC_FS
409 	.show_fdinfo = xe_drm_client_fdinfo,
410 #endif
411 	.ioctls = xe_ioctls,
412 	.num_ioctls = ARRAY_SIZE(xe_ioctls),
413 	.fops = &xe_driver_fops,
414 	.name = DRIVER_NAME,
415 	.desc = DRIVER_DESC,
416 	.major = DRIVER_MAJOR,
417 	.minor = DRIVER_MINOR,
418 	.patchlevel = DRIVER_PATCHLEVEL,
419 	XE_DISPLAY_DRIVER_OPS,
420 };
421 
422 #ifdef CONFIG_PCI_IOV
423 static const struct drm_ioctl_desc xe_ioctls_admin_only[] = {
424 	DRM_IOCTL_DEF_DRV(XE_DEVICE_QUERY, xe_query_ioctl, DRM_RENDER_ALLOW),
425 	DRM_IOCTL_DEF_DRV(XE_OBSERVATION, xe_observation_ioctl, DRM_RENDER_ALLOW),
426 };
427 
428 static const struct drm_driver admin_only_driver = {
429 	.driver_features =
430 	    XE_DISPLAY_DRIVER_FEATURES |
431 	    DRIVER_GEM | DRIVER_RENDER,
432 	.open = xe_file_open,
433 	.postclose = xe_file_close,
434 	.ioctls = xe_ioctls_admin_only,
435 	.num_ioctls = ARRAY_SIZE(xe_ioctls_admin_only),
436 	.fops = &xe_driver_fops,
437 	.name = DRIVER_NAME,
438 	.desc = DRIVER_DESC,
439 	.major = DRIVER_MAJOR,
440 	.minor = DRIVER_MINOR,
441 	.patchlevel = DRIVER_PATCHLEVEL,
442 	XE_DISPLAY_DRIVER_OPS,
443 };
444 
445 /**
446  * xe_device_is_admin_only() - Check whether device is admin only or not.
447  * @xe: the &xe_device to check
448  *
449  * Return: true if the device is admin only, false otherwise.
450  */
451 bool xe_device_is_admin_only(const struct xe_device *xe)
452 {
453 	KUNIT_STATIC_STUB_REDIRECT(xe_device_is_admin_only, xe);
454 	return xe->drm.driver == &admin_only_driver;
455 }
456 #endif
457 
458 static void xe_device_destroy(struct drm_device *dev, void *dummy)
459 {
460 	struct xe_device *xe = to_xe_device(dev);
461 
462 	xe_bo_dev_fini(&xe->bo_device);
463 
464 	if (xe->preempt_fence_wq)
465 		destroy_workqueue(xe->preempt_fence_wq);
466 
467 	if (xe->ordered_wq)
468 		destroy_workqueue(xe->ordered_wq);
469 
470 	if (xe->unordered_wq)
471 		destroy_workqueue(xe->unordered_wq);
472 
473 	if (xe->destroy_wq)
474 		destroy_workqueue(xe->destroy_wq);
475 
476 	ttm_device_fini(&xe->ttm);
477 }
478 
479 /**
480  * xe_device_create() - Create a new &xe_device instance
481  * @pdev: the parent &pci_dev
482  *
483  * Allocate and initialize a device managed Xe device structure.
484  *
485  * Return: pointer to new &xe_device on success, or ERR_PTR on failure.
486  */
487 struct xe_device *xe_device_create(struct pci_dev *pdev)
488 {
489 	const struct drm_driver *driver = &regular_driver;
490 	struct xe_device *xe;
491 	int err;
492 
493 #ifdef CONFIG_PCI_IOV
494 	/*
495 	 * Since XE device is not initialized yet, read from configfs
496 	 * directly to decide whether we are in admin-only PF mode or not.
497 	 */
498 	if (xe_configfs_admin_only_pf(pdev))
499 		driver = &admin_only_driver;
500 #endif
501 
502 	err = aperture_remove_conflicting_pci_devices(pdev, driver->name);
503 	if (err)
504 		return ERR_PTR(err);
505 
506 	xe = devm_drm_dev_alloc(&pdev->dev, driver, struct xe_device, drm);
507 	if (IS_ERR(xe))
508 		return xe;
509 
510 	err = xe_device_init_early(xe);
511 	if (err)
512 		return ERR_PTR(err);
513 
514 	return xe;
515 }
516 ALLOW_ERROR_INJECTION(xe_device_create, ERRNO); /* See xe_pci_probe() */
517 
518 /**
519  * xe_device_init_early() - Initialize a new &xe_device instance
520  * @xe: the &xe_device to initialize
521  *
522  * Return: 0 on success or a negative error code on failure.
523  */
524 int xe_device_init_early(struct xe_device *xe)
525 {
526 	int err;
527 
528 	err = ttm_device_init(&xe->ttm, &xe_ttm_funcs, xe->drm.dev,
529 			      xe->drm.anon_inode->i_mapping,
530 			      xe->drm.vma_offset_manager,
531 			      TTM_ALLOCATION_POOL_BENEFICIAL_ORDER(get_order(SZ_2M)));
532 	if (err)
533 		return err;
534 
535 	xe_bo_dev_init(&xe->bo_device);
536 	err = drmm_add_action_or_reset(&xe->drm, xe_device_destroy, NULL);
537 	if (err)
538 		return err;
539 
540 	err = xe_shrinker_create(xe);
541 	if (err)
542 		return err;
543 
544 	xe->atomic_svm_timeslice_ms = 5;
545 	xe->min_run_period_lr_ms = 5;
546 
547 	err = xe_irq_init(xe);
548 	if (err)
549 		return err;
550 
551 	xe_validation_device_init(&xe->val);
552 
553 	init_waitqueue_head(&xe->ufence_wq);
554 
555 	init_rwsem(&xe->usm.lock);
556 
557 	err = xe_pagemap_shrinker_create(xe);
558 	if (err)
559 		return err;
560 
561 	xa_init_flags(&xe->usm.asid_to_vm, XA_FLAGS_ALLOC);
562 
563 	if (IS_ENABLED(CONFIG_DRM_XE_DEBUG)) {
564 		/* Trigger a large asid and an early asid wrap. */
565 		u32 asid;
566 
567 		BUILD_BUG_ON(XE_MAX_ASID < 2);
568 		err = xa_alloc_cyclic(&xe->usm.asid_to_vm, &asid, NULL,
569 				      XA_LIMIT(XE_MAX_ASID - 2, XE_MAX_ASID - 1),
570 				      &xe->usm.next_asid, GFP_KERNEL);
571 		drm_WARN_ON(&xe->drm, err);
572 		if (err >= 0)
573 			xa_erase(&xe->usm.asid_to_vm, asid);
574 	}
575 
576 	err = xe_bo_pinned_init(xe);
577 	if (err)
578 		return err;
579 
580 	xe->preempt_fence_wq = alloc_ordered_workqueue("xe-preempt-fence-wq",
581 						       WQ_MEM_RECLAIM);
582 	xe->ordered_wq = alloc_ordered_workqueue("xe-ordered-wq", 0);
583 	xe->unordered_wq = alloc_workqueue("xe-unordered-wq", WQ_PERCPU, 0);
584 	xe->destroy_wq = alloc_workqueue("xe-destroy-wq", WQ_PERCPU, 0);
585 	if (!xe->ordered_wq || !xe->unordered_wq ||
586 	    !xe->preempt_fence_wq || !xe->destroy_wq) {
587 		/*
588 		 * Cleanup done in xe_device_destroy via
589 		 * drmm_add_action_or_reset register above
590 		 */
591 		drm_err(&xe->drm, "Failed to allocate xe workqueues\n");
592 		return -ENOMEM;
593 	}
594 
595 	err = drmm_mutex_init(&xe->drm, &xe->pmt.lock);
596 	if (err)
597 		return err;
598 
599 	err = xe_pm_init_early(xe);
600 	if (err)
601 		return err;
602 
603 	return 0;
604 }
605 
606 static bool xe_driver_flr_disabled(struct xe_device *xe)
607 {
608 	if (IS_SRIOV_VF(xe))
609 		return true;
610 
611 	if (xe_mmio_read32(xe_root_tile_mmio(xe), GU_CNTL_PROTECTED) & DRIVERINT_FLR_DIS) {
612 		drm_info(&xe->drm, "Driver-FLR disabled by BIOS\n");
613 		return true;
614 	}
615 
616 	return false;
617 }
618 
619 /*
620  * The driver-initiated FLR is the highest level of reset that we can trigger
621  * from within the driver. It is different from the PCI FLR in that it doesn't
622  * fully reset the SGUnit and doesn't modify the PCI config space and therefore
623  * it doesn't require a re-enumeration of the PCI BARs. However, the
624  * driver-initiated FLR does still cause a reset of both GT and display and a
625  * memory wipe of local and stolen memory, so recovery would require a full HW
626  * re-init and saving/restoring (or re-populating) the wiped memory. Since we
627  * perform the FLR as the very last action before releasing access to the HW
628  * during the driver release flow, we don't attempt recovery at all, because
629  * if/when a new instance of Xe is bound to the device it will do a full
630  * re-init anyway.
631  */
632 static void __xe_driver_flr(struct xe_device *xe)
633 {
634 	const unsigned int flr_timeout = 3 * USEC_PER_SEC; /* specs recommend a 3s wait */
635 	struct xe_mmio *mmio = xe_root_tile_mmio(xe);
636 	int ret;
637 
638 	drm_dbg(&xe->drm, "Triggering Driver-FLR\n");
639 
640 	/*
641 	 * Make sure any pending FLR requests have cleared by waiting for the
642 	 * FLR trigger bit to go to zero. Also clear GU_DEBUG's DRIVERFLR_STATUS
643 	 * to make sure it's not still set from a prior attempt (it's a write to
644 	 * clear bit).
645 	 * Note that we should never be in a situation where a previous attempt
646 	 * is still pending (unless the HW is totally dead), but better to be
647 	 * safe in case something unexpected happens
648 	 */
649 	ret = xe_mmio_wait32(mmio, GU_CNTL, DRIVERFLR, 0, flr_timeout, NULL, false);
650 	if (ret) {
651 		drm_err(&xe->drm, "Driver-FLR-prepare wait for ready failed! %d\n", ret);
652 		return;
653 	}
654 	xe_mmio_write32(mmio, GU_DEBUG, DRIVERFLR_STATUS);
655 
656 	/* Trigger the actual Driver-FLR */
657 	xe_mmio_rmw32(mmio, GU_CNTL, 0, DRIVERFLR);
658 
659 	/* Wait for hardware teardown to complete */
660 	ret = xe_mmio_wait32(mmio, GU_CNTL, DRIVERFLR, 0, flr_timeout, NULL, false);
661 	if (ret) {
662 		drm_err(&xe->drm, "Driver-FLR-teardown wait completion failed! %d\n", ret);
663 		return;
664 	}
665 
666 	/* Wait for hardware/firmware re-init to complete */
667 	ret = xe_mmio_wait32(mmio, GU_DEBUG, DRIVERFLR_STATUS, DRIVERFLR_STATUS,
668 			     flr_timeout, NULL, false);
669 	if (ret) {
670 		drm_err(&xe->drm, "Driver-FLR-reinit wait completion failed! %d\n", ret);
671 		return;
672 	}
673 
674 	/* Clear sticky completion status */
675 	xe_mmio_write32(mmio, GU_DEBUG, DRIVERFLR_STATUS);
676 }
677 
678 static void xe_driver_flr(struct xe_device *xe)
679 {
680 	if (xe_driver_flr_disabled(xe))
681 		return;
682 
683 	__xe_driver_flr(xe);
684 }
685 
686 static void xe_driver_flr_fini(void *arg)
687 {
688 	struct xe_device *xe = arg;
689 
690 	if (xe->needs_flr_on_fini)
691 		xe_driver_flr(xe);
692 }
693 
694 static void xe_device_sanitize(void *arg)
695 {
696 	struct xe_device *xe = arg;
697 	struct xe_gt *gt;
698 	u8 id;
699 
700 	for_each_gt(gt, xe, id)
701 		xe_gt_sanitize(gt);
702 }
703 
704 static int xe_set_dma_info(struct xe_device *xe)
705 {
706 	unsigned int mask_size = xe->info.dma_mask_size;
707 	int err;
708 
709 	dma_set_max_seg_size(xe->drm.dev, xe_sg_segment_size(xe->drm.dev));
710 
711 	err = dma_set_mask(xe->drm.dev, DMA_BIT_MASK(mask_size));
712 	if (err)
713 		goto mask_err;
714 
715 	err = dma_set_coherent_mask(xe->drm.dev, DMA_BIT_MASK(mask_size));
716 	if (err)
717 		goto mask_err;
718 
719 	return 0;
720 
721 mask_err:
722 	drm_err(&xe->drm, "Can't set DMA mask/consistent mask (%d)\n", err);
723 	return err;
724 }
725 
726 static void assert_lmem_ready(struct xe_device *xe)
727 {
728 	if (!IS_DGFX(xe) || IS_SRIOV_VF(xe))
729 		return;
730 
731 	xe_assert(xe, xe_mmio_read32(xe_root_tile_mmio(xe), GU_CNTL) &
732 		  LMEM_INIT);
733 }
734 
735 static void vf_update_device_info(struct xe_device *xe)
736 {
737 	xe_assert(xe, IS_SRIOV_VF(xe));
738 	/* disable features that are not available/applicable to VFs */
739 	xe->info.probe_display = 0;
740 	xe->info.has_heci_cscfi = 0;
741 	xe->info.has_heci_gscfi = 0;
742 	xe->info.has_i2c = 0;
743 	xe->info.has_late_bind = 0;
744 	xe->info.skip_guc_pc = 1;
745 	xe->info.skip_pcode = 1;
746 	xe->info.has_drm_ras = false;
747 }
748 
749 static int xe_device_vram_alloc(struct xe_device *xe)
750 {
751 	struct xe_vram_region *vram;
752 
753 	if (!IS_DGFX(xe))
754 		return 0;
755 
756 	vram = drmm_kzalloc(&xe->drm, sizeof(*vram), GFP_KERNEL);
757 	if (!vram)
758 		return -ENOMEM;
759 
760 	xe->mem.vram = vram;
761 	return 0;
762 }
763 
764 /**
765  * xe_device_probe_early: Device early probe
766  * @xe: xe device instance
767  *
768  * Initialize MMIO resources that don't require any
769  * knowledge about tile count. Also initialize pcode and
770  * check vram initialization on root tile.
771  *
772  * Return: 0 on success, error code on failure
773  */
774 int xe_device_probe_early(struct xe_device *xe)
775 {
776 	int err;
777 
778 	xe_wa_device_init(xe);
779 	xe_wa_process_device_oob(xe);
780 
781 	err = xe_mmio_probe_early(xe);
782 	if (err)
783 		return err;
784 
785 	xe_sriov_probe_early(xe);
786 
787 	if (xe_device_is_admin_only(xe) && !IS_SRIOV_PF(xe)) {
788 		xe_err(xe, "Can't run Admin-only mode without SR-IOV PF mode!\n");
789 		return -ENODEV;
790 	}
791 
792 	if (IS_SRIOV_VF(xe))
793 		vf_update_device_info(xe);
794 
795 	/*
796 	 * Check for pcode uncore_init status to confirm if the SoC
797 	 * initialization is complete. Until done, any MMIO or lmem access from
798 	 * the driver will be blocked
799 	 */
800 	err = xe_pcode_probe_early(xe);
801 	if (err || xe_survivability_mode_is_requested(xe)) {
802 		int save_err = err;
803 
804 		/*
805 		 * Try to leave device in survivability mode if device is
806 		 * possible, but still return the previous error for error
807 		 * propagation
808 		 */
809 		err = xe_survivability_mode_boot_enable(xe);
810 		if (err)
811 			return err;
812 
813 		return save_err;
814 	}
815 
816 	/*
817 	 * Make sure the lmem is initialized and ready to use. xe_pcode_ready()
818 	 * is flagged after full initialization is complete. Assert if lmem is
819 	 * not initialized.
820 	 */
821 	assert_lmem_ready(xe);
822 
823 	xe->wedged.mode = xe_device_validate_wedged_mode(xe, xe_modparam.wedged_mode) ?
824 			  XE_DEFAULT_WEDGED_MODE : xe_modparam.wedged_mode;
825 	drm_dbg(&xe->drm, "wedged_mode: setting mode (%u) %s\n",
826 		xe->wedged.mode, xe_wedged_mode_to_string(xe->wedged.mode));
827 
828 	err = xe_device_vram_alloc(xe);
829 	if (err)
830 		return err;
831 
832 	return 0;
833 }
834 ALLOW_ERROR_INJECTION(xe_device_probe_early, ERRNO); /* See xe_pci_probe() */
835 
836 static int probe_has_flat_ccs(struct xe_device *xe)
837 {
838 	struct xe_gt *gt;
839 	u32 reg;
840 
841 	/* Always enabled/disabled, no runtime check to do */
842 	if (GRAPHICS_VER(xe) < 20 || !xe->info.has_flat_ccs || IS_SRIOV_VF(xe))
843 		return 0;
844 
845 	gt = xe_root_mmio_gt(xe);
846 	if (!gt)
847 		return 0;
848 
849 	CLASS(xe_force_wake, fw_ref)(gt_to_fw(gt), XE_FW_GT);
850 	if (!fw_ref.domains)
851 		return -ETIMEDOUT;
852 
853 	reg = xe_gt_mcr_unicast_read_any(gt, XE2_FLAT_CCS_BASE_RANGE_LOWER);
854 	xe->info.has_flat_ccs = (reg & XE2_FLAT_CCS_ENABLE);
855 
856 	if (!xe->info.has_flat_ccs)
857 		drm_dbg(&xe->drm,
858 			"Flat CCS has been disabled in bios, May lead to performance impact");
859 
860 	return 0;
861 }
862 
863 /*
864  * Detect if the driver is being run on pre-production hardware.  We don't
865  * keep workarounds for pre-production hardware long term, so print an
866  * error and add taint if we're being loaded on a pre-production platform
867  * for which the pre-prod workarounds have already been removed.
868  *
869  * The general policy is that we'll remove any workarounds that only apply to
870  * pre-production hardware around the time force_probe restrictions are lifted
871  * for a platform of the next major IP generation (for example, Xe2 pre-prod
872  * workarounds should be removed around the time the first Xe3 platforms have
873  * force_probe lifted).
874  */
875 static void detect_preproduction_hw(struct xe_device *xe)
876 {
877 	struct xe_gt *gt;
878 	int id;
879 
880 	/*
881 	 * SR-IOV VFs don't have access to the FUSE2 register, so we can't
882 	 * check pre-production status there.  But the host OS will notice
883 	 * and report the pre-production status, which should be enough to
884 	 * help us catch mistaken use of pre-production hardware.
885 	 */
886 	if (IS_SRIOV_VF(xe))
887 		return;
888 
889 	/*
890 	 * The "SW_CAP" fuse contains a bit indicating whether the device is a
891 	 * production or pre-production device.  This fuse is reflected through
892 	 * the GT "FUSE2" register, even though the contents of the fuse are
893 	 * not GT-specific.  Every GT's reflection of this fuse should show the
894 	 * same value, so we'll just use the first available GT for lookup.
895 	 */
896 	for_each_gt(gt, xe, id)
897 		break;
898 
899 	if (!gt)
900 		return;
901 
902 	CLASS(xe_force_wake, fw_ref)(gt_to_fw(gt), XE_FW_GT);
903 	if (!xe_force_wake_ref_has_domain(fw_ref.domains, XE_FW_GT)) {
904 		xe_gt_err(gt, "Forcewake failure; cannot determine production/pre-production hw status.\n");
905 		return;
906 	}
907 
908 	if (xe_mmio_read32(&gt->mmio, FUSE2) & PRODUCTION_HW)
909 		return;
910 
911 	xe_info(xe, "Pre-production hardware detected.\n");
912 	if (!xe->info.has_pre_prod_wa) {
913 		xe_err(xe, "Pre-production workarounds for this platform have already been removed.\n");
914 		add_taint(TAINT_MACHINE_CHECK, LOCKDEP_STILL_OK);
915 	}
916 }
917 
918 static void xe_device_wedged_fini(struct drm_device *drm, void *arg)
919 {
920 	struct xe_device *xe = arg;
921 
922 	if (atomic_read(&xe->wedged.flag))
923 		xe_pm_runtime_put(xe);
924 }
925 
926 int xe_device_probe(struct xe_device *xe)
927 {
928 	struct xe_tile *tile;
929 	struct xe_gt *gt;
930 	int err;
931 	u8 id;
932 
933 	xe_pat_init_early(xe);
934 
935 	err = xe_sriov_init(xe);
936 	if (err)
937 		return err;
938 
939 	xe->info.mem_region_mask = 1;
940 
941 	err = xe_set_dma_info(xe);
942 	if (err)
943 		return err;
944 
945 	err = xe_mmio_probe_tiles(xe);
946 	if (err)
947 		return err;
948 
949 	for_each_gt(gt, xe, id) {
950 		err = xe_gt_init_early(gt);
951 		if (err)
952 			return err;
953 	}
954 
955 	/*
956 	 * Wa_16029380221: The affected GT will always use non-coherent
957 	 * access to page tables, so we must do uncached writes from the
958 	 * CPU.
959 	 */
960 	for_each_gt(gt, xe, id)
961 		if (XE_GT_WA(gt, 16029380221))
962 			xe->info.has_cached_pt = false;
963 
964 	for_each_tile(tile, xe, id) {
965 		err = xe_ggtt_init_early(tile->mem.ggtt);
966 		if (err)
967 			return err;
968 	}
969 
970 	/*
971 	 * From here on, if a step fails, make sure a Driver-FLR is triggereed
972 	 */
973 	err = devm_add_action_or_reset(xe->drm.dev, xe_driver_flr_fini, xe);
974 	if (err)
975 		return err;
976 
977 	err = probe_has_flat_ccs(xe);
978 	if (err)
979 		return err;
980 
981 	err = xe_vram_probe(xe);
982 	if (err)
983 		return err;
984 
985 	for_each_tile(tile, xe, id) {
986 		err = xe_tile_init_noalloc(tile);
987 		if (err)
988 			return err;
989 	}
990 
991 	/*
992 	 * Allow allocations only now to ensure xe_display_init_early()
993 	 * is the first to allocate, always.
994 	 */
995 	err = xe_ttm_sys_mgr_init(xe);
996 	if (err)
997 		return err;
998 
999 	/* Allocate and map stolen after potential VRAM resize */
1000 	err = xe_ttm_stolen_mgr_init(xe);
1001 	if (err)
1002 		return err;
1003 
1004 	err = xe_soc_remapper_init(xe);
1005 	if (err)
1006 		return err;
1007 
1008 	err = xe_sysctrl_init(xe);
1009 	if (err)
1010 		return err;
1011 
1012 	xe_ras_init(xe);
1013 
1014 	/*
1015 	 * Now that GT is initialized (TTM in particular),
1016 	 * we can try to init display, and inherit the initial fb.
1017 	 * This is the reason the first allocation needs to be done
1018 	 * inside display.
1019 	 */
1020 	err = xe_display_init_early(xe);
1021 	if (err)
1022 		return err;
1023 
1024 	for_each_tile(tile, xe, id) {
1025 		err = xe_tile_init(tile);
1026 		if (err)
1027 			return err;
1028 	}
1029 
1030 	err = xe_irq_install(xe);
1031 	if (err)
1032 		return err;
1033 
1034 	for_each_gt(gt, xe, id) {
1035 		err = xe_gt_init(gt);
1036 		if (err)
1037 			return err;
1038 	}
1039 
1040 	err = xe_pagefault_init(xe);
1041 	if (err)
1042 		return err;
1043 
1044 	if (xe->tiles->media_gt &&
1045 	    XE_GT_WA(xe->tiles->media_gt, 15015404425_disable))
1046 		XE_DEVICE_WA_DISABLE(xe, 15015404425);
1047 
1048 	err = xe_devcoredump_init(xe);
1049 	if (err)
1050 		return err;
1051 
1052 	xe_nvm_init(xe);
1053 
1054 	err = xe_heci_gsc_init(xe);
1055 	if (err)
1056 		return err;
1057 
1058 	err = xe_late_bind_init(&xe->late_bind);
1059 	if (err)
1060 		return err;
1061 
1062 	err = xe_oa_init(xe);
1063 	if (err)
1064 		return err;
1065 
1066 	err = xe_display_init(xe);
1067 	if (err)
1068 		return err;
1069 
1070 	err = xe_pxp_init(xe);
1071 	if (err)
1072 		return err;
1073 
1074 	err = xe_psmi_init(xe);
1075 	if (err)
1076 		return err;
1077 
1078 	err = drm_dev_register(&xe->drm, 0);
1079 	if (err)
1080 		return err;
1081 
1082 	xe_display_register(xe);
1083 
1084 	err = xe_oa_register(xe);
1085 	if (err)
1086 		goto err_unregister_display;
1087 
1088 	err = xe_pmu_register(&xe->pmu);
1089 	if (err)
1090 		goto err_unregister_display;
1091 
1092 	err = xe_device_sysfs_init(xe);
1093 	if (err)
1094 		goto err_unregister_display;
1095 
1096 	xe_debugfs_register(xe);
1097 
1098 	err = xe_hwmon_register(xe);
1099 	if (err)
1100 		goto err_unregister_display;
1101 
1102 	err = xe_i2c_probe(xe);
1103 	if (err)
1104 		goto err_unregister_display;
1105 
1106 	for_each_gt(gt, xe, id)
1107 		xe_gt_sanitize_freq(gt);
1108 
1109 	xe_vsec_init(xe);
1110 
1111 	err = xe_sriov_init_late(xe);
1112 	if (err)
1113 		goto err_unregister_display;
1114 
1115 	detect_preproduction_hw(xe);
1116 
1117 	err = drmm_add_action_or_reset(&xe->drm, xe_device_wedged_fini, xe);
1118 	if (err)
1119 		goto err_unregister_display;
1120 
1121 	return devm_add_action_or_reset(xe->drm.dev, xe_device_sanitize, xe);
1122 
1123 err_unregister_display:
1124 	xe_display_unregister(xe);
1125 	drm_dev_unregister(&xe->drm);
1126 
1127 	return err;
1128 }
1129 
1130 void xe_device_remove(struct xe_device *xe)
1131 {
1132 	xe_display_unregister(xe);
1133 
1134 	drm_dev_unplug(&xe->drm);
1135 
1136 	xe_bo_pci_dev_remove_all(xe);
1137 }
1138 
1139 void xe_device_shutdown(struct xe_device *xe)
1140 {
1141 	struct xe_gt *gt;
1142 	u8 id;
1143 
1144 	drm_dbg(&xe->drm, "Shutting down device\n");
1145 
1146 	xe_display_shutdown(xe);
1147 
1148 	xe_irq_suspend(xe);
1149 
1150 	for_each_gt(gt, xe, id)
1151 		xe_gt_shutdown(gt);
1152 
1153 	xe_display_shutdown_late(xe);
1154 
1155 	if (!xe_driver_flr_disabled(xe)) {
1156 		/* BOOM! */
1157 		__xe_driver_flr(xe);
1158 	}
1159 }
1160 
1161 /**
1162  * xe_device_wmb() - Device specific write memory barrier
1163  * @xe: the &xe_device
1164  *
1165  * While wmb() is sufficient for a barrier if we use system memory, on discrete
1166  * platforms with device memory we additionally need to issue a register write.
1167  * Since it doesn't matter which register we write to, use the read-only VF_CAP
1168  * register that is also marked as accessible by the VFs.
1169  */
1170 void xe_device_wmb(struct xe_device *xe)
1171 {
1172 	wmb();
1173 	if (IS_DGFX(xe))
1174 		xe_mmio_write32(xe_root_tile_mmio(xe), VF_CAP_REG, 0);
1175 }
1176 
1177 /*
1178  * Issue a TRANSIENT_FLUSH_REQUEST and wait for completion on each gt.
1179  */
1180 static void tdf_request_sync(struct xe_device *xe)
1181 {
1182 	struct xe_gt *gt;
1183 	u8 id;
1184 
1185 	for_each_gt_with_type(gt, xe, id, BIT(XE_GT_TYPE_MAIN)) {
1186 		CLASS(xe_force_wake, fw_ref)(gt_to_fw(gt), XE_FW_GT);
1187 		if (!fw_ref.domains)
1188 			return;
1189 
1190 		xe_mmio_write32(&gt->mmio, XE2_TDF_CTRL, TRANSIENT_FLUSH_REQUEST);
1191 
1192 		/*
1193 		 * FIXME: We can likely do better here with our choice of
1194 		 * timeout. Currently we just assume the worst case, i.e. 150us,
1195 		 * which is believed to be sufficient to cover the worst case
1196 		 * scenario on current platforms if all cache entries are
1197 		 * transient and need to be flushed..
1198 		 */
1199 		if (xe_mmio_wait32(&gt->mmio, XE2_TDF_CTRL, TRANSIENT_FLUSH_REQUEST, 0,
1200 				   300, NULL, false))
1201 			xe_gt_err_once(gt, "TD flush timeout\n");
1202 	}
1203 }
1204 
1205 /**
1206  * xe_device_is_l2_flush_optimized - if L2 flush is optimized by HW
1207  * @xe: The device to check.
1208  *
1209  * Return: true if the HW device optimizing L2 flush, false otherwise.
1210  */
1211 bool xe_device_is_l2_flush_optimized(struct xe_device *xe)
1212 {
1213 	/* XA is *always* flushed, like at the end-of-submssion (and maybe other
1214 	 * places), just that internally as an optimisation hw doesn't need to make
1215 	 * that a full flush (which will also include XA) when Media is
1216 	 * off/powergated, since it doesn't need to worry about GT caches vs Media
1217 	 * coherency, and only CPU vs GPU coherency, so can make that flush a
1218 	 * targeted XA flush, since stuff tagged with XA now means it's shared with
1219 	 * the CPU. The main implication is that we now need to somehow flush non-XA before
1220 	 * freeing system memory pages, otherwise dirty cachelines could be flushed after the free
1221 	 * (like if Media suddenly turns on and does a full flush)
1222 	 */
1223 	if (GRAPHICS_VER(xe) >= 35 && !IS_DGFX(xe))
1224 		return true;
1225 	return false;
1226 }
1227 
1228 void xe_device_l2_flush(struct xe_device *xe)
1229 {
1230 	struct xe_gt *gt;
1231 
1232 	gt = xe_root_mmio_gt(xe);
1233 	if (!gt)
1234 		return;
1235 
1236 	if (!XE_GT_WA(gt, 16023588340))
1237 		return;
1238 
1239 	CLASS(xe_force_wake, fw_ref)(gt_to_fw(gt), XE_FW_GT);
1240 	if (!fw_ref.domains)
1241 		return;
1242 
1243 	spin_lock(&gt->global_invl_lock);
1244 
1245 	xe_mmio_write32(&gt->mmio, XE2_GLOBAL_INVAL, 0x1);
1246 	if (xe_mmio_wait32(&gt->mmio, XE2_GLOBAL_INVAL, 0x1, 0x0, 1000, NULL, true))
1247 		xe_gt_err_once(gt, "Global invalidation timeout\n");
1248 
1249 	spin_unlock(&gt->global_invl_lock);
1250 }
1251 
1252 /**
1253  * xe_device_td_flush() - Flush transient L3 cache entries
1254  * @xe: The device
1255  *
1256  * Display engine has direct access to memory and is never coherent with L3/L4
1257  * caches (or CPU caches), however KMD is responsible for specifically flushing
1258  * transient L3 GPU cache entries prior to the flip sequence to ensure scanout
1259  * can happen from such a surface without seeing corruption.
1260  *
1261  * Display surfaces can be tagged as transient by mapping it using one of the
1262  * various L3:XD PAT index modes on Xe2.
1263  *
1264  * Note: On non-discrete xe2 platforms, like LNL, the entire L3 cache is flushed
1265  * at the end of each submission via PIPE_CONTROL for compute/render, since SA
1266  * Media is not coherent with L3 and we want to support render-vs-media
1267  * usescases. For other engines like copy/blt the HW internally forces uncached
1268  * behaviour, hence why we can skip the TDF on such platforms.
1269  */
1270 void xe_device_td_flush(struct xe_device *xe)
1271 {
1272 	struct xe_gt *root_gt;
1273 
1274 	/*
1275 	 * From Xe3p onward the HW takes care of flush of TD entries also along
1276 	 * with flushing XA entries, which will be at the usual sync points,
1277 	 * like at the end of submission, so no manual flush is needed here.
1278 	 */
1279 	if (GRAPHICS_VER(xe) >= 35)
1280 		return;
1281 
1282 	if (!IS_DGFX(xe) || GRAPHICS_VER(xe) < 20)
1283 		return;
1284 
1285 	root_gt = xe_root_mmio_gt(xe);
1286 	if (!root_gt)
1287 		return;
1288 
1289 	if (XE_GT_WA(root_gt, 16023588340)) {
1290 		/* A transient flush is not sufficient: flush the L2 */
1291 		xe_device_l2_flush(xe);
1292 	} else {
1293 		xe_guc_pc_apply_flush_freq_limit(&root_gt->uc.guc.pc);
1294 		tdf_request_sync(xe);
1295 		xe_guc_pc_remove_flush_freq_limit(&root_gt->uc.guc.pc);
1296 	}
1297 }
1298 
1299 u32 xe_device_ccs_bytes(struct xe_device *xe, u64 size)
1300 {
1301 	return xe_device_has_flat_ccs(xe) ?
1302 		DIV_ROUND_UP_ULL(size, NUM_BYTES_PER_CCS_BYTE(xe)) : 0;
1303 }
1304 
1305 /**
1306  * xe_device_assert_mem_access - Inspect the current runtime_pm state.
1307  * @xe: xe device instance
1308  *
1309  * To be used before any kind of memory access. It will splat a debug warning
1310  * if the device is currently sleeping. But it doesn't guarantee in any way
1311  * that the device is going to remain awake. Xe PM runtime get and put
1312  * functions might be added to the outer bound of the memory access, while
1313  * this check is intended for inner usage to splat some warning if the worst
1314  * case has just happened.
1315  */
1316 void xe_device_assert_mem_access(struct xe_device *xe)
1317 {
1318 	xe_assert(xe, !xe_pm_runtime_suspended(xe));
1319 }
1320 
1321 void xe_device_snapshot_print(struct xe_device *xe, struct drm_printer *p)
1322 {
1323 	struct xe_gt *gt;
1324 	u8 id;
1325 
1326 	drm_printf(p, "PCI ID: 0x%04x\n", xe->info.devid);
1327 	drm_printf(p, "PCI revision: 0x%02x\n", xe->info.revid);
1328 
1329 	for_each_gt(gt, xe, id) {
1330 		drm_printf(p, "GT id: %u\n", id);
1331 		drm_printf(p, "\tTile: %u\n", gt->tile->id);
1332 		drm_printf(p, "\tType: %s\n",
1333 			   gt->info.type == XE_GT_TYPE_MAIN ? "main" : "media");
1334 		drm_printf(p, "\tIP ver: %u.%u.%u\n",
1335 			   REG_FIELD_GET(GMD_ID_ARCH_MASK, gt->info.gmdid),
1336 			   REG_FIELD_GET(GMD_ID_RELEASE_MASK, gt->info.gmdid),
1337 			   REG_FIELD_GET(GMD_ID_REVID, gt->info.gmdid));
1338 		drm_printf(p, "\tCS reference clock: %u\n", gt->info.reference_clock);
1339 	}
1340 }
1341 
1342 u64 xe_device_canonicalize_addr(struct xe_device *xe, u64 address)
1343 {
1344 	return sign_extend64(address, xe->info.va_bits - 1);
1345 }
1346 
1347 u64 xe_device_uncanonicalize_addr(struct xe_device *xe, u64 address)
1348 {
1349 	return address & GENMASK_ULL(xe->info.va_bits - 1, 0);
1350 }
1351 
1352 /**
1353  * DOC: Xe Device Wedging
1354  *
1355  * Xe driver uses drm device wedged uevent as documented in Documentation/gpu/drm-uapi.rst.
1356  * When device is in wedged state, every IOCTL will be blocked and GT cannot
1357  * be used. The conditions under which the driver declares the device wedged
1358  * depend on the wedged mode configuration (see &enum xe_wedged_mode). The
1359  * default recovery method for a wedged state is rebind/bus-reset.
1360  *
1361  * Another recovery method is vendor-specific. Below are the cases that send
1362  * ``WEDGED=vendor-specific`` recovery method in drm device wedged uevent.
1363  *
1364  * Case: Firmware Flash
1365  * --------------------
1366  *
1367  * Identification Hint
1368  * +++++++++++++++++++
1369  *
1370  * ``WEDGED=vendor-specific`` drm device wedged uevent with
1371  * :ref:`Runtime Survivability mode <xe-survivability-mode>` is used to notify
1372  * admin/userspace consumer about the need for a firmware flash.
1373  *
1374  * Recovery Procedure
1375  * ++++++++++++++++++
1376  *
1377  * Once ``WEDGED=vendor-specific`` drm device wedged uevent is received, follow
1378  * the below steps
1379  *
1380  * - Check Runtime Survivability mode sysfs.
1381  *   If enabled, firmware flash is required to recover the device.
1382  *
1383  *   /sys/bus/pci/devices/<device>/survivability_mode
1384  *
1385  * - Admin/userspace consumer can use firmware flashing tools like fwupd to flash
1386  *   firmware and restore device to normal operation.
1387  */
1388 
1389 /**
1390  * xe_device_set_wedged_method - Set wedged recovery method
1391  * @xe: xe device instance
1392  * @method: recovery method to set
1393  *
1394  * Set wedged recovery method to be sent in drm wedged uevent.
1395  */
1396 void xe_device_set_wedged_method(struct xe_device *xe, unsigned long method)
1397 {
1398 	xe->wedged.method = method;
1399 }
1400 
1401 /**
1402  * xe_device_declare_wedged - Declare device wedged
1403  * @xe: xe device instance
1404  *
1405  * This is a final state that can only be cleared with the recovery method
1406  * specified in the drm wedged uevent. The method can be set using
1407  * xe_device_set_wedged_method before declaring the device as wedged. If no method
1408  * is set, reprobe (unbind/re-bind) will be sent by default.
1409  *
1410  * In this state every IOCTL will be blocked so the GT cannot be used.
1411  * In general it will be called upon any critical error such as gt reset
1412  * failure or guc loading failure. Userspace will be notified of this state
1413  * through device wedged uevent.
1414  * If xe.wedged module parameter is set to 2, this function will be called
1415  * on every single execution timeout (a.k.a. GPU hang) right after devcoredump
1416  * snapshot capture. In this mode, GT reset won't be attempted so the state of
1417  * the issue is preserved for further debugging.
1418  */
1419 void xe_device_declare_wedged(struct xe_device *xe)
1420 {
1421 	struct xe_gt *gt;
1422 	u8 id;
1423 
1424 	if (xe->wedged.mode == XE_WEDGED_MODE_NEVER) {
1425 		drm_dbg(&xe->drm, "Wedged mode is forcibly disabled\n");
1426 		return;
1427 	}
1428 
1429 	if (!atomic_xchg(&xe->wedged.flag, 1)) {
1430 		xe->needs_flr_on_fini = true;
1431 		xe_pm_runtime_get_noresume(xe);
1432 		drm_err(&xe->drm,
1433 			"CRITICAL: Xe has declared device %s as wedged.\n"
1434 			"IOCTLs and executions are blocked.\n"
1435 			"For recovery procedure, refer to https://docs.kernel.org/gpu/drm-uapi.html#device-wedging\n"
1436 			"Please file a _new_ bug report at https://gitlab.freedesktop.org/drm/xe/kernel/issues/new\n",
1437 			dev_name(xe->drm.dev));
1438 	}
1439 
1440 	for_each_gt(gt, xe, id)
1441 		xe_gt_declare_wedged(gt);
1442 
1443 	if (xe_device_wedged(xe)) {
1444 		/*
1445 		 * XE_WEDGED_MODE_UPON_ANY_HANG_NO_RESET is intended for debugging
1446 		 * hangs, so wedge the device with 'none' recovery method and have
1447 		 * it available to the user for debugging.
1448 		 */
1449 		if (xe->wedged.mode == XE_WEDGED_MODE_UPON_ANY_HANG_NO_RESET)
1450 			xe_device_set_wedged_method(xe, DRM_WEDGE_RECOVERY_NONE);
1451 		/* If no wedge recovery method is set, use default */
1452 		else if (!xe->wedged.method)
1453 			xe_device_set_wedged_method(xe, DRM_WEDGE_RECOVERY_REBIND |
1454 						    DRM_WEDGE_RECOVERY_BUS_RESET);
1455 
1456 		/* Notify userspace of wedged device */
1457 		drm_dev_wedged_event(&xe->drm, xe->wedged.method, NULL);
1458 	}
1459 }
1460 
1461 /**
1462  * xe_device_validate_wedged_mode - Check if given mode is supported
1463  * @xe: the &xe_device
1464  * @mode: requested mode to validate
1465  *
1466  * Check whether the provided wedged mode is supported.
1467  *
1468  * Return: 0 if mode is supported, error code otherwise.
1469  */
1470 int xe_device_validate_wedged_mode(struct xe_device *xe, unsigned int mode)
1471 {
1472 	if (mode > XE_WEDGED_MODE_UPON_ANY_HANG_NO_RESET) {
1473 		drm_dbg(&xe->drm, "wedged_mode: invalid value (%u)\n", mode);
1474 		return -EINVAL;
1475 	} else if (mode == XE_WEDGED_MODE_UPON_ANY_HANG_NO_RESET && (IS_SRIOV_VF(xe) ||
1476 		   (IS_SRIOV_PF(xe) && !IS_ENABLED(CONFIG_DRM_XE_DEBUG)))) {
1477 		drm_dbg(&xe->drm, "wedged_mode: (%u) %s mode is not supported for %s\n",
1478 			mode, xe_wedged_mode_to_string(mode),
1479 			xe_sriov_mode_to_string(xe_device_sriov_mode(xe)));
1480 		return -EPERM;
1481 	}
1482 
1483 	return 0;
1484 }
1485 
1486 /**
1487  * xe_wedged_mode_to_string - Convert enum value to string.
1488  * @mode: the &xe_wedged_mode to convert
1489  *
1490  * Returns: wedged mode as a user friendly string.
1491  */
1492 const char *xe_wedged_mode_to_string(enum xe_wedged_mode mode)
1493 {
1494 	switch (mode) {
1495 	case XE_WEDGED_MODE_NEVER:
1496 		return "never";
1497 	case XE_WEDGED_MODE_UPON_CRITICAL_ERROR:
1498 		return "upon-critical-error";
1499 	case XE_WEDGED_MODE_UPON_ANY_HANG_NO_RESET:
1500 		return "upon-any-hang-no-reset";
1501 	default:
1502 		return "<invalid>";
1503 	}
1504 }
1505 
1506 /**
1507  * xe_device_asid_to_vm() - Find VM from ASID
1508  * @xe: the &xe_device
1509  * @asid: Address space ID
1510  *
1511  * Find a VM from ASID and take a reference to VM which caller must drop.
1512  * Reclaim safe.
1513  *
1514  * Return: VM on success, ERR_PTR on failure
1515  */
1516 struct xe_vm *xe_device_asid_to_vm(struct xe_device *xe, u32 asid)
1517 {
1518 	struct xe_vm *vm;
1519 
1520 	down_read(&xe->usm.lock);
1521 	vm = xa_load(&xe->usm.asid_to_vm, asid);
1522 	if (vm)
1523 		xe_vm_get(vm);
1524 	else
1525 		vm = ERR_PTR(-EINVAL);
1526 	up_read(&xe->usm.lock);
1527 
1528 	return vm;
1529 }
1530