xref: /openbmc/linux/drivers/accel/habanalabs/common/device.c (revision 6c31c13759272818108a329f166d86846d0e3f7a)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 /*
4  * Copyright 2016-2022 HabanaLabs, Ltd.
5  * All Rights Reserved.
6  */
7 
8 #define pr_fmt(fmt)			"habanalabs: " fmt
9 
10 #include <uapi/drm/habanalabs_accel.h>
11 #include "habanalabs.h"
12 
13 #include <linux/pci.h>
14 #include <linux/hwmon.h>
15 #include <linux/vmalloc.h>
16 
17 #include <trace/events/habanalabs.h>
18 
19 #define HL_RESET_DELAY_USEC			10000	/* 10ms */
20 
21 #define HL_DEVICE_RELEASE_WATCHDOG_TIMEOUT_SEC	5
22 
23 enum dma_alloc_type {
24 	DMA_ALLOC_COHERENT,
25 	DMA_ALLOC_POOL,
26 };
27 
28 #define MEM_SCRUB_DEFAULT_VAL 0x1122334455667788
29 
30 /*
31  * hl_set_dram_bar- sets the bar to allow later access to address
32  *
33  * @hdev: pointer to habanalabs device structure.
34  * @addr: the address the caller wants to access.
35  * @region: the PCI region.
36  * @new_bar_region_base: the new BAR region base address.
37  *
38  * @return: the old BAR base address on success, U64_MAX for failure.
39  *	    The caller should set it back to the old address after use.
40  *
41  * In case the bar space does not cover the whole address space,
42  * the bar base address should be set to allow access to a given address.
43  * This function can be called also if the bar doesn't need to be set,
44  * in that case it just won't change the base.
45  */
46 static u64 hl_set_dram_bar(struct hl_device *hdev, u64 addr, struct pci_mem_region *region,
47 				u64 *new_bar_region_base)
48 {
49 	struct asic_fixed_properties *prop = &hdev->asic_prop;
50 	u64 bar_base_addr, old_base;
51 
52 	if (is_power_of_2(prop->dram_pci_bar_size))
53 		bar_base_addr = addr & ~(prop->dram_pci_bar_size - 0x1ull);
54 	else
55 		bar_base_addr = DIV_ROUND_DOWN_ULL(addr, prop->dram_pci_bar_size) *
56 				prop->dram_pci_bar_size;
57 
58 	old_base = hdev->asic_funcs->set_dram_bar_base(hdev, bar_base_addr);
59 
60 	/* in case of success we need to update the new BAR base */
61 	if ((old_base != U64_MAX) && new_bar_region_base)
62 		*new_bar_region_base = bar_base_addr;
63 
64 	return old_base;
65 }
66 
67 int hl_access_sram_dram_region(struct hl_device *hdev, u64 addr, u64 *val,
68 	enum debugfs_access_type acc_type, enum pci_region region_type, bool set_dram_bar)
69 {
70 	struct pci_mem_region *region = &hdev->pci_mem_region[region_type];
71 	u64 old_base = 0, rc, bar_region_base = region->region_base;
72 	void __iomem *acc_addr;
73 
74 	if (set_dram_bar) {
75 		old_base = hl_set_dram_bar(hdev, addr, region, &bar_region_base);
76 		if (old_base == U64_MAX)
77 			return -EIO;
78 	}
79 
80 	acc_addr = hdev->pcie_bar[region->bar_id] + region->offset_in_bar +
81 			(addr - bar_region_base);
82 
83 	switch (acc_type) {
84 	case DEBUGFS_READ8:
85 		*val = readb(acc_addr);
86 		break;
87 	case DEBUGFS_WRITE8:
88 		writeb(*val, acc_addr);
89 		break;
90 	case DEBUGFS_READ32:
91 		*val = readl(acc_addr);
92 		break;
93 	case DEBUGFS_WRITE32:
94 		writel(*val, acc_addr);
95 		break;
96 	case DEBUGFS_READ64:
97 		*val = readq(acc_addr);
98 		break;
99 	case DEBUGFS_WRITE64:
100 		writeq(*val, acc_addr);
101 		break;
102 	}
103 
104 	if (set_dram_bar) {
105 		rc = hl_set_dram_bar(hdev, old_base, region, NULL);
106 		if (rc == U64_MAX)
107 			return -EIO;
108 	}
109 
110 	return 0;
111 }
112 
113 static void *hl_dma_alloc_common(struct hl_device *hdev, size_t size, dma_addr_t *dma_handle,
114 					gfp_t flag, enum dma_alloc_type alloc_type,
115 					const char *caller)
116 {
117 	void *ptr = NULL;
118 
119 	switch (alloc_type) {
120 	case DMA_ALLOC_COHERENT:
121 		ptr = hdev->asic_funcs->asic_dma_alloc_coherent(hdev, size, dma_handle, flag);
122 		break;
123 	case DMA_ALLOC_POOL:
124 		ptr = hdev->asic_funcs->asic_dma_pool_zalloc(hdev, size, flag, dma_handle);
125 		break;
126 	}
127 
128 	if (trace_habanalabs_dma_alloc_enabled() && !ZERO_OR_NULL_PTR(ptr))
129 		trace_habanalabs_dma_alloc(hdev->dev, (u64) (uintptr_t) ptr, *dma_handle, size,
130 						caller);
131 
132 	return ptr;
133 }
134 
135 static void hl_asic_dma_free_common(struct hl_device *hdev, size_t size, void *cpu_addr,
136 					dma_addr_t dma_handle, enum dma_alloc_type alloc_type,
137 					const char *caller)
138 {
139 	/* this is needed to avoid warning on using freed pointer */
140 	u64 store_cpu_addr = (u64) (uintptr_t) cpu_addr;
141 
142 	switch (alloc_type) {
143 	case DMA_ALLOC_COHERENT:
144 		hdev->asic_funcs->asic_dma_free_coherent(hdev, size, cpu_addr, dma_handle);
145 		break;
146 	case DMA_ALLOC_POOL:
147 		hdev->asic_funcs->asic_dma_pool_free(hdev, cpu_addr, dma_handle);
148 		break;
149 	}
150 
151 	trace_habanalabs_dma_free(hdev->dev, store_cpu_addr, dma_handle, size, caller);
152 }
153 
154 void *hl_asic_dma_alloc_coherent_caller(struct hl_device *hdev, size_t size, dma_addr_t *dma_handle,
155 					gfp_t flag, const char *caller)
156 {
157 	return hl_dma_alloc_common(hdev, size, dma_handle, flag, DMA_ALLOC_COHERENT, caller);
158 }
159 
160 void hl_asic_dma_free_coherent_caller(struct hl_device *hdev, size_t size, void *cpu_addr,
161 					dma_addr_t dma_handle, const char *caller)
162 {
163 	hl_asic_dma_free_common(hdev, size, cpu_addr, dma_handle, DMA_ALLOC_COHERENT, caller);
164 }
165 
166 void *hl_asic_dma_pool_zalloc_caller(struct hl_device *hdev, size_t size, gfp_t mem_flags,
167 					dma_addr_t *dma_handle, const char *caller)
168 {
169 	return hl_dma_alloc_common(hdev, size, dma_handle, mem_flags, DMA_ALLOC_POOL, caller);
170 }
171 
172 void hl_asic_dma_pool_free_caller(struct hl_device *hdev, void *vaddr, dma_addr_t dma_addr,
173 					const char *caller)
174 {
175 	hl_asic_dma_free_common(hdev, 0, vaddr, dma_addr, DMA_ALLOC_POOL, caller);
176 }
177 
178 void *hl_cpu_accessible_dma_pool_alloc(struct hl_device *hdev, size_t size, dma_addr_t *dma_handle)
179 {
180 	return hdev->asic_funcs->cpu_accessible_dma_pool_alloc(hdev, size, dma_handle);
181 }
182 
183 void hl_cpu_accessible_dma_pool_free(struct hl_device *hdev, size_t size, void *vaddr)
184 {
185 	hdev->asic_funcs->cpu_accessible_dma_pool_free(hdev, size, vaddr);
186 }
187 
188 int hl_dma_map_sgtable(struct hl_device *hdev, struct sg_table *sgt, enum dma_data_direction dir)
189 {
190 	struct asic_fixed_properties *prop = &hdev->asic_prop;
191 	struct scatterlist *sg;
192 	int rc, i;
193 
194 	rc = dma_map_sgtable(&hdev->pdev->dev, sgt, dir, 0);
195 	if (rc)
196 		return rc;
197 
198 	/* Shift to the device's base physical address of host memory if necessary */
199 	if (prop->device_dma_offset_for_host_access)
200 		for_each_sgtable_dma_sg(sgt, sg, i)
201 			sg->dma_address += prop->device_dma_offset_for_host_access;
202 
203 	return 0;
204 }
205 
206 void hl_dma_unmap_sgtable(struct hl_device *hdev, struct sg_table *sgt, enum dma_data_direction dir)
207 {
208 	struct asic_fixed_properties *prop = &hdev->asic_prop;
209 	struct scatterlist *sg;
210 	int i;
211 
212 	/* Cancel the device's base physical address of host memory if necessary */
213 	if (prop->device_dma_offset_for_host_access)
214 		for_each_sgtable_dma_sg(sgt, sg, i)
215 			sg->dma_address -= prop->device_dma_offset_for_host_access;
216 
217 	dma_unmap_sgtable(&hdev->pdev->dev, sgt, dir, 0);
218 }
219 
220 /*
221  * hl_access_cfg_region - access the config region
222  *
223  * @hdev: pointer to habanalabs device structure
224  * @addr: the address to access
225  * @val: the value to write from or read to
226  * @acc_type: the type of access (read/write 64/32)
227  */
228 int hl_access_cfg_region(struct hl_device *hdev, u64 addr, u64 *val,
229 	enum debugfs_access_type acc_type)
230 {
231 	struct pci_mem_region *cfg_region = &hdev->pci_mem_region[PCI_REGION_CFG];
232 	u32 val_h, val_l;
233 
234 	if (!IS_ALIGNED(addr, sizeof(u32))) {
235 		dev_err(hdev->dev, "address %#llx not a multiple of %zu\n", addr, sizeof(u32));
236 		return -EINVAL;
237 	}
238 
239 	switch (acc_type) {
240 	case DEBUGFS_READ32:
241 		*val = RREG32(addr - cfg_region->region_base);
242 		break;
243 	case DEBUGFS_WRITE32:
244 		WREG32(addr - cfg_region->region_base, *val);
245 		break;
246 	case DEBUGFS_READ64:
247 		val_l = RREG32(addr - cfg_region->region_base);
248 		val_h = RREG32(addr + sizeof(u32) - cfg_region->region_base);
249 
250 		*val = (((u64) val_h) << 32) | val_l;
251 		break;
252 	case DEBUGFS_WRITE64:
253 		WREG32(addr - cfg_region->region_base, lower_32_bits(*val));
254 		WREG32(addr + sizeof(u32) - cfg_region->region_base, upper_32_bits(*val));
255 		break;
256 	default:
257 		dev_err(hdev->dev, "access type %d is not supported\n", acc_type);
258 		return -EOPNOTSUPP;
259 	}
260 
261 	return 0;
262 }
263 
264 /*
265  * hl_access_dev_mem - access device memory
266  *
267  * @hdev: pointer to habanalabs device structure
268  * @region_type: the type of the region the address belongs to
269  * @addr: the address to access
270  * @val: the value to write from or read to
271  * @acc_type: the type of access (r/w, 32/64)
272  */
273 int hl_access_dev_mem(struct hl_device *hdev, enum pci_region region_type,
274 			u64 addr, u64 *val, enum debugfs_access_type acc_type)
275 {
276 	switch (region_type) {
277 	case PCI_REGION_CFG:
278 		return hl_access_cfg_region(hdev, addr, val, acc_type);
279 	case PCI_REGION_SRAM:
280 	case PCI_REGION_DRAM:
281 		return hl_access_sram_dram_region(hdev, addr, val, acc_type,
282 				region_type, (region_type == PCI_REGION_DRAM));
283 	default:
284 		return -EFAULT;
285 	}
286 
287 	return 0;
288 }
289 
290 void hl_engine_data_sprintf(struct engines_data *e, const char *fmt, ...)
291 {
292 	va_list args;
293 	int str_size;
294 
295 	va_start(args, fmt);
296 	/* Calculate formatted string length. Assuming each string is null terminated, hence
297 	 * increment result by 1
298 	 */
299 	str_size = vsnprintf(NULL, 0, fmt, args) + 1;
300 	va_end(args);
301 
302 	if ((e->actual_size + str_size) < e->allocated_buf_size) {
303 		va_start(args, fmt);
304 		vsnprintf(e->buf + e->actual_size, str_size, fmt, args);
305 		va_end(args);
306 	}
307 
308 	/* Need to update the size even when not updating destination buffer to get the exact size
309 	 * of all input strings
310 	 */
311 	e->actual_size += str_size;
312 }
313 
314 enum hl_device_status hl_device_status(struct hl_device *hdev)
315 {
316 	enum hl_device_status status;
317 
318 	if (hdev->reset_info.in_reset) {
319 		if (hdev->reset_info.in_compute_reset)
320 			status = HL_DEVICE_STATUS_IN_RESET_AFTER_DEVICE_RELEASE;
321 		else
322 			status = HL_DEVICE_STATUS_IN_RESET;
323 	} else if (hdev->reset_info.needs_reset) {
324 		status = HL_DEVICE_STATUS_NEEDS_RESET;
325 	} else if (hdev->disabled) {
326 		status = HL_DEVICE_STATUS_MALFUNCTION;
327 	} else if (!hdev->init_done) {
328 		status = HL_DEVICE_STATUS_IN_DEVICE_CREATION;
329 	} else {
330 		status = HL_DEVICE_STATUS_OPERATIONAL;
331 	}
332 
333 	return status;
334 }
335 
336 bool hl_device_operational(struct hl_device *hdev,
337 		enum hl_device_status *status)
338 {
339 	enum hl_device_status current_status;
340 
341 	current_status = hl_device_status(hdev);
342 	if (status)
343 		*status = current_status;
344 
345 	switch (current_status) {
346 	case HL_DEVICE_STATUS_IN_RESET:
347 	case HL_DEVICE_STATUS_IN_RESET_AFTER_DEVICE_RELEASE:
348 	case HL_DEVICE_STATUS_MALFUNCTION:
349 	case HL_DEVICE_STATUS_NEEDS_RESET:
350 		return false;
351 	case HL_DEVICE_STATUS_OPERATIONAL:
352 	case HL_DEVICE_STATUS_IN_DEVICE_CREATION:
353 	default:
354 		return true;
355 	}
356 }
357 
358 bool hl_ctrl_device_operational(struct hl_device *hdev,
359 		enum hl_device_status *status)
360 {
361 	enum hl_device_status current_status;
362 
363 	current_status = hl_device_status(hdev);
364 	if (status)
365 		*status = current_status;
366 
367 	switch (current_status) {
368 	case HL_DEVICE_STATUS_MALFUNCTION:
369 		return false;
370 	case HL_DEVICE_STATUS_IN_RESET:
371 	case HL_DEVICE_STATUS_IN_RESET_AFTER_DEVICE_RELEASE:
372 	case HL_DEVICE_STATUS_NEEDS_RESET:
373 	case HL_DEVICE_STATUS_OPERATIONAL:
374 	case HL_DEVICE_STATUS_IN_DEVICE_CREATION:
375 	default:
376 		return true;
377 	}
378 }
379 
380 static void print_idle_status_mask(struct hl_device *hdev, const char *message,
381 					u64 idle_mask[HL_BUSY_ENGINES_MASK_EXT_SIZE])
382 {
383 	if (idle_mask[3])
384 		dev_err(hdev->dev, "%s (mask %#llx_%016llx_%016llx_%016llx)\n",
385 			message, idle_mask[3], idle_mask[2], idle_mask[1], idle_mask[0]);
386 	else if (idle_mask[2])
387 		dev_err(hdev->dev, "%s (mask %#llx_%016llx_%016llx)\n",
388 			message, idle_mask[2], idle_mask[1], idle_mask[0]);
389 	else if (idle_mask[1])
390 		dev_err(hdev->dev, "%s (mask %#llx_%016llx)\n",
391 			message, idle_mask[1], idle_mask[0]);
392 	else
393 		dev_err(hdev->dev, "%s (mask %#llx)\n", message, idle_mask[0]);
394 }
395 
396 static void hpriv_release(struct kref *ref)
397 {
398 	u64 idle_mask[HL_BUSY_ENGINES_MASK_EXT_SIZE] = {0};
399 	bool reset_device, device_is_idle = true;
400 	struct hl_fpriv *hpriv;
401 	struct hl_device *hdev;
402 
403 	hpriv = container_of(ref, struct hl_fpriv, refcount);
404 
405 	hdev = hpriv->hdev;
406 
407 	hdev->asic_funcs->send_device_activity(hdev, false);
408 
409 	put_pid(hpriv->taskpid);
410 
411 	hl_debugfs_remove_file(hpriv);
412 
413 	mutex_destroy(&hpriv->ctx_lock);
414 	mutex_destroy(&hpriv->restore_phase_mutex);
415 
416 	/* There should be no memory buffers at this point and handles IDR can be destroyed */
417 	hl_mem_mgr_idr_destroy(&hpriv->mem_mgr);
418 
419 	/* Device should be reset if reset-upon-device-release is enabled, or if there is a pending
420 	 * reset that waits for device release.
421 	 */
422 	reset_device = hdev->reset_upon_device_release || hdev->reset_info.watchdog_active;
423 
424 	/* Check the device idle status and reset if not idle.
425 	 * Skip it if already in reset, or if device is going to be reset in any case.
426 	 */
427 	if (!hdev->reset_info.in_reset && !reset_device && hdev->pdev && !hdev->pldm)
428 		device_is_idle = hdev->asic_funcs->is_device_idle(hdev, idle_mask,
429 							HL_BUSY_ENGINES_MASK_EXT_SIZE, NULL);
430 	if (!device_is_idle) {
431 		print_idle_status_mask(hdev, "device is not idle after user context is closed",
432 					idle_mask);
433 		reset_device = true;
434 	}
435 
436 	/* We need to remove the user from the list to make sure the reset process won't
437 	 * try to kill the user process. Because, if we got here, it means there are no
438 	 * more driver/device resources that the user process is occupying so there is
439 	 * no need to kill it
440 	 *
441 	 * However, we can't set the compute_ctx to NULL at this stage. This is to prevent
442 	 * a race between the release and opening the device again. We don't want to let
443 	 * a user open the device while there a reset is about to happen.
444 	 */
445 	mutex_lock(&hdev->fpriv_list_lock);
446 	list_del(&hpriv->dev_node);
447 	mutex_unlock(&hdev->fpriv_list_lock);
448 
449 	if (reset_device) {
450 		hl_device_reset(hdev, HL_DRV_RESET_DEV_RELEASE);
451 	} else {
452 		/* Scrubbing is handled within hl_device_reset(), so here need to do it directly */
453 		int rc = hdev->asic_funcs->scrub_device_mem(hdev);
454 
455 		if (rc)
456 			dev_err(hdev->dev, "failed to scrub memory from hpriv release (%d)\n", rc);
457 	}
458 
459 	/* Now we can mark the compute_ctx as not active. Even if a reset is running in a different
460 	 * thread, we don't care because the in_reset is marked so if a user will try to open
461 	 * the device it will fail on that, even if compute_ctx is false.
462 	 */
463 	mutex_lock(&hdev->fpriv_list_lock);
464 	hdev->is_compute_ctx_active = false;
465 	mutex_unlock(&hdev->fpriv_list_lock);
466 
467 	hdev->compute_ctx_in_release = 0;
468 
469 	/* release the eventfd */
470 	if (hpriv->notifier_event.eventfd)
471 		eventfd_ctx_put(hpriv->notifier_event.eventfd);
472 
473 	mutex_destroy(&hpriv->notifier_event.lock);
474 
475 	kfree(hpriv);
476 }
477 
478 void hl_hpriv_get(struct hl_fpriv *hpriv)
479 {
480 	kref_get(&hpriv->refcount);
481 }
482 
483 int hl_hpriv_put(struct hl_fpriv *hpriv)
484 {
485 	return kref_put(&hpriv->refcount, hpriv_release);
486 }
487 
488 static void print_device_in_use_info(struct hl_device *hdev, const char *message)
489 {
490 	u32 active_cs_num, dmabuf_export_cnt;
491 	bool unknown_reason = true;
492 	char buf[128];
493 	size_t size;
494 	int offset;
495 
496 	size = sizeof(buf);
497 	offset = 0;
498 
499 	active_cs_num = hl_get_active_cs_num(hdev);
500 	if (active_cs_num) {
501 		unknown_reason = false;
502 		offset += scnprintf(buf + offset, size - offset, " [%u active CS]", active_cs_num);
503 	}
504 
505 	dmabuf_export_cnt = atomic_read(&hdev->dmabuf_export_cnt);
506 	if (dmabuf_export_cnt) {
507 		unknown_reason = false;
508 		offset += scnprintf(buf + offset, size - offset, " [%u exported dma-buf]",
509 					dmabuf_export_cnt);
510 	}
511 
512 	if (unknown_reason)
513 		scnprintf(buf + offset, size - offset, " [unknown reason]");
514 
515 	dev_notice(hdev->dev, "%s%s\n", message, buf);
516 }
517 
518 /*
519  * hl_device_release - release function for habanalabs device
520  *
521  * @inode: pointer to inode structure
522  * @filp: pointer to file structure
523  *
524  * Called when process closes an habanalabs device
525  */
526 static int hl_device_release(struct inode *inode, struct file *filp)
527 {
528 	struct hl_fpriv *hpriv = filp->private_data;
529 	struct hl_device *hdev = hpriv->hdev;
530 
531 	filp->private_data = NULL;
532 
533 	if (!hdev) {
534 		pr_crit("Closing FD after device was removed. Memory leak will occur and it is advised to reboot.\n");
535 		put_pid(hpriv->taskpid);
536 		return 0;
537 	}
538 
539 	hl_ctx_mgr_fini(hdev, &hpriv->ctx_mgr);
540 
541 	/* Memory buffers might be still in use at this point and thus the handles IDR destruction
542 	 * is postponed to hpriv_release().
543 	 */
544 	hl_mem_mgr_fini(&hpriv->mem_mgr);
545 
546 	hdev->compute_ctx_in_release = 1;
547 
548 	if (!hl_hpriv_put(hpriv)) {
549 		print_device_in_use_info(hdev, "User process closed FD but device still in use");
550 		hl_device_reset(hdev, HL_DRV_RESET_HARD);
551 	}
552 
553 	hdev->last_open_session_duration_jif = jiffies - hdev->last_successful_open_jif;
554 
555 	return 0;
556 }
557 
558 static int hl_device_release_ctrl(struct inode *inode, struct file *filp)
559 {
560 	struct hl_fpriv *hpriv = filp->private_data;
561 	struct hl_device *hdev = hpriv->hdev;
562 
563 	filp->private_data = NULL;
564 
565 	if (!hdev) {
566 		pr_err("Closing FD after device was removed\n");
567 		goto out;
568 	}
569 
570 	mutex_lock(&hdev->fpriv_ctrl_list_lock);
571 	list_del(&hpriv->dev_node);
572 	mutex_unlock(&hdev->fpriv_ctrl_list_lock);
573 out:
574 	/* release the eventfd */
575 	if (hpriv->notifier_event.eventfd)
576 		eventfd_ctx_put(hpriv->notifier_event.eventfd);
577 
578 	mutex_destroy(&hpriv->notifier_event.lock);
579 	put_pid(hpriv->taskpid);
580 
581 	kfree(hpriv);
582 
583 	return 0;
584 }
585 
586 /*
587  * hl_mmap - mmap function for habanalabs device
588  *
589  * @*filp: pointer to file structure
590  * @*vma: pointer to vm_area_struct of the process
591  *
592  * Called when process does an mmap on habanalabs device. Call the relevant mmap
593  * function at the end of the common code.
594  */
595 static int hl_mmap(struct file *filp, struct vm_area_struct *vma)
596 {
597 	struct hl_fpriv *hpriv = filp->private_data;
598 	struct hl_device *hdev = hpriv->hdev;
599 	unsigned long vm_pgoff;
600 
601 	if (!hdev) {
602 		pr_err_ratelimited("Trying to mmap after device was removed! Please close FD\n");
603 		return -ENODEV;
604 	}
605 
606 	vm_pgoff = vma->vm_pgoff;
607 
608 	switch (vm_pgoff & HL_MMAP_TYPE_MASK) {
609 	case HL_MMAP_TYPE_BLOCK:
610 		vma->vm_pgoff = HL_MMAP_OFFSET_VALUE_GET(vm_pgoff);
611 		return hl_hw_block_mmap(hpriv, vma);
612 
613 	case HL_MMAP_TYPE_CB:
614 	case HL_MMAP_TYPE_TS_BUFF:
615 		return hl_mem_mgr_mmap(&hpriv->mem_mgr, vma, NULL);
616 	}
617 	return -EINVAL;
618 }
619 
620 static const struct file_operations hl_ops = {
621 	.owner = THIS_MODULE,
622 	.open = hl_device_open,
623 	.release = hl_device_release,
624 	.mmap = hl_mmap,
625 	.unlocked_ioctl = hl_ioctl,
626 	.compat_ioctl = hl_ioctl
627 };
628 
629 static const struct file_operations hl_ctrl_ops = {
630 	.owner = THIS_MODULE,
631 	.open = hl_device_open_ctrl,
632 	.release = hl_device_release_ctrl,
633 	.unlocked_ioctl = hl_ioctl_control,
634 	.compat_ioctl = hl_ioctl_control
635 };
636 
637 static void device_release_func(struct device *dev)
638 {
639 	kfree(dev);
640 }
641 
642 /*
643  * device_init_cdev - Initialize cdev and device for habanalabs device
644  *
645  * @hdev: pointer to habanalabs device structure
646  * @class: pointer to the class object of the device
647  * @minor: minor number of the specific device
648  * @fpos: file operations to install for this device
649  * @name: name of the device as it will appear in the filesystem
650  * @cdev: pointer to the char device object that will be initialized
651  * @dev: pointer to the device object that will be initialized
652  *
653  * Initialize a cdev and a Linux device for habanalabs's device.
654  */
655 static int device_init_cdev(struct hl_device *hdev, struct class *class,
656 				int minor, const struct file_operations *fops,
657 				char *name, struct cdev *cdev,
658 				struct device **dev)
659 {
660 	cdev_init(cdev, fops);
661 	cdev->owner = THIS_MODULE;
662 
663 	*dev = kzalloc(sizeof(**dev), GFP_KERNEL);
664 	if (!*dev)
665 		return -ENOMEM;
666 
667 	device_initialize(*dev);
668 	(*dev)->devt = MKDEV(hdev->major, minor);
669 	(*dev)->class = class;
670 	(*dev)->release = device_release_func;
671 	dev_set_drvdata(*dev, hdev);
672 	dev_set_name(*dev, "%s", name);
673 
674 	return 0;
675 }
676 
677 static int device_cdev_sysfs_add(struct hl_device *hdev)
678 {
679 	int rc;
680 
681 	rc = cdev_device_add(&hdev->cdev, hdev->dev);
682 	if (rc) {
683 		dev_err(hdev->dev,
684 			"failed to add a char device to the system\n");
685 		return rc;
686 	}
687 
688 	rc = cdev_device_add(&hdev->cdev_ctrl, hdev->dev_ctrl);
689 	if (rc) {
690 		dev_err(hdev->dev,
691 			"failed to add a control char device to the system\n");
692 		goto delete_cdev_device;
693 	}
694 
695 	/* hl_sysfs_init() must be done after adding the device to the system */
696 	rc = hl_sysfs_init(hdev);
697 	if (rc) {
698 		dev_err(hdev->dev, "failed to initialize sysfs\n");
699 		goto delete_ctrl_cdev_device;
700 	}
701 
702 	hdev->cdev_sysfs_created = true;
703 
704 	return 0;
705 
706 delete_ctrl_cdev_device:
707 	cdev_device_del(&hdev->cdev_ctrl, hdev->dev_ctrl);
708 delete_cdev_device:
709 	cdev_device_del(&hdev->cdev, hdev->dev);
710 	return rc;
711 }
712 
713 static void device_cdev_sysfs_del(struct hl_device *hdev)
714 {
715 	if (!hdev->cdev_sysfs_created)
716 		goto put_devices;
717 
718 	hl_sysfs_fini(hdev);
719 	cdev_device_del(&hdev->cdev_ctrl, hdev->dev_ctrl);
720 	cdev_device_del(&hdev->cdev, hdev->dev);
721 
722 put_devices:
723 	put_device(hdev->dev);
724 	put_device(hdev->dev_ctrl);
725 }
726 
727 static void device_hard_reset_pending(struct work_struct *work)
728 {
729 	struct hl_device_reset_work *device_reset_work =
730 		container_of(work, struct hl_device_reset_work, reset_work.work);
731 	struct hl_device *hdev = device_reset_work->hdev;
732 	u32 flags;
733 	int rc;
734 
735 	flags = device_reset_work->flags | HL_DRV_RESET_FROM_RESET_THR;
736 
737 	rc = hl_device_reset(hdev, flags);
738 
739 	if ((rc == -EBUSY) && !hdev->device_fini_pending) {
740 		struct hl_ctx *ctx = hl_get_compute_ctx(hdev);
741 
742 		if (ctx) {
743 			/* The read refcount value should subtracted by one, because the read is
744 			 * protected with hl_get_compute_ctx().
745 			 */
746 			dev_info(hdev->dev,
747 				"Could not reset device (compute_ctx refcount %u). will try again in %u seconds",
748 				kref_read(&ctx->refcount) - 1, HL_PENDING_RESET_PER_SEC);
749 			hl_ctx_put(ctx);
750 		} else {
751 			dev_info(hdev->dev, "Could not reset device. will try again in %u seconds",
752 				HL_PENDING_RESET_PER_SEC);
753 		}
754 
755 		queue_delayed_work(hdev->reset_wq, &device_reset_work->reset_work,
756 					msecs_to_jiffies(HL_PENDING_RESET_PER_SEC * 1000));
757 	}
758 }
759 
760 static void device_release_watchdog_func(struct work_struct *work)
761 {
762 	struct hl_device_reset_work *watchdog_work =
763 			container_of(work, struct hl_device_reset_work, reset_work.work);
764 	struct hl_device *hdev = watchdog_work->hdev;
765 	u32 flags;
766 
767 	dev_dbg(hdev->dev, "Device wasn't released in time. Initiate hard-reset.\n");
768 
769 	flags = watchdog_work->flags | HL_DRV_RESET_HARD | HL_DRV_RESET_FROM_WD_THR;
770 
771 	hl_device_reset(hdev, flags);
772 }
773 
774 /*
775  * device_early_init - do some early initialization for the habanalabs device
776  *
777  * @hdev: pointer to habanalabs device structure
778  *
779  * Install the relevant function pointers and call the early_init function,
780  * if such a function exists
781  */
782 static int device_early_init(struct hl_device *hdev)
783 {
784 	int i, rc;
785 	char workq_name[32];
786 
787 	switch (hdev->asic_type) {
788 	case ASIC_GOYA:
789 		goya_set_asic_funcs(hdev);
790 		strscpy(hdev->asic_name, "GOYA", sizeof(hdev->asic_name));
791 		break;
792 	case ASIC_GAUDI:
793 		gaudi_set_asic_funcs(hdev);
794 		strscpy(hdev->asic_name, "GAUDI", sizeof(hdev->asic_name));
795 		break;
796 	case ASIC_GAUDI_SEC:
797 		gaudi_set_asic_funcs(hdev);
798 		strscpy(hdev->asic_name, "GAUDI SEC", sizeof(hdev->asic_name));
799 		break;
800 	case ASIC_GAUDI2:
801 		gaudi2_set_asic_funcs(hdev);
802 		strscpy(hdev->asic_name, "GAUDI2", sizeof(hdev->asic_name));
803 		break;
804 	case ASIC_GAUDI2B:
805 		gaudi2_set_asic_funcs(hdev);
806 		strscpy(hdev->asic_name, "GAUDI2B", sizeof(hdev->asic_name));
807 		break;
808 		break;
809 	default:
810 		dev_err(hdev->dev, "Unrecognized ASIC type %d\n",
811 			hdev->asic_type);
812 		return -EINVAL;
813 	}
814 
815 	rc = hdev->asic_funcs->early_init(hdev);
816 	if (rc)
817 		return rc;
818 
819 	rc = hl_asid_init(hdev);
820 	if (rc)
821 		goto early_fini;
822 
823 	if (hdev->asic_prop.completion_queues_count) {
824 		hdev->cq_wq = kcalloc(hdev->asic_prop.completion_queues_count,
825 				sizeof(struct workqueue_struct *),
826 				GFP_KERNEL);
827 		if (!hdev->cq_wq) {
828 			rc = -ENOMEM;
829 			goto asid_fini;
830 		}
831 	}
832 
833 	for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++) {
834 		snprintf(workq_name, 32, "hl%u-free-jobs-%u", hdev->cdev_idx, (u32) i);
835 		hdev->cq_wq[i] = create_singlethread_workqueue(workq_name);
836 		if (hdev->cq_wq[i] == NULL) {
837 			dev_err(hdev->dev, "Failed to allocate CQ workqueue\n");
838 			rc = -ENOMEM;
839 			goto free_cq_wq;
840 		}
841 	}
842 
843 	snprintf(workq_name, 32, "hl%u-events", hdev->cdev_idx);
844 	hdev->eq_wq = create_singlethread_workqueue(workq_name);
845 	if (hdev->eq_wq == NULL) {
846 		dev_err(hdev->dev, "Failed to allocate EQ workqueue\n");
847 		rc = -ENOMEM;
848 		goto free_cq_wq;
849 	}
850 
851 	snprintf(workq_name, 32, "hl%u-cs-completions", hdev->cdev_idx);
852 	hdev->cs_cmplt_wq = alloc_workqueue(workq_name, WQ_UNBOUND, 0);
853 	if (!hdev->cs_cmplt_wq) {
854 		dev_err(hdev->dev,
855 			"Failed to allocate CS completions workqueue\n");
856 		rc = -ENOMEM;
857 		goto free_eq_wq;
858 	}
859 
860 	snprintf(workq_name, 32, "hl%u-ts-free-obj", hdev->cdev_idx);
861 	hdev->ts_free_obj_wq = alloc_workqueue(workq_name, WQ_UNBOUND, 0);
862 	if (!hdev->ts_free_obj_wq) {
863 		dev_err(hdev->dev,
864 			"Failed to allocate Timestamp registration free workqueue\n");
865 		rc = -ENOMEM;
866 		goto free_cs_cmplt_wq;
867 	}
868 
869 	snprintf(workq_name, 32, "hl%u-prefetch", hdev->cdev_idx);
870 	hdev->prefetch_wq = alloc_workqueue(workq_name, WQ_UNBOUND, 0);
871 	if (!hdev->prefetch_wq) {
872 		dev_err(hdev->dev, "Failed to allocate MMU prefetch workqueue\n");
873 		rc = -ENOMEM;
874 		goto free_ts_free_wq;
875 	}
876 
877 	hdev->hl_chip_info = kzalloc(sizeof(struct hwmon_chip_info), GFP_KERNEL);
878 	if (!hdev->hl_chip_info) {
879 		rc = -ENOMEM;
880 		goto free_prefetch_wq;
881 	}
882 
883 	rc = hl_mmu_if_set_funcs(hdev);
884 	if (rc)
885 		goto free_chip_info;
886 
887 	hl_mem_mgr_init(hdev->dev, &hdev->kernel_mem_mgr);
888 
889 	snprintf(workq_name, 32, "hl%u_device_reset", hdev->cdev_idx);
890 	hdev->reset_wq = create_singlethread_workqueue(workq_name);
891 	if (!hdev->reset_wq) {
892 		rc = -ENOMEM;
893 		dev_err(hdev->dev, "Failed to create device reset WQ\n");
894 		goto free_cb_mgr;
895 	}
896 
897 	INIT_DELAYED_WORK(&hdev->device_reset_work.reset_work, device_hard_reset_pending);
898 	hdev->device_reset_work.hdev = hdev;
899 	hdev->device_fini_pending = 0;
900 
901 	INIT_DELAYED_WORK(&hdev->device_release_watchdog_work.reset_work,
902 				device_release_watchdog_func);
903 	hdev->device_release_watchdog_work.hdev = hdev;
904 
905 	mutex_init(&hdev->send_cpu_message_lock);
906 	mutex_init(&hdev->debug_lock);
907 	INIT_LIST_HEAD(&hdev->cs_mirror_list);
908 	spin_lock_init(&hdev->cs_mirror_lock);
909 	spin_lock_init(&hdev->reset_info.lock);
910 	INIT_LIST_HEAD(&hdev->fpriv_list);
911 	INIT_LIST_HEAD(&hdev->fpriv_ctrl_list);
912 	mutex_init(&hdev->fpriv_list_lock);
913 	mutex_init(&hdev->fpriv_ctrl_list_lock);
914 	mutex_init(&hdev->clk_throttling.lock);
915 
916 	return 0;
917 
918 free_cb_mgr:
919 	hl_mem_mgr_fini(&hdev->kernel_mem_mgr);
920 	hl_mem_mgr_idr_destroy(&hdev->kernel_mem_mgr);
921 free_chip_info:
922 	kfree(hdev->hl_chip_info);
923 free_prefetch_wq:
924 	destroy_workqueue(hdev->prefetch_wq);
925 free_ts_free_wq:
926 	destroy_workqueue(hdev->ts_free_obj_wq);
927 free_cs_cmplt_wq:
928 	destroy_workqueue(hdev->cs_cmplt_wq);
929 free_eq_wq:
930 	destroy_workqueue(hdev->eq_wq);
931 free_cq_wq:
932 	for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
933 		if (hdev->cq_wq[i])
934 			destroy_workqueue(hdev->cq_wq[i]);
935 	kfree(hdev->cq_wq);
936 asid_fini:
937 	hl_asid_fini(hdev);
938 early_fini:
939 	if (hdev->asic_funcs->early_fini)
940 		hdev->asic_funcs->early_fini(hdev);
941 
942 	return rc;
943 }
944 
945 /*
946  * device_early_fini - finalize all that was done in device_early_init
947  *
948  * @hdev: pointer to habanalabs device structure
949  *
950  */
951 static void device_early_fini(struct hl_device *hdev)
952 {
953 	int i;
954 
955 	mutex_destroy(&hdev->debug_lock);
956 	mutex_destroy(&hdev->send_cpu_message_lock);
957 
958 	mutex_destroy(&hdev->fpriv_list_lock);
959 	mutex_destroy(&hdev->fpriv_ctrl_list_lock);
960 
961 	mutex_destroy(&hdev->clk_throttling.lock);
962 
963 	hl_mem_mgr_fini(&hdev->kernel_mem_mgr);
964 	hl_mem_mgr_idr_destroy(&hdev->kernel_mem_mgr);
965 
966 	kfree(hdev->hl_chip_info);
967 
968 	destroy_workqueue(hdev->prefetch_wq);
969 	destroy_workqueue(hdev->ts_free_obj_wq);
970 	destroy_workqueue(hdev->cs_cmplt_wq);
971 	destroy_workqueue(hdev->eq_wq);
972 	destroy_workqueue(hdev->reset_wq);
973 
974 	for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
975 		destroy_workqueue(hdev->cq_wq[i]);
976 	kfree(hdev->cq_wq);
977 
978 	hl_asid_fini(hdev);
979 
980 	if (hdev->asic_funcs->early_fini)
981 		hdev->asic_funcs->early_fini(hdev);
982 }
983 
984 static void hl_device_heartbeat(struct work_struct *work)
985 {
986 	struct hl_device *hdev = container_of(work, struct hl_device,
987 						work_heartbeat.work);
988 	struct hl_info_fw_err_info info = {0};
989 	u64 event_mask = HL_NOTIFIER_EVENT_DEVICE_RESET | HL_NOTIFIER_EVENT_DEVICE_UNAVAILABLE;
990 
991 	if (!hl_device_operational(hdev, NULL))
992 		goto reschedule;
993 
994 	if (!hdev->asic_funcs->send_heartbeat(hdev))
995 		goto reschedule;
996 
997 	if (hl_device_operational(hdev, NULL))
998 		dev_err(hdev->dev, "Device heartbeat failed!\n");
999 
1000 	info.err_type = HL_INFO_FW_HEARTBEAT_ERR;
1001 	info.event_mask = &event_mask;
1002 	hl_handle_fw_err(hdev, &info);
1003 	hl_device_cond_reset(hdev, HL_DRV_RESET_HARD | HL_DRV_RESET_HEARTBEAT, event_mask);
1004 
1005 	return;
1006 
1007 reschedule:
1008 	/*
1009 	 * prev_reset_trigger tracks consecutive fatal h/w errors until first
1010 	 * heartbeat immediately post reset.
1011 	 * If control reached here, then at least one heartbeat work has been
1012 	 * scheduled since last reset/init cycle.
1013 	 * So if the device is not already in reset cycle, reset the flag
1014 	 * prev_reset_trigger as no reset occurred with HL_DRV_RESET_FW_FATAL_ERR
1015 	 * status for at least one heartbeat. From this point driver restarts
1016 	 * tracking future consecutive fatal errors.
1017 	 */
1018 	if (!hdev->reset_info.in_reset)
1019 		hdev->reset_info.prev_reset_trigger = HL_RESET_TRIGGER_DEFAULT;
1020 
1021 	schedule_delayed_work(&hdev->work_heartbeat,
1022 			usecs_to_jiffies(HL_HEARTBEAT_PER_USEC));
1023 }
1024 
1025 /*
1026  * device_late_init - do late stuff initialization for the habanalabs device
1027  *
1028  * @hdev: pointer to habanalabs device structure
1029  *
1030  * Do stuff that either needs the device H/W queues to be active or needs
1031  * to happen after all the rest of the initialization is finished
1032  */
1033 static int device_late_init(struct hl_device *hdev)
1034 {
1035 	int rc;
1036 
1037 	if (hdev->asic_funcs->late_init) {
1038 		rc = hdev->asic_funcs->late_init(hdev);
1039 		if (rc) {
1040 			dev_err(hdev->dev,
1041 				"failed late initialization for the H/W\n");
1042 			return rc;
1043 		}
1044 	}
1045 
1046 	hdev->high_pll = hdev->asic_prop.high_pll;
1047 
1048 	if (hdev->heartbeat) {
1049 		INIT_DELAYED_WORK(&hdev->work_heartbeat, hl_device_heartbeat);
1050 		schedule_delayed_work(&hdev->work_heartbeat,
1051 				usecs_to_jiffies(HL_HEARTBEAT_PER_USEC));
1052 	}
1053 
1054 	hdev->late_init_done = true;
1055 
1056 	return 0;
1057 }
1058 
1059 /*
1060  * device_late_fini - finalize all that was done in device_late_init
1061  *
1062  * @hdev: pointer to habanalabs device structure
1063  *
1064  */
1065 static void device_late_fini(struct hl_device *hdev)
1066 {
1067 	if (!hdev->late_init_done)
1068 		return;
1069 
1070 	if (hdev->heartbeat)
1071 		cancel_delayed_work_sync(&hdev->work_heartbeat);
1072 
1073 	if (hdev->asic_funcs->late_fini)
1074 		hdev->asic_funcs->late_fini(hdev);
1075 
1076 	hdev->late_init_done = false;
1077 }
1078 
1079 int hl_device_utilization(struct hl_device *hdev, u32 *utilization)
1080 {
1081 	u64 max_power, curr_power, dc_power, dividend, divisor;
1082 	int rc;
1083 
1084 	max_power = hdev->max_power;
1085 	dc_power = hdev->asic_prop.dc_power_default;
1086 	divisor = max_power - dc_power;
1087 	if (!divisor) {
1088 		dev_warn(hdev->dev, "device utilization is not supported\n");
1089 		return -EOPNOTSUPP;
1090 	}
1091 	rc = hl_fw_cpucp_power_get(hdev, &curr_power);
1092 
1093 	if (rc)
1094 		return rc;
1095 
1096 	curr_power = clamp(curr_power, dc_power, max_power);
1097 
1098 	dividend = (curr_power - dc_power) * 100;
1099 	*utilization = (u32) div_u64(dividend, divisor);
1100 
1101 	return 0;
1102 }
1103 
1104 int hl_device_set_debug_mode(struct hl_device *hdev, struct hl_ctx *ctx, bool enable)
1105 {
1106 	int rc = 0;
1107 
1108 	mutex_lock(&hdev->debug_lock);
1109 
1110 	if (!enable) {
1111 		if (!hdev->in_debug) {
1112 			dev_err(hdev->dev,
1113 				"Failed to disable debug mode because device was not in debug mode\n");
1114 			rc = -EFAULT;
1115 			goto out;
1116 		}
1117 
1118 		if (!hdev->reset_info.hard_reset_pending)
1119 			hdev->asic_funcs->halt_coresight(hdev, ctx);
1120 
1121 		hdev->in_debug = 0;
1122 
1123 		goto out;
1124 	}
1125 
1126 	if (hdev->in_debug) {
1127 		dev_err(hdev->dev,
1128 			"Failed to enable debug mode because device is already in debug mode\n");
1129 		rc = -EFAULT;
1130 		goto out;
1131 	}
1132 
1133 	hdev->in_debug = 1;
1134 
1135 out:
1136 	mutex_unlock(&hdev->debug_lock);
1137 
1138 	return rc;
1139 }
1140 
1141 static void take_release_locks(struct hl_device *hdev)
1142 {
1143 	/* Flush anyone that is inside the critical section of enqueue
1144 	 * jobs to the H/W
1145 	 */
1146 	hdev->asic_funcs->hw_queues_lock(hdev);
1147 	hdev->asic_funcs->hw_queues_unlock(hdev);
1148 
1149 	/* Flush processes that are sending message to CPU */
1150 	mutex_lock(&hdev->send_cpu_message_lock);
1151 	mutex_unlock(&hdev->send_cpu_message_lock);
1152 
1153 	/* Flush anyone that is inside device open */
1154 	mutex_lock(&hdev->fpriv_list_lock);
1155 	mutex_unlock(&hdev->fpriv_list_lock);
1156 	mutex_lock(&hdev->fpriv_ctrl_list_lock);
1157 	mutex_unlock(&hdev->fpriv_ctrl_list_lock);
1158 }
1159 
1160 static void cleanup_resources(struct hl_device *hdev, bool hard_reset, bool fw_reset,
1161 				bool skip_wq_flush)
1162 {
1163 	if (hard_reset)
1164 		device_late_fini(hdev);
1165 
1166 	/*
1167 	 * Halt the engines and disable interrupts so we won't get any more
1168 	 * completions from H/W and we won't have any accesses from the
1169 	 * H/W to the host machine
1170 	 */
1171 	hdev->asic_funcs->halt_engines(hdev, hard_reset, fw_reset);
1172 
1173 	/* Go over all the queues, release all CS and their jobs */
1174 	hl_cs_rollback_all(hdev, skip_wq_flush);
1175 
1176 	/* flush the MMU prefetch workqueue */
1177 	flush_workqueue(hdev->prefetch_wq);
1178 
1179 	/* Release all pending user interrupts, each pending user interrupt
1180 	 * holds a reference to user context
1181 	 */
1182 	hl_release_pending_user_interrupts(hdev);
1183 }
1184 
1185 /*
1186  * hl_device_suspend - initiate device suspend
1187  *
1188  * @hdev: pointer to habanalabs device structure
1189  *
1190  * Puts the hw in the suspend state (all asics).
1191  * Returns 0 for success or an error on failure.
1192  * Called at driver suspend.
1193  */
1194 int hl_device_suspend(struct hl_device *hdev)
1195 {
1196 	int rc;
1197 
1198 	pci_save_state(hdev->pdev);
1199 
1200 	/* Block future CS/VM/JOB completion operations */
1201 	spin_lock(&hdev->reset_info.lock);
1202 	if (hdev->reset_info.in_reset) {
1203 		spin_unlock(&hdev->reset_info.lock);
1204 		dev_err(hdev->dev, "Can't suspend while in reset\n");
1205 		return -EIO;
1206 	}
1207 	hdev->reset_info.in_reset = 1;
1208 	spin_unlock(&hdev->reset_info.lock);
1209 
1210 	/* This blocks all other stuff that is not blocked by in_reset */
1211 	hdev->disabled = true;
1212 
1213 	take_release_locks(hdev);
1214 
1215 	rc = hdev->asic_funcs->suspend(hdev);
1216 	if (rc)
1217 		dev_err(hdev->dev,
1218 			"Failed to disable PCI access of device CPU\n");
1219 
1220 	/* Shut down the device */
1221 	pci_disable_device(hdev->pdev);
1222 	pci_set_power_state(hdev->pdev, PCI_D3hot);
1223 
1224 	return 0;
1225 }
1226 
1227 /*
1228  * hl_device_resume - initiate device resume
1229  *
1230  * @hdev: pointer to habanalabs device structure
1231  *
1232  * Bring the hw back to operating state (all asics).
1233  * Returns 0 for success or an error on failure.
1234  * Called at driver resume.
1235  */
1236 int hl_device_resume(struct hl_device *hdev)
1237 {
1238 	int rc;
1239 
1240 	pci_set_power_state(hdev->pdev, PCI_D0);
1241 	pci_restore_state(hdev->pdev);
1242 	rc = pci_enable_device_mem(hdev->pdev);
1243 	if (rc) {
1244 		dev_err(hdev->dev,
1245 			"Failed to enable PCI device in resume\n");
1246 		return rc;
1247 	}
1248 
1249 	pci_set_master(hdev->pdev);
1250 
1251 	rc = hdev->asic_funcs->resume(hdev);
1252 	if (rc) {
1253 		dev_err(hdev->dev, "Failed to resume device after suspend\n");
1254 		goto disable_device;
1255 	}
1256 
1257 
1258 	/* 'in_reset' was set to true during suspend, now we must clear it in order
1259 	 * for hard reset to be performed
1260 	 */
1261 	spin_lock(&hdev->reset_info.lock);
1262 	hdev->reset_info.in_reset = 0;
1263 	spin_unlock(&hdev->reset_info.lock);
1264 
1265 	rc = hl_device_reset(hdev, HL_DRV_RESET_HARD);
1266 	if (rc) {
1267 		dev_err(hdev->dev, "Failed to reset device during resume\n");
1268 		goto disable_device;
1269 	}
1270 
1271 	return 0;
1272 
1273 disable_device:
1274 	pci_disable_device(hdev->pdev);
1275 
1276 	return rc;
1277 }
1278 
1279 static int device_kill_open_processes(struct hl_device *hdev, u32 timeout, bool control_dev)
1280 {
1281 	struct task_struct *task = NULL;
1282 	struct list_head *fd_list;
1283 	struct hl_fpriv	*hpriv;
1284 	struct mutex *fd_lock;
1285 	u32 pending_cnt;
1286 
1287 	fd_lock = control_dev ? &hdev->fpriv_ctrl_list_lock : &hdev->fpriv_list_lock;
1288 	fd_list = control_dev ? &hdev->fpriv_ctrl_list : &hdev->fpriv_list;
1289 
1290 	/* Giving time for user to close FD, and for processes that are inside
1291 	 * hl_device_open to finish
1292 	 */
1293 	if (!list_empty(fd_list))
1294 		ssleep(1);
1295 
1296 	if (timeout) {
1297 		pending_cnt = timeout;
1298 	} else {
1299 		if (hdev->process_kill_trial_cnt) {
1300 			/* Processes have been already killed */
1301 			pending_cnt = 1;
1302 			goto wait_for_processes;
1303 		} else {
1304 			/* Wait a small period after process kill */
1305 			pending_cnt = HL_PENDING_RESET_PER_SEC;
1306 		}
1307 	}
1308 
1309 	mutex_lock(fd_lock);
1310 
1311 	/* This section must be protected because we are dereferencing
1312 	 * pointers that are freed if the process exits
1313 	 */
1314 	list_for_each_entry(hpriv, fd_list, dev_node) {
1315 		task = get_pid_task(hpriv->taskpid, PIDTYPE_PID);
1316 		if (task) {
1317 			dev_info(hdev->dev, "Killing user process pid=%d\n",
1318 				task_pid_nr(task));
1319 			send_sig(SIGKILL, task, 1);
1320 			usleep_range(1000, 10000);
1321 
1322 			put_task_struct(task);
1323 		} else {
1324 			/*
1325 			 * If we got here, it means that process was killed from outside the driver
1326 			 * right after it started looping on fd_list and before get_pid_task, thus
1327 			 * we don't need to kill it.
1328 			 */
1329 			dev_dbg(hdev->dev,
1330 				"Can't get task struct for user process, assuming process was killed from outside the driver\n");
1331 		}
1332 	}
1333 
1334 	mutex_unlock(fd_lock);
1335 
1336 	/*
1337 	 * We killed the open users, but that doesn't mean they are closed.
1338 	 * It could be that they are running a long cleanup phase in the driver
1339 	 * e.g. MMU unmappings, or running other long teardown flow even before
1340 	 * our cleanup.
1341 	 * Therefore we need to wait again to make sure they are closed before
1342 	 * continuing with the reset.
1343 	 */
1344 
1345 wait_for_processes:
1346 	while ((!list_empty(fd_list)) && (pending_cnt)) {
1347 		dev_dbg(hdev->dev,
1348 			"Waiting for all unmap operations to finish before hard reset\n");
1349 
1350 		pending_cnt--;
1351 
1352 		ssleep(1);
1353 	}
1354 
1355 	/* All processes exited successfully */
1356 	if (list_empty(fd_list))
1357 		return 0;
1358 
1359 	/* Give up waiting for processes to exit */
1360 	if (hdev->process_kill_trial_cnt == HL_PENDING_RESET_MAX_TRIALS)
1361 		return -ETIME;
1362 
1363 	hdev->process_kill_trial_cnt++;
1364 
1365 	return -EBUSY;
1366 }
1367 
1368 static void device_disable_open_processes(struct hl_device *hdev, bool control_dev)
1369 {
1370 	struct list_head *fd_list;
1371 	struct hl_fpriv *hpriv;
1372 	struct mutex *fd_lock;
1373 
1374 	fd_lock = control_dev ? &hdev->fpriv_ctrl_list_lock : &hdev->fpriv_list_lock;
1375 	fd_list = control_dev ? &hdev->fpriv_ctrl_list : &hdev->fpriv_list;
1376 
1377 	mutex_lock(fd_lock);
1378 	list_for_each_entry(hpriv, fd_list, dev_node)
1379 		hpriv->hdev = NULL;
1380 	mutex_unlock(fd_lock);
1381 }
1382 
1383 static void handle_reset_trigger(struct hl_device *hdev, u32 flags)
1384 {
1385 	u32 cur_reset_trigger = HL_RESET_TRIGGER_DEFAULT;
1386 
1387 	/* No consecutive mechanism when user context exists */
1388 	if (hdev->is_compute_ctx_active)
1389 		return;
1390 
1391 	/*
1392 	 * 'reset cause' is being updated here, because getting here
1393 	 * means that it's the 1st time and the last time we're here
1394 	 * ('in_reset' makes sure of it). This makes sure that
1395 	 * 'reset_cause' will continue holding its 1st recorded reason!
1396 	 */
1397 	if (flags & HL_DRV_RESET_HEARTBEAT) {
1398 		hdev->reset_info.curr_reset_cause = HL_RESET_CAUSE_HEARTBEAT;
1399 		cur_reset_trigger = HL_DRV_RESET_HEARTBEAT;
1400 	} else if (flags & HL_DRV_RESET_TDR) {
1401 		hdev->reset_info.curr_reset_cause = HL_RESET_CAUSE_TDR;
1402 		cur_reset_trigger = HL_DRV_RESET_TDR;
1403 	} else if (flags & HL_DRV_RESET_FW_FATAL_ERR) {
1404 		hdev->reset_info.curr_reset_cause = HL_RESET_CAUSE_UNKNOWN;
1405 		cur_reset_trigger = HL_DRV_RESET_FW_FATAL_ERR;
1406 	} else {
1407 		hdev->reset_info.curr_reset_cause = HL_RESET_CAUSE_UNKNOWN;
1408 	}
1409 
1410 	/*
1411 	 * If reset cause is same twice, then reset_trigger_repeated
1412 	 * is set and if this reset is due to a fatal FW error
1413 	 * device is set to an unstable state.
1414 	 */
1415 	if (hdev->reset_info.prev_reset_trigger != cur_reset_trigger) {
1416 		hdev->reset_info.prev_reset_trigger = cur_reset_trigger;
1417 		hdev->reset_info.reset_trigger_repeated = 0;
1418 	} else {
1419 		hdev->reset_info.reset_trigger_repeated = 1;
1420 	}
1421 
1422 	/* If reset is due to heartbeat, device CPU is no responsive in
1423 	 * which case no point sending PCI disable message to it.
1424 	 *
1425 	 * If F/W is performing the reset, no need to send it a message to disable
1426 	 * PCI access
1427 	 */
1428 	if ((flags & HL_DRV_RESET_HARD) &&
1429 			!(flags & (HL_DRV_RESET_HEARTBEAT | HL_DRV_RESET_BYPASS_REQ_TO_FW))) {
1430 		/* Disable PCI access from device F/W so he won't send
1431 		 * us additional interrupts. We disable MSI/MSI-X at
1432 		 * the halt_engines function and we can't have the F/W
1433 		 * sending us interrupts after that. We need to disable
1434 		 * the access here because if the device is marked
1435 		 * disable, the message won't be send. Also, in case
1436 		 * of heartbeat, the device CPU is marked as disable
1437 		 * so this message won't be sent
1438 		 */
1439 		if (hl_fw_send_pci_access_msg(hdev, CPUCP_PACKET_DISABLE_PCI_ACCESS, 0x0))
1440 			dev_warn(hdev->dev,
1441 				"Failed to disable FW's PCI access\n");
1442 	}
1443 }
1444 
1445 /*
1446  * hl_device_reset - reset the device
1447  *
1448  * @hdev: pointer to habanalabs device structure
1449  * @flags: reset flags.
1450  *
1451  * Block future CS and wait for pending CS to be enqueued
1452  * Call ASIC H/W fini
1453  * Flush all completions
1454  * Re-initialize all internal data structures
1455  * Call ASIC H/W init, late_init
1456  * Test queues
1457  * Enable device
1458  *
1459  * Returns 0 for success or an error on failure.
1460  */
1461 int hl_device_reset(struct hl_device *hdev, u32 flags)
1462 {
1463 	bool hard_reset, from_hard_reset_thread, fw_reset, reset_upon_device_release,
1464 		schedule_hard_reset = false, delay_reset, from_dev_release, from_watchdog_thread;
1465 	u64 idle_mask[HL_BUSY_ENGINES_MASK_EXT_SIZE] = {0};
1466 	struct hl_ctx *ctx;
1467 	int i, rc, hw_fini_rc;
1468 
1469 	if (!hdev->init_done) {
1470 		dev_err(hdev->dev, "Can't reset before initialization is done\n");
1471 		return 0;
1472 	}
1473 
1474 	hard_reset = !!(flags & HL_DRV_RESET_HARD);
1475 	from_hard_reset_thread = !!(flags & HL_DRV_RESET_FROM_RESET_THR);
1476 	fw_reset = !!(flags & HL_DRV_RESET_BYPASS_REQ_TO_FW);
1477 	from_dev_release = !!(flags & HL_DRV_RESET_DEV_RELEASE);
1478 	delay_reset = !!(flags & HL_DRV_RESET_DELAY);
1479 	from_watchdog_thread = !!(flags & HL_DRV_RESET_FROM_WD_THR);
1480 	reset_upon_device_release = hdev->reset_upon_device_release && from_dev_release;
1481 
1482 	if (!hard_reset && (hl_device_status(hdev) == HL_DEVICE_STATUS_MALFUNCTION)) {
1483 		dev_dbg(hdev->dev, "soft-reset isn't supported on a malfunctioning device\n");
1484 		return 0;
1485 	}
1486 
1487 	if (!hard_reset && !hdev->asic_prop.supports_compute_reset) {
1488 		dev_dbg(hdev->dev, "asic doesn't support compute reset - do hard-reset instead\n");
1489 		hard_reset = true;
1490 	}
1491 
1492 	if (reset_upon_device_release) {
1493 		if (hard_reset) {
1494 			dev_crit(hdev->dev,
1495 				"Aborting reset because hard-reset is mutually exclusive with reset-on-device-release\n");
1496 			return -EINVAL;
1497 		}
1498 
1499 		goto do_reset;
1500 	}
1501 
1502 	if (!hard_reset && !hdev->asic_prop.allow_inference_soft_reset) {
1503 		dev_dbg(hdev->dev,
1504 			"asic doesn't allow inference soft reset - do hard-reset instead\n");
1505 		hard_reset = true;
1506 	}
1507 
1508 do_reset:
1509 	/* Re-entry of reset thread */
1510 	if (from_hard_reset_thread && hdev->process_kill_trial_cnt)
1511 		goto kill_processes;
1512 
1513 	/*
1514 	 * Prevent concurrency in this function - only one reset should be
1515 	 * done at any given time. We need to perform this only if we didn't
1516 	 * get here from a dedicated hard reset thread.
1517 	 */
1518 	if (!from_hard_reset_thread) {
1519 		/* Block future CS/VM/JOB completion operations */
1520 		spin_lock(&hdev->reset_info.lock);
1521 		if (hdev->reset_info.in_reset) {
1522 			/* We allow scheduling of a hard reset only during a compute reset */
1523 			if (hard_reset && hdev->reset_info.in_compute_reset)
1524 				hdev->reset_info.hard_reset_schedule_flags = flags;
1525 			spin_unlock(&hdev->reset_info.lock);
1526 			return 0;
1527 		}
1528 
1529 		/* This still allows the completion of some KDMA ops
1530 		 * Update this before in_reset because in_compute_reset implies we are in reset
1531 		 */
1532 		hdev->reset_info.in_compute_reset = !hard_reset;
1533 
1534 		hdev->reset_info.in_reset = 1;
1535 
1536 		spin_unlock(&hdev->reset_info.lock);
1537 
1538 		/* Cancel the device release watchdog work if required.
1539 		 * In case of reset-upon-device-release while the release watchdog work is
1540 		 * scheduled due to a hard-reset, do hard-reset instead of compute-reset.
1541 		 */
1542 		if ((hard_reset || from_dev_release) && hdev->reset_info.watchdog_active) {
1543 			struct hl_device_reset_work *watchdog_work =
1544 					&hdev->device_release_watchdog_work;
1545 
1546 			hdev->reset_info.watchdog_active = 0;
1547 			if (!from_watchdog_thread)
1548 				cancel_delayed_work_sync(&watchdog_work->reset_work);
1549 
1550 			if (from_dev_release && (watchdog_work->flags & HL_DRV_RESET_HARD)) {
1551 				hdev->reset_info.in_compute_reset = 0;
1552 				flags |= HL_DRV_RESET_HARD;
1553 				flags &= ~HL_DRV_RESET_DEV_RELEASE;
1554 				hard_reset = true;
1555 			}
1556 		}
1557 
1558 		if (delay_reset)
1559 			usleep_range(HL_RESET_DELAY_USEC, HL_RESET_DELAY_USEC << 1);
1560 
1561 escalate_reset_flow:
1562 		handle_reset_trigger(hdev, flags);
1563 
1564 		/* This also blocks future CS/VM/JOB completion operations */
1565 		hdev->disabled = true;
1566 
1567 		take_release_locks(hdev);
1568 
1569 		if (hard_reset)
1570 			dev_info(hdev->dev, "Going to reset device\n");
1571 		else if (reset_upon_device_release)
1572 			dev_dbg(hdev->dev, "Going to reset device after release by user\n");
1573 		else
1574 			dev_dbg(hdev->dev, "Going to reset engines of inference device\n");
1575 	}
1576 
1577 	if ((hard_reset) && (!from_hard_reset_thread)) {
1578 		hdev->reset_info.hard_reset_pending = true;
1579 
1580 		hdev->process_kill_trial_cnt = 0;
1581 
1582 		hdev->device_reset_work.flags = flags;
1583 
1584 		/*
1585 		 * Because the reset function can't run from heartbeat work,
1586 		 * we need to call the reset function from a dedicated work.
1587 		 */
1588 		queue_delayed_work(hdev->reset_wq, &hdev->device_reset_work.reset_work, 0);
1589 
1590 		return 0;
1591 	}
1592 
1593 	cleanup_resources(hdev, hard_reset, fw_reset, from_dev_release);
1594 
1595 kill_processes:
1596 	if (hard_reset) {
1597 		/* Kill processes here after CS rollback. This is because the
1598 		 * process can't really exit until all its CSs are done, which
1599 		 * is what we do in cs rollback
1600 		 */
1601 		rc = device_kill_open_processes(hdev, 0, false);
1602 
1603 		if (rc == -EBUSY) {
1604 			if (hdev->device_fini_pending) {
1605 				dev_crit(hdev->dev,
1606 					"%s Failed to kill all open processes, stopping hard reset\n",
1607 					dev_name(&(hdev)->pdev->dev));
1608 				goto out_err;
1609 			}
1610 
1611 			/* signal reset thread to reschedule */
1612 			return rc;
1613 		}
1614 
1615 		if (rc) {
1616 			dev_crit(hdev->dev,
1617 				"%s Failed to kill all open processes, stopping hard reset\n",
1618 				dev_name(&(hdev)->pdev->dev));
1619 			goto out_err;
1620 		}
1621 
1622 		/* Flush the Event queue workers to make sure no other thread is
1623 		 * reading or writing to registers during the reset
1624 		 */
1625 		flush_workqueue(hdev->eq_wq);
1626 	}
1627 
1628 	/* Reset the H/W. It will be in idle state after this returns */
1629 	hw_fini_rc = hdev->asic_funcs->hw_fini(hdev, hard_reset, fw_reset);
1630 
1631 	if (hard_reset) {
1632 		hdev->fw_loader.fw_comp_loaded = FW_TYPE_NONE;
1633 
1634 		/* Release kernel context */
1635 		if (hdev->kernel_ctx && hl_ctx_put(hdev->kernel_ctx) == 1)
1636 			hdev->kernel_ctx = NULL;
1637 
1638 		hl_vm_fini(hdev);
1639 		hl_mmu_fini(hdev);
1640 		hl_eq_reset(hdev, &hdev->event_queue);
1641 	}
1642 
1643 	/* Re-initialize PI,CI to 0 in all queues (hw queue, cq) */
1644 	hl_hw_queue_reset(hdev, hard_reset);
1645 	for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
1646 		hl_cq_reset(hdev, &hdev->completion_queue[i]);
1647 
1648 	/* Make sure the context switch phase will run again */
1649 	ctx = hl_get_compute_ctx(hdev);
1650 	if (ctx) {
1651 		atomic_set(&ctx->thread_ctx_switch_token, 1);
1652 		ctx->thread_ctx_switch_wait_token = 0;
1653 		hl_ctx_put(ctx);
1654 	}
1655 
1656 	if (hw_fini_rc) {
1657 		rc = hw_fini_rc;
1658 		goto out_err;
1659 	}
1660 	/* Finished tear-down, starting to re-initialize */
1661 
1662 	if (hard_reset) {
1663 		hdev->device_cpu_disabled = false;
1664 		hdev->reset_info.hard_reset_pending = false;
1665 
1666 		if (hdev->reset_info.reset_trigger_repeated &&
1667 				(hdev->reset_info.prev_reset_trigger ==
1668 						HL_DRV_RESET_FW_FATAL_ERR)) {
1669 			/* if there 2 back to back resets from FW,
1670 			 * ensure driver puts the driver in a unusable state
1671 			 */
1672 			dev_crit(hdev->dev,
1673 				"%s Consecutive FW fatal errors received, stopping hard reset\n",
1674 				dev_name(&(hdev)->pdev->dev));
1675 			rc = -EIO;
1676 			goto out_err;
1677 		}
1678 
1679 		if (hdev->kernel_ctx) {
1680 			dev_crit(hdev->dev,
1681 				"%s kernel ctx was alive during hard reset, something is terribly wrong\n",
1682 				dev_name(&(hdev)->pdev->dev));
1683 			rc = -EBUSY;
1684 			goto out_err;
1685 		}
1686 
1687 		rc = hl_mmu_init(hdev);
1688 		if (rc) {
1689 			dev_err(hdev->dev,
1690 				"Failed to initialize MMU S/W after hard reset\n");
1691 			goto out_err;
1692 		}
1693 
1694 		/* Allocate the kernel context */
1695 		hdev->kernel_ctx = kzalloc(sizeof(*hdev->kernel_ctx),
1696 						GFP_KERNEL);
1697 		if (!hdev->kernel_ctx) {
1698 			rc = -ENOMEM;
1699 			hl_mmu_fini(hdev);
1700 			goto out_err;
1701 		}
1702 
1703 		hdev->is_compute_ctx_active = false;
1704 
1705 		rc = hl_ctx_init(hdev, hdev->kernel_ctx, true);
1706 		if (rc) {
1707 			dev_err(hdev->dev,
1708 				"failed to init kernel ctx in hard reset\n");
1709 			kfree(hdev->kernel_ctx);
1710 			hdev->kernel_ctx = NULL;
1711 			hl_mmu_fini(hdev);
1712 			goto out_err;
1713 		}
1714 	}
1715 
1716 	/* Device is now enabled as part of the initialization requires
1717 	 * communication with the device firmware to get information that
1718 	 * is required for the initialization itself
1719 	 */
1720 	hdev->disabled = false;
1721 
1722 	/* F/W security enabled indication might be updated after hard-reset */
1723 	if (hard_reset) {
1724 		rc = hl_fw_read_preboot_status(hdev);
1725 		if (rc)
1726 			goto out_err;
1727 	}
1728 
1729 	rc = hdev->asic_funcs->hw_init(hdev);
1730 	if (rc) {
1731 		dev_err(hdev->dev, "failed to initialize the H/W after reset\n");
1732 		goto out_err;
1733 	}
1734 
1735 	/* If device is not idle fail the reset process */
1736 	if (!hdev->asic_funcs->is_device_idle(hdev, idle_mask,
1737 						HL_BUSY_ENGINES_MASK_EXT_SIZE, NULL)) {
1738 		print_idle_status_mask(hdev, "device is not idle after reset", idle_mask);
1739 		rc = -EIO;
1740 		goto out_err;
1741 	}
1742 
1743 	/* Check that the communication with the device is working */
1744 	rc = hdev->asic_funcs->test_queues(hdev);
1745 	if (rc) {
1746 		dev_err(hdev->dev, "Failed to detect if device is alive after reset\n");
1747 		goto out_err;
1748 	}
1749 
1750 	if (hard_reset) {
1751 		rc = device_late_init(hdev);
1752 		if (rc) {
1753 			dev_err(hdev->dev, "Failed late init after hard reset\n");
1754 			goto out_err;
1755 		}
1756 
1757 		rc = hl_vm_init(hdev);
1758 		if (rc) {
1759 			dev_err(hdev->dev, "Failed to init memory module after hard reset\n");
1760 			goto out_err;
1761 		}
1762 
1763 		if (!hdev->asic_prop.fw_security_enabled)
1764 			hl_fw_set_max_power(hdev);
1765 	} else {
1766 		rc = hdev->asic_funcs->compute_reset_late_init(hdev);
1767 		if (rc) {
1768 			if (reset_upon_device_release)
1769 				dev_err(hdev->dev,
1770 					"Failed late init in reset after device release\n");
1771 			else
1772 				dev_err(hdev->dev, "Failed late init after compute reset\n");
1773 			goto out_err;
1774 		}
1775 	}
1776 
1777 	rc = hdev->asic_funcs->scrub_device_mem(hdev);
1778 	if (rc) {
1779 		dev_err(hdev->dev, "scrub mem failed from device reset (%d)\n", rc);
1780 		goto out_err;
1781 	}
1782 
1783 	spin_lock(&hdev->reset_info.lock);
1784 	hdev->reset_info.in_compute_reset = 0;
1785 
1786 	/* Schedule hard reset only if requested and if not already in hard reset.
1787 	 * We keep 'in_reset' enabled, so no other reset can go in during the hard
1788 	 * reset schedule
1789 	 */
1790 	if (!hard_reset && hdev->reset_info.hard_reset_schedule_flags)
1791 		schedule_hard_reset = true;
1792 	else
1793 		hdev->reset_info.in_reset = 0;
1794 
1795 	spin_unlock(&hdev->reset_info.lock);
1796 
1797 	hdev->reset_info.needs_reset = false;
1798 
1799 	if (hard_reset)
1800 		dev_info(hdev->dev,
1801 			 "Successfully finished resetting the %s device\n",
1802 			 dev_name(&(hdev)->pdev->dev));
1803 	else
1804 		dev_dbg(hdev->dev,
1805 			"Successfully finished resetting the %s device\n",
1806 			dev_name(&(hdev)->pdev->dev));
1807 
1808 	if (hard_reset) {
1809 		hdev->reset_info.hard_reset_cnt++;
1810 
1811 		/* After reset is done, we are ready to receive events from
1812 		 * the F/W. We can't do it before because we will ignore events
1813 		 * and if those events are fatal, we won't know about it and
1814 		 * the device will be operational although it shouldn't be
1815 		 */
1816 		hdev->asic_funcs->enable_events_from_fw(hdev);
1817 	} else {
1818 		if (!reset_upon_device_release)
1819 			hdev->reset_info.compute_reset_cnt++;
1820 
1821 		if (schedule_hard_reset) {
1822 			dev_info(hdev->dev, "Performing hard reset scheduled during compute reset\n");
1823 			flags = hdev->reset_info.hard_reset_schedule_flags;
1824 			hdev->reset_info.hard_reset_schedule_flags = 0;
1825 			hdev->disabled = true;
1826 			hard_reset = true;
1827 			handle_reset_trigger(hdev, flags);
1828 			goto escalate_reset_flow;
1829 		}
1830 	}
1831 
1832 	return 0;
1833 
1834 out_err:
1835 	hdev->disabled = true;
1836 
1837 	spin_lock(&hdev->reset_info.lock);
1838 	hdev->reset_info.in_compute_reset = 0;
1839 
1840 	if (hard_reset) {
1841 		dev_err(hdev->dev,
1842 			"%s Failed to reset! Device is NOT usable\n",
1843 			dev_name(&(hdev)->pdev->dev));
1844 		hdev->reset_info.hard_reset_cnt++;
1845 	} else {
1846 		if (reset_upon_device_release) {
1847 			dev_err(hdev->dev, "Failed to reset device after user release\n");
1848 			flags &= ~HL_DRV_RESET_DEV_RELEASE;
1849 		} else {
1850 			dev_err(hdev->dev, "Failed to do compute reset\n");
1851 			hdev->reset_info.compute_reset_cnt++;
1852 		}
1853 
1854 		spin_unlock(&hdev->reset_info.lock);
1855 		flags |= HL_DRV_RESET_HARD;
1856 		hard_reset = true;
1857 		goto escalate_reset_flow;
1858 	}
1859 
1860 	hdev->reset_info.in_reset = 0;
1861 
1862 	spin_unlock(&hdev->reset_info.lock);
1863 
1864 	return rc;
1865 }
1866 
1867 /*
1868  * hl_device_cond_reset() - conditionally reset the device.
1869  * @hdev: pointer to habanalabs device structure.
1870  * @reset_flags: reset flags.
1871  * @event_mask: events to notify user about.
1872  *
1873  * Conditionally reset the device, or alternatively schedule a watchdog work to reset the device
1874  * unless another reset precedes it.
1875  */
1876 int hl_device_cond_reset(struct hl_device *hdev, u32 flags, u64 event_mask)
1877 {
1878 	struct hl_ctx *ctx = NULL;
1879 
1880 	/* F/W reset cannot be postponed */
1881 	if (flags & HL_DRV_RESET_BYPASS_REQ_TO_FW)
1882 		goto device_reset;
1883 
1884 	/* Device release watchdog is relevant only if user exists and gets a reset notification */
1885 	if (!(event_mask & HL_NOTIFIER_EVENT_DEVICE_RESET)) {
1886 		dev_err(hdev->dev, "Resetting device without a reset indication to user\n");
1887 		goto device_reset;
1888 	}
1889 
1890 	ctx = hl_get_compute_ctx(hdev);
1891 	if (!ctx || !ctx->hpriv->notifier_event.eventfd)
1892 		goto device_reset;
1893 
1894 	/* Schedule the device release watchdog work unless reset is already in progress or if the
1895 	 * work is already scheduled.
1896 	 */
1897 	spin_lock(&hdev->reset_info.lock);
1898 	if (hdev->reset_info.in_reset) {
1899 		spin_unlock(&hdev->reset_info.lock);
1900 		goto device_reset;
1901 	}
1902 
1903 	if (hdev->reset_info.watchdog_active)
1904 		goto out;
1905 
1906 	hdev->device_release_watchdog_work.flags = flags;
1907 	dev_dbg(hdev->dev, "Device is going to be hard-reset in %u sec unless being released\n",
1908 		hdev->device_release_watchdog_timeout_sec);
1909 	schedule_delayed_work(&hdev->device_release_watchdog_work.reset_work,
1910 				msecs_to_jiffies(hdev->device_release_watchdog_timeout_sec * 1000));
1911 	hdev->reset_info.watchdog_active = 1;
1912 out:
1913 	spin_unlock(&hdev->reset_info.lock);
1914 
1915 	hl_notifier_event_send_all(hdev, event_mask);
1916 
1917 	hl_ctx_put(ctx);
1918 
1919 	hl_abort_waitings_for_completion(hdev);
1920 
1921 	return 0;
1922 
1923 device_reset:
1924 	if (event_mask)
1925 		hl_notifier_event_send_all(hdev, event_mask);
1926 	if (ctx)
1927 		hl_ctx_put(ctx);
1928 
1929 	return hl_device_reset(hdev, flags);
1930 }
1931 
1932 static void hl_notifier_event_send(struct hl_notifier_event *notifier_event, u64 event_mask)
1933 {
1934 	mutex_lock(&notifier_event->lock);
1935 	notifier_event->events_mask |= event_mask;
1936 
1937 	if (notifier_event->eventfd)
1938 		eventfd_signal(notifier_event->eventfd, 1);
1939 
1940 	mutex_unlock(&notifier_event->lock);
1941 }
1942 
1943 /*
1944  * hl_notifier_event_send_all - notify all user processes via eventfd
1945  *
1946  * @hdev: pointer to habanalabs device structure
1947  * @event_mask: the occurred event/s
1948  * Returns 0 for success or an error on failure.
1949  */
1950 void hl_notifier_event_send_all(struct hl_device *hdev, u64 event_mask)
1951 {
1952 	struct hl_fpriv	*hpriv;
1953 
1954 	if (!event_mask) {
1955 		dev_warn(hdev->dev, "Skip sending zero event");
1956 		return;
1957 	}
1958 
1959 	mutex_lock(&hdev->fpriv_list_lock);
1960 
1961 	list_for_each_entry(hpriv, &hdev->fpriv_list, dev_node)
1962 		hl_notifier_event_send(&hpriv->notifier_event, event_mask);
1963 
1964 	mutex_unlock(&hdev->fpriv_list_lock);
1965 
1966 	/* control device */
1967 	mutex_lock(&hdev->fpriv_ctrl_list_lock);
1968 
1969 	list_for_each_entry(hpriv, &hdev->fpriv_ctrl_list, dev_node)
1970 		hl_notifier_event_send(&hpriv->notifier_event, event_mask);
1971 
1972 	mutex_unlock(&hdev->fpriv_ctrl_list_lock);
1973 }
1974 
1975 static int create_cdev(struct hl_device *hdev)
1976 {
1977 	char *name;
1978 	int rc;
1979 
1980 	hdev->cdev_idx = hdev->id / 2;
1981 
1982 	name = kasprintf(GFP_KERNEL, "hl%d", hdev->cdev_idx);
1983 	if (!name) {
1984 		rc = -ENOMEM;
1985 		goto out_err;
1986 	}
1987 
1988 	/* Initialize cdev and device structures */
1989 	rc = device_init_cdev(hdev, hdev->hclass, hdev->id, &hl_ops, name,
1990 				&hdev->cdev, &hdev->dev);
1991 
1992 	kfree(name);
1993 
1994 	if (rc)
1995 		goto out_err;
1996 
1997 	name = kasprintf(GFP_KERNEL, "hl_controlD%d", hdev->cdev_idx);
1998 	if (!name) {
1999 		rc = -ENOMEM;
2000 		goto free_dev;
2001 	}
2002 
2003 	/* Initialize cdev and device structures for control device */
2004 	rc = device_init_cdev(hdev, hdev->hclass, hdev->id_control, &hl_ctrl_ops,
2005 				name, &hdev->cdev_ctrl, &hdev->dev_ctrl);
2006 
2007 	kfree(name);
2008 
2009 	if (rc)
2010 		goto free_dev;
2011 
2012 	return 0;
2013 
2014 free_dev:
2015 	put_device(hdev->dev);
2016 out_err:
2017 	return rc;
2018 }
2019 
2020 /*
2021  * hl_device_init - main initialization function for habanalabs device
2022  *
2023  * @hdev: pointer to habanalabs device structure
2024  *
2025  * Allocate an id for the device, do early initialization and then call the
2026  * ASIC specific initialization functions. Finally, create the cdev and the
2027  * Linux device to expose it to the user
2028  */
2029 int hl_device_init(struct hl_device *hdev)
2030 {
2031 	int i, rc, cq_cnt, user_interrupt_cnt, cq_ready_cnt;
2032 	bool add_cdev_sysfs_on_err = false;
2033 
2034 	rc = create_cdev(hdev);
2035 	if (rc)
2036 		goto out_disabled;
2037 
2038 	/* Initialize ASIC function pointers and perform early init */
2039 	rc = device_early_init(hdev);
2040 	if (rc)
2041 		goto free_dev;
2042 
2043 	user_interrupt_cnt = hdev->asic_prop.user_dec_intr_count +
2044 				hdev->asic_prop.user_interrupt_count;
2045 
2046 	if (user_interrupt_cnt) {
2047 		hdev->user_interrupt = kcalloc(user_interrupt_cnt, sizeof(*hdev->user_interrupt),
2048 						GFP_KERNEL);
2049 		if (!hdev->user_interrupt) {
2050 			rc = -ENOMEM;
2051 			goto early_fini;
2052 		}
2053 	}
2054 
2055 	/*
2056 	 * Start calling ASIC initialization. First S/W then H/W and finally
2057 	 * late init
2058 	 */
2059 	rc = hdev->asic_funcs->sw_init(hdev);
2060 	if (rc)
2061 		goto free_usr_intr_mem;
2062 
2063 
2064 	/* initialize completion structure for multi CS wait */
2065 	hl_multi_cs_completion_init(hdev);
2066 
2067 	/*
2068 	 * Initialize the H/W queues. Must be done before hw_init, because
2069 	 * there the addresses of the kernel queue are being written to the
2070 	 * registers of the device
2071 	 */
2072 	rc = hl_hw_queues_create(hdev);
2073 	if (rc) {
2074 		dev_err(hdev->dev, "failed to initialize kernel queues\n");
2075 		goto sw_fini;
2076 	}
2077 
2078 	cq_cnt = hdev->asic_prop.completion_queues_count;
2079 
2080 	/*
2081 	 * Initialize the completion queues. Must be done before hw_init,
2082 	 * because there the addresses of the completion queues are being
2083 	 * passed as arguments to request_irq
2084 	 */
2085 	if (cq_cnt) {
2086 		hdev->completion_queue = kcalloc(cq_cnt,
2087 				sizeof(*hdev->completion_queue),
2088 				GFP_KERNEL);
2089 
2090 		if (!hdev->completion_queue) {
2091 			dev_err(hdev->dev,
2092 				"failed to allocate completion queues\n");
2093 			rc = -ENOMEM;
2094 			goto hw_queues_destroy;
2095 		}
2096 	}
2097 
2098 	for (i = 0, cq_ready_cnt = 0 ; i < cq_cnt ; i++, cq_ready_cnt++) {
2099 		rc = hl_cq_init(hdev, &hdev->completion_queue[i],
2100 				hdev->asic_funcs->get_queue_id_for_cq(hdev, i));
2101 		if (rc) {
2102 			dev_err(hdev->dev,
2103 				"failed to initialize completion queue\n");
2104 			goto cq_fini;
2105 		}
2106 		hdev->completion_queue[i].cq_idx = i;
2107 	}
2108 
2109 	hdev->shadow_cs_queue = kcalloc(hdev->asic_prop.max_pending_cs,
2110 					sizeof(struct hl_cs *), GFP_KERNEL);
2111 	if (!hdev->shadow_cs_queue) {
2112 		rc = -ENOMEM;
2113 		goto cq_fini;
2114 	}
2115 
2116 	/*
2117 	 * Initialize the event queue. Must be done before hw_init,
2118 	 * because there the address of the event queue is being
2119 	 * passed as argument to request_irq
2120 	 */
2121 	rc = hl_eq_init(hdev, &hdev->event_queue);
2122 	if (rc) {
2123 		dev_err(hdev->dev, "failed to initialize event queue\n");
2124 		goto free_shadow_cs_queue;
2125 	}
2126 
2127 	/* MMU S/W must be initialized before kernel context is created */
2128 	rc = hl_mmu_init(hdev);
2129 	if (rc) {
2130 		dev_err(hdev->dev, "Failed to initialize MMU S/W structures\n");
2131 		goto eq_fini;
2132 	}
2133 
2134 	/* Allocate the kernel context */
2135 	hdev->kernel_ctx = kzalloc(sizeof(*hdev->kernel_ctx), GFP_KERNEL);
2136 	if (!hdev->kernel_ctx) {
2137 		rc = -ENOMEM;
2138 		goto mmu_fini;
2139 	}
2140 
2141 	hdev->is_compute_ctx_active = false;
2142 
2143 	hdev->asic_funcs->state_dump_init(hdev);
2144 
2145 	hdev->device_release_watchdog_timeout_sec = HL_DEVICE_RELEASE_WATCHDOG_TIMEOUT_SEC;
2146 
2147 	hdev->memory_scrub_val = MEM_SCRUB_DEFAULT_VAL;
2148 	hl_debugfs_add_device(hdev);
2149 
2150 	/* debugfs nodes are created in hl_ctx_init so it must be called after
2151 	 * hl_debugfs_add_device.
2152 	 */
2153 	rc = hl_ctx_init(hdev, hdev->kernel_ctx, true);
2154 	if (rc) {
2155 		dev_err(hdev->dev, "failed to initialize kernel context\n");
2156 		kfree(hdev->kernel_ctx);
2157 		goto remove_device_from_debugfs;
2158 	}
2159 
2160 	rc = hl_cb_pool_init(hdev);
2161 	if (rc) {
2162 		dev_err(hdev->dev, "failed to initialize CB pool\n");
2163 		goto release_ctx;
2164 	}
2165 
2166 	rc = hl_dec_init(hdev);
2167 	if (rc) {
2168 		dev_err(hdev->dev, "Failed to initialize the decoder module\n");
2169 		goto cb_pool_fini;
2170 	}
2171 
2172 	/*
2173 	 * From this point, override rc (=0) in case of an error to allow
2174 	 * debugging (by adding char devices and create sysfs nodes as part of
2175 	 * the error flow).
2176 	 */
2177 	add_cdev_sysfs_on_err = true;
2178 
2179 	/* Device is now enabled as part of the initialization requires
2180 	 * communication with the device firmware to get information that
2181 	 * is required for the initialization itself
2182 	 */
2183 	hdev->disabled = false;
2184 
2185 	rc = hdev->asic_funcs->hw_init(hdev);
2186 	if (rc) {
2187 		dev_err(hdev->dev, "failed to initialize the H/W\n");
2188 		rc = 0;
2189 		goto out_disabled;
2190 	}
2191 
2192 	/* Check that the communication with the device is working */
2193 	rc = hdev->asic_funcs->test_queues(hdev);
2194 	if (rc) {
2195 		dev_err(hdev->dev, "Failed to detect if device is alive\n");
2196 		rc = 0;
2197 		goto out_disabled;
2198 	}
2199 
2200 	rc = device_late_init(hdev);
2201 	if (rc) {
2202 		dev_err(hdev->dev, "Failed late initialization\n");
2203 		rc = 0;
2204 		goto out_disabled;
2205 	}
2206 
2207 	dev_info(hdev->dev, "Found %s device with %lluGB DRAM\n",
2208 		hdev->asic_name,
2209 		hdev->asic_prop.dram_size / SZ_1G);
2210 
2211 	rc = hl_vm_init(hdev);
2212 	if (rc) {
2213 		dev_err(hdev->dev, "Failed to initialize memory module\n");
2214 		rc = 0;
2215 		goto out_disabled;
2216 	}
2217 
2218 	/*
2219 	 * Expose devices and sysfs nodes to user.
2220 	 * From here there is no need to add char devices and create sysfs nodes
2221 	 * in case of an error.
2222 	 */
2223 	add_cdev_sysfs_on_err = false;
2224 	rc = device_cdev_sysfs_add(hdev);
2225 	if (rc) {
2226 		dev_err(hdev->dev,
2227 			"Failed to add char devices and sysfs nodes\n");
2228 		rc = 0;
2229 		goto out_disabled;
2230 	}
2231 
2232 	/* Need to call this again because the max power might change,
2233 	 * depending on card type for certain ASICs
2234 	 */
2235 	if (hdev->asic_prop.set_max_power_on_device_init &&
2236 			!hdev->asic_prop.fw_security_enabled)
2237 		hl_fw_set_max_power(hdev);
2238 
2239 	/*
2240 	 * hl_hwmon_init() must be called after device_late_init(), because only
2241 	 * there we get the information from the device about which
2242 	 * hwmon-related sensors the device supports.
2243 	 * Furthermore, it must be done after adding the device to the system.
2244 	 */
2245 	rc = hl_hwmon_init(hdev);
2246 	if (rc) {
2247 		dev_err(hdev->dev, "Failed to initialize hwmon\n");
2248 		rc = 0;
2249 		goto out_disabled;
2250 	}
2251 
2252 	dev_notice(hdev->dev,
2253 		"Successfully added device %s to habanalabs driver\n",
2254 		dev_name(&(hdev)->pdev->dev));
2255 
2256 	hdev->init_done = true;
2257 
2258 	/* After initialization is done, we are ready to receive events from
2259 	 * the F/W. We can't do it before because we will ignore events and if
2260 	 * those events are fatal, we won't know about it and the device will
2261 	 * be operational although it shouldn't be
2262 	 */
2263 	hdev->asic_funcs->enable_events_from_fw(hdev);
2264 
2265 	return 0;
2266 
2267 cb_pool_fini:
2268 	hl_cb_pool_fini(hdev);
2269 release_ctx:
2270 	if (hl_ctx_put(hdev->kernel_ctx) != 1)
2271 		dev_err(hdev->dev,
2272 			"kernel ctx is still alive on initialization failure\n");
2273 remove_device_from_debugfs:
2274 	hl_debugfs_remove_device(hdev);
2275 mmu_fini:
2276 	hl_mmu_fini(hdev);
2277 eq_fini:
2278 	hl_eq_fini(hdev, &hdev->event_queue);
2279 free_shadow_cs_queue:
2280 	kfree(hdev->shadow_cs_queue);
2281 cq_fini:
2282 	for (i = 0 ; i < cq_ready_cnt ; i++)
2283 		hl_cq_fini(hdev, &hdev->completion_queue[i]);
2284 	kfree(hdev->completion_queue);
2285 hw_queues_destroy:
2286 	hl_hw_queues_destroy(hdev);
2287 sw_fini:
2288 	hdev->asic_funcs->sw_fini(hdev);
2289 free_usr_intr_mem:
2290 	kfree(hdev->user_interrupt);
2291 early_fini:
2292 	device_early_fini(hdev);
2293 free_dev:
2294 	put_device(hdev->dev_ctrl);
2295 	put_device(hdev->dev);
2296 out_disabled:
2297 	hdev->disabled = true;
2298 	if (add_cdev_sysfs_on_err)
2299 		device_cdev_sysfs_add(hdev);
2300 	if (hdev->pdev)
2301 		dev_err(&hdev->pdev->dev,
2302 			"Failed to initialize hl%d. Device %s is NOT usable !\n",
2303 			hdev->cdev_idx, dev_name(&(hdev)->pdev->dev));
2304 	else
2305 		pr_err("Failed to initialize hl%d. Device %s is NOT usable !\n",
2306 			hdev->cdev_idx, dev_name(&(hdev)->pdev->dev));
2307 
2308 	return rc;
2309 }
2310 
2311 /*
2312  * hl_device_fini - main tear-down function for habanalabs device
2313  *
2314  * @hdev: pointer to habanalabs device structure
2315  *
2316  * Destroy the device, call ASIC fini functions and release the id
2317  */
2318 void hl_device_fini(struct hl_device *hdev)
2319 {
2320 	bool device_in_reset;
2321 	ktime_t timeout;
2322 	u64 reset_sec;
2323 	int i, rc;
2324 
2325 	dev_info(hdev->dev, "Removing device\n");
2326 
2327 	hdev->device_fini_pending = 1;
2328 	flush_delayed_work(&hdev->device_reset_work.reset_work);
2329 
2330 	if (hdev->pldm)
2331 		reset_sec = HL_PLDM_HARD_RESET_MAX_TIMEOUT;
2332 	else
2333 		reset_sec = HL_HARD_RESET_MAX_TIMEOUT;
2334 
2335 	/*
2336 	 * This function is competing with the reset function, so try to
2337 	 * take the reset atomic and if we are already in middle of reset,
2338 	 * wait until reset function is finished. Reset function is designed
2339 	 * to always finish. However, in Gaudi, because of all the network
2340 	 * ports, the hard reset could take between 10-30 seconds
2341 	 */
2342 
2343 	timeout = ktime_add_us(ktime_get(), reset_sec * 1000 * 1000);
2344 
2345 	spin_lock(&hdev->reset_info.lock);
2346 	device_in_reset = !!hdev->reset_info.in_reset;
2347 	if (!device_in_reset)
2348 		hdev->reset_info.in_reset = 1;
2349 	spin_unlock(&hdev->reset_info.lock);
2350 
2351 	while (device_in_reset) {
2352 		usleep_range(50, 200);
2353 
2354 		spin_lock(&hdev->reset_info.lock);
2355 		device_in_reset = !!hdev->reset_info.in_reset;
2356 		if (!device_in_reset)
2357 			hdev->reset_info.in_reset = 1;
2358 		spin_unlock(&hdev->reset_info.lock);
2359 
2360 		if (ktime_compare(ktime_get(), timeout) > 0) {
2361 			dev_crit(hdev->dev,
2362 				"%s Failed to remove device because reset function did not finish\n",
2363 				dev_name(&(hdev)->pdev->dev));
2364 			return;
2365 		}
2366 	}
2367 
2368 	cancel_delayed_work_sync(&hdev->device_release_watchdog_work.reset_work);
2369 
2370 	/* Disable PCI access from device F/W so it won't send us additional
2371 	 * interrupts. We disable MSI/MSI-X at the halt_engines function and we
2372 	 * can't have the F/W sending us interrupts after that. We need to
2373 	 * disable the access here because if the device is marked disable, the
2374 	 * message won't be send. Also, in case of heartbeat, the device CPU is
2375 	 * marked as disable so this message won't be sent
2376 	 */
2377 	hl_fw_send_pci_access_msg(hdev,	CPUCP_PACKET_DISABLE_PCI_ACCESS, 0x0);
2378 
2379 	/* Mark device as disabled */
2380 	hdev->disabled = true;
2381 
2382 	take_release_locks(hdev);
2383 
2384 	hdev->reset_info.hard_reset_pending = true;
2385 
2386 	hl_hwmon_fini(hdev);
2387 
2388 	cleanup_resources(hdev, true, false, false);
2389 
2390 	/* Kill processes here after CS rollback. This is because the process
2391 	 * can't really exit until all its CSs are done, which is what we
2392 	 * do in cs rollback
2393 	 */
2394 	dev_info(hdev->dev,
2395 		"Waiting for all processes to exit (timeout of %u seconds)",
2396 		HL_WAIT_PROCESS_KILL_ON_DEVICE_FINI);
2397 
2398 	hdev->process_kill_trial_cnt = 0;
2399 	rc = device_kill_open_processes(hdev, HL_WAIT_PROCESS_KILL_ON_DEVICE_FINI, false);
2400 	if (rc) {
2401 		dev_crit(hdev->dev, "Failed to kill all open processes\n");
2402 		device_disable_open_processes(hdev, false);
2403 	}
2404 
2405 	hdev->process_kill_trial_cnt = 0;
2406 	rc = device_kill_open_processes(hdev, 0, true);
2407 	if (rc) {
2408 		dev_crit(hdev->dev, "Failed to kill all control device open processes\n");
2409 		device_disable_open_processes(hdev, true);
2410 	}
2411 
2412 	hl_cb_pool_fini(hdev);
2413 
2414 	/* Reset the H/W. It will be in idle state after this returns */
2415 	rc = hdev->asic_funcs->hw_fini(hdev, true, false);
2416 	if (rc)
2417 		dev_err(hdev->dev, "hw_fini failed in device fini while removing device %d\n", rc);
2418 
2419 	hdev->fw_loader.fw_comp_loaded = FW_TYPE_NONE;
2420 
2421 	/* Release kernel context */
2422 	if ((hdev->kernel_ctx) && (hl_ctx_put(hdev->kernel_ctx) != 1))
2423 		dev_err(hdev->dev, "kernel ctx is still alive\n");
2424 
2425 	hl_debugfs_remove_device(hdev);
2426 
2427 	hl_dec_fini(hdev);
2428 
2429 	hl_vm_fini(hdev);
2430 
2431 	hl_mmu_fini(hdev);
2432 
2433 	vfree(hdev->captured_err_info.page_fault_info.user_mappings);
2434 
2435 	hl_eq_fini(hdev, &hdev->event_queue);
2436 
2437 	kfree(hdev->shadow_cs_queue);
2438 
2439 	for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
2440 		hl_cq_fini(hdev, &hdev->completion_queue[i]);
2441 	kfree(hdev->completion_queue);
2442 	kfree(hdev->user_interrupt);
2443 
2444 	hl_hw_queues_destroy(hdev);
2445 
2446 	/* Call ASIC S/W finalize function */
2447 	hdev->asic_funcs->sw_fini(hdev);
2448 
2449 	device_early_fini(hdev);
2450 
2451 	/* Hide devices and sysfs nodes from user */
2452 	device_cdev_sysfs_del(hdev);
2453 
2454 	pr_info("removed device successfully\n");
2455 }
2456 
2457 /*
2458  * MMIO register access helper functions.
2459  */
2460 
2461 /*
2462  * hl_rreg - Read an MMIO register
2463  *
2464  * @hdev: pointer to habanalabs device structure
2465  * @reg: MMIO register offset (in bytes)
2466  *
2467  * Returns the value of the MMIO register we are asked to read
2468  *
2469  */
2470 inline u32 hl_rreg(struct hl_device *hdev, u32 reg)
2471 {
2472 	u32 val = readl(hdev->rmmio + reg);
2473 
2474 	if (unlikely(trace_habanalabs_rreg32_enabled()))
2475 		trace_habanalabs_rreg32(hdev->dev, reg, val);
2476 
2477 	return val;
2478 }
2479 
2480 /*
2481  * hl_wreg - Write to an MMIO register
2482  *
2483  * @hdev: pointer to habanalabs device structure
2484  * @reg: MMIO register offset (in bytes)
2485  * @val: 32-bit value
2486  *
2487  * Writes the 32-bit value into the MMIO register
2488  *
2489  */
2490 inline void hl_wreg(struct hl_device *hdev, u32 reg, u32 val)
2491 {
2492 	if (unlikely(trace_habanalabs_wreg32_enabled()))
2493 		trace_habanalabs_wreg32(hdev->dev, reg, val);
2494 
2495 	writel(val, hdev->rmmio + reg);
2496 }
2497 
2498 void hl_capture_razwi(struct hl_device *hdev, u64 addr, u16 *engine_id, u16 num_of_engines,
2499 			u8 flags)
2500 {
2501 	struct razwi_info *razwi_info = &hdev->captured_err_info.razwi_info;
2502 
2503 	if (num_of_engines > HL_RAZWI_MAX_NUM_OF_ENGINES_PER_RTR) {
2504 		dev_err(hdev->dev,
2505 				"Number of possible razwi initiators (%u) exceeded limit (%u)\n",
2506 				num_of_engines, HL_RAZWI_MAX_NUM_OF_ENGINES_PER_RTR);
2507 		return;
2508 	}
2509 
2510 	/* In case it's the first razwi since the device was opened, capture its parameters */
2511 	if (atomic_cmpxchg(&hdev->captured_err_info.razwi_info.razwi_detected, 0, 1))
2512 		return;
2513 
2514 	razwi_info->razwi.timestamp = ktime_to_ns(ktime_get());
2515 	razwi_info->razwi.addr = addr;
2516 	razwi_info->razwi.num_of_possible_engines = num_of_engines;
2517 	memcpy(&razwi_info->razwi.engine_id[0], &engine_id[0],
2518 			num_of_engines * sizeof(u16));
2519 	razwi_info->razwi.flags = flags;
2520 
2521 	razwi_info->razwi_info_available = true;
2522 }
2523 
2524 void hl_handle_razwi(struct hl_device *hdev, u64 addr, u16 *engine_id, u16 num_of_engines,
2525 			u8 flags, u64 *event_mask)
2526 {
2527 	hl_capture_razwi(hdev, addr, engine_id, num_of_engines, flags);
2528 
2529 	if (event_mask)
2530 		*event_mask |= HL_NOTIFIER_EVENT_RAZWI;
2531 }
2532 
2533 static void hl_capture_user_mappings(struct hl_device *hdev, bool is_pmmu)
2534 {
2535 	struct page_fault_info *pgf_info = &hdev->captured_err_info.page_fault_info;
2536 	struct hl_vm_phys_pg_pack *phys_pg_pack = NULL;
2537 	struct hl_vm_hash_node *hnode;
2538 	struct hl_userptr *userptr;
2539 	enum vm_type *vm_type;
2540 	struct hl_ctx *ctx;
2541 	u32 map_idx = 0;
2542 	int i;
2543 
2544 	/* Reset previous session count*/
2545 	pgf_info->num_of_user_mappings = 0;
2546 
2547 	ctx = hl_get_compute_ctx(hdev);
2548 	if (!ctx) {
2549 		dev_err(hdev->dev, "Can't get user context for user mappings\n");
2550 		return;
2551 	}
2552 
2553 	mutex_lock(&ctx->mem_hash_lock);
2554 	hash_for_each(ctx->mem_hash, i, hnode, node) {
2555 		vm_type = hnode->ptr;
2556 		if (((*vm_type == VM_TYPE_USERPTR) && is_pmmu) ||
2557 				((*vm_type == VM_TYPE_PHYS_PACK) && !is_pmmu))
2558 			pgf_info->num_of_user_mappings++;
2559 
2560 	}
2561 
2562 	if (!pgf_info->num_of_user_mappings)
2563 		goto finish;
2564 
2565 	/* In case we already allocated in previous session, need to release it before
2566 	 * allocating new buffer.
2567 	 */
2568 	vfree(pgf_info->user_mappings);
2569 	pgf_info->user_mappings =
2570 			vzalloc(pgf_info->num_of_user_mappings * sizeof(struct hl_user_mapping));
2571 	if (!pgf_info->user_mappings) {
2572 		pgf_info->num_of_user_mappings = 0;
2573 		goto finish;
2574 	}
2575 
2576 	hash_for_each(ctx->mem_hash, i, hnode, node) {
2577 		vm_type = hnode->ptr;
2578 		if ((*vm_type == VM_TYPE_USERPTR) && (is_pmmu)) {
2579 			userptr = hnode->ptr;
2580 			pgf_info->user_mappings[map_idx].dev_va = hnode->vaddr;
2581 			pgf_info->user_mappings[map_idx].size = userptr->size;
2582 			map_idx++;
2583 		} else if ((*vm_type == VM_TYPE_PHYS_PACK) && (!is_pmmu)) {
2584 			phys_pg_pack = hnode->ptr;
2585 			pgf_info->user_mappings[map_idx].dev_va = hnode->vaddr;
2586 			pgf_info->user_mappings[map_idx].size = phys_pg_pack->total_size;
2587 			map_idx++;
2588 		}
2589 	}
2590 finish:
2591 	mutex_unlock(&ctx->mem_hash_lock);
2592 	hl_ctx_put(ctx);
2593 }
2594 
2595 void hl_capture_page_fault(struct hl_device *hdev, u64 addr, u16 eng_id, bool is_pmmu)
2596 {
2597 	struct page_fault_info *pgf_info = &hdev->captured_err_info.page_fault_info;
2598 
2599 	/* Capture only the first page fault */
2600 	if (atomic_cmpxchg(&pgf_info->page_fault_detected, 0, 1))
2601 		return;
2602 
2603 	pgf_info->page_fault.timestamp = ktime_to_ns(ktime_get());
2604 	pgf_info->page_fault.addr = addr;
2605 	pgf_info->page_fault.engine_id = eng_id;
2606 	hl_capture_user_mappings(hdev, is_pmmu);
2607 
2608 	pgf_info->page_fault_info_available = true;
2609 }
2610 
2611 void hl_handle_page_fault(struct hl_device *hdev, u64 addr, u16 eng_id, bool is_pmmu,
2612 				u64 *event_mask)
2613 {
2614 	hl_capture_page_fault(hdev, addr, eng_id, is_pmmu);
2615 
2616 	if (event_mask)
2617 		*event_mask |=  HL_NOTIFIER_EVENT_PAGE_FAULT;
2618 }
2619 
2620 static void hl_capture_hw_err(struct hl_device *hdev, u16 event_id)
2621 {
2622 	struct hw_err_info *info = &hdev->captured_err_info.hw_err;
2623 
2624 	/* Capture only the first HW err */
2625 	if (atomic_cmpxchg(&info->event_detected, 0, 1))
2626 		return;
2627 
2628 	info->event.timestamp = ktime_to_ns(ktime_get());
2629 	info->event.event_id = event_id;
2630 
2631 	info->event_info_available = true;
2632 }
2633 
2634 void hl_handle_critical_hw_err(struct hl_device *hdev, u16 event_id, u64 *event_mask)
2635 {
2636 	hl_capture_hw_err(hdev, event_id);
2637 
2638 	if (event_mask)
2639 		*event_mask |= HL_NOTIFIER_EVENT_CRITICL_HW_ERR;
2640 }
2641 
2642 static void hl_capture_fw_err(struct hl_device *hdev, struct hl_info_fw_err_info *fw_info)
2643 {
2644 	struct fw_err_info *info = &hdev->captured_err_info.fw_err;
2645 
2646 	/* Capture only the first FW error */
2647 	if (atomic_cmpxchg(&info->event_detected, 0, 1))
2648 		return;
2649 
2650 	info->event.timestamp = ktime_to_ns(ktime_get());
2651 	info->event.err_type = fw_info->err_type;
2652 	if (fw_info->err_type == HL_INFO_FW_REPORTED_ERR)
2653 		info->event.event_id = fw_info->event_id;
2654 
2655 	info->event_info_available = true;
2656 }
2657 
2658 void hl_handle_fw_err(struct hl_device *hdev, struct hl_info_fw_err_info *info)
2659 {
2660 	hl_capture_fw_err(hdev, info);
2661 
2662 	if (info->event_mask)
2663 		*info->event_mask |= HL_NOTIFIER_EVENT_CRITICL_FW_ERR;
2664 }
2665