1 /* SPDX-License-Identifier: GPL-2.0
2  *
3  * Copyright 2016-2022 HabanaLabs, Ltd.
4  * All Rights Reserved.
5  *
6  */
7 
8 #ifndef HABANALABSP_H_
9 #define HABANALABSP_H_
10 
11 #include "../include/common/cpucp_if.h"
12 #include "../include/common/qman_if.h"
13 #include "../include/hw_ip/mmu/mmu_general.h"
14 #include <uapi/drm/habanalabs_accel.h>
15 
16 #include <linux/cdev.h>
17 #include <linux/iopoll.h>
18 #include <linux/irqreturn.h>
19 #include <linux/dma-direction.h>
20 #include <linux/scatterlist.h>
21 #include <linux/hashtable.h>
22 #include <linux/debugfs.h>
23 #include <linux/rwsem.h>
24 #include <linux/eventfd.h>
25 #include <linux/bitfield.h>
26 #include <linux/genalloc.h>
27 #include <linux/sched/signal.h>
28 #include <linux/io-64-nonatomic-lo-hi.h>
29 #include <linux/coresight.h>
30 #include <linux/dma-buf.h>
31 
32 #include "security.h"
33 
34 #define HL_NAME				"habanalabs"
35 
36 struct hl_device;
37 struct hl_fpriv;
38 
39 /* Use upper bits of mmap offset to store habana driver specific information.
40  * bits[63:59] - Encode mmap type
41  * bits[45:0]  - mmap offset value
42  *
43  * NOTE: struct vm_area_struct.vm_pgoff uses offset in pages. Hence, these
44  *  defines are w.r.t to PAGE_SIZE
45  */
46 #define HL_MMAP_TYPE_SHIFT		(59 - PAGE_SHIFT)
47 #define HL_MMAP_TYPE_MASK		(0x1full << HL_MMAP_TYPE_SHIFT)
48 #define HL_MMAP_TYPE_TS_BUFF		(0x10ull << HL_MMAP_TYPE_SHIFT)
49 #define HL_MMAP_TYPE_BLOCK		(0x4ull << HL_MMAP_TYPE_SHIFT)
50 #define HL_MMAP_TYPE_CB			(0x2ull << HL_MMAP_TYPE_SHIFT)
51 
52 #define HL_MMAP_OFFSET_VALUE_MASK	(0x1FFFFFFFFFFFull >> PAGE_SHIFT)
53 #define HL_MMAP_OFFSET_VALUE_GET(off)	(off & HL_MMAP_OFFSET_VALUE_MASK)
54 
55 #define HL_PENDING_RESET_PER_SEC		10
56 #define HL_PENDING_RESET_MAX_TRIALS		60 /* 10 minutes */
57 #define HL_PENDING_RESET_LONG_SEC		60
58 /*
59  * In device fini, wait 10 minutes for user processes to be terminated after we kill them.
60  * This is needed to prevent situation of clearing resources while user processes are still alive.
61  */
62 #define HL_WAIT_PROCESS_KILL_ON_DEVICE_FINI	600
63 
64 #define HL_HARD_RESET_MAX_TIMEOUT	120
65 #define HL_PLDM_HARD_RESET_MAX_TIMEOUT	(HL_HARD_RESET_MAX_TIMEOUT * 3)
66 
67 #define HL_DEVICE_TIMEOUT_USEC		1000000 /* 1 s */
68 
69 #define HL_HEARTBEAT_PER_USEC		5000000 /* 5 s */
70 
71 #define HL_PLL_LOW_JOB_FREQ_USEC	5000000 /* 5 s */
72 
73 #define HL_CPUCP_INFO_TIMEOUT_USEC	10000000 /* 10s */
74 #define HL_CPUCP_EEPROM_TIMEOUT_USEC	10000000 /* 10s */
75 #define HL_CPUCP_MON_DUMP_TIMEOUT_USEC	10000000 /* 10s */
76 #define HL_CPUCP_SEC_ATTEST_INFO_TINEOUT_USEC 10000000 /* 10s */
77 
78 #define HL_FW_STATUS_POLL_INTERVAL_USEC		10000 /* 10ms */
79 #define HL_FW_COMMS_STATUS_PLDM_POLL_INTERVAL_USEC	1000000 /* 1s */
80 
81 #define HL_PCI_ELBI_TIMEOUT_MSEC	10 /* 10ms */
82 
83 #define HL_SIM_MAX_TIMEOUT_US		100000000 /* 100s */
84 
85 #define HL_INVALID_QUEUE		UINT_MAX
86 
87 #define HL_COMMON_USER_CQ_INTERRUPT_ID	0xFFF
88 #define HL_COMMON_DEC_INTERRUPT_ID	0xFFE
89 
90 #define HL_STATE_DUMP_HIST_LEN		5
91 
92 /* Default value for device reset trigger , an invalid value */
93 #define HL_RESET_TRIGGER_DEFAULT	0xFF
94 
95 #define OBJ_NAMES_HASH_TABLE_BITS	7 /* 1 << 7 buckets */
96 #define SYNC_TO_ENGINE_HASH_TABLE_BITS	7 /* 1 << 7 buckets */
97 
98 /* Memory */
99 #define MEM_HASH_TABLE_BITS		7 /* 1 << 7 buckets */
100 
101 /* MMU */
102 #define MMU_HASH_TABLE_BITS		7 /* 1 << 7 buckets */
103 
104 /**
105  * enum hl_mmu_page_table_location - mmu page table location
106  * @MMU_DR_PGT: page-table is located on device DRAM.
107  * @MMU_HR_PGT: page-table is located on host memory.
108  * @MMU_NUM_PGT_LOCATIONS: number of page-table locations currently supported.
109  */
110 enum hl_mmu_page_table_location {
111 	MMU_DR_PGT = 0,		/* device-dram-resident MMU PGT */
112 	MMU_HR_PGT,		/* host resident MMU PGT */
113 	MMU_NUM_PGT_LOCATIONS	/* num of PGT locations */
114 };
115 
116 /**
117  * enum hl_mmu_enablement - what mmu modules to enable
118  * @MMU_EN_NONE: mmu disabled.
119  * @MMU_EN_ALL: enable all.
120  * @MMU_EN_PMMU_ONLY: Enable only the PMMU leaving the DMMU disabled.
121  */
122 enum hl_mmu_enablement {
123 	MMU_EN_NONE = 0,
124 	MMU_EN_ALL = 1,
125 	MMU_EN_PMMU_ONLY = 3,	/* N/A for Goya/Gaudi */
126 };
127 
128 /*
129  * HL_RSVD_SOBS 'sync stream' reserved sync objects per QMAN stream
130  * HL_RSVD_MONS 'sync stream' reserved monitors per QMAN stream
131  */
132 #define HL_RSVD_SOBS			2
133 #define HL_RSVD_MONS			1
134 
135 /*
136  * HL_COLLECTIVE_RSVD_MSTR_MONS 'collective' reserved monitors per QMAN stream
137  */
138 #define HL_COLLECTIVE_RSVD_MSTR_MONS	2
139 
140 #define HL_MAX_SOB_VAL			(1 << 15)
141 
142 #define IS_POWER_OF_2(n)		(n != 0 && ((n & (n - 1)) == 0))
143 #define IS_MAX_PENDING_CS_VALID(n)	(IS_POWER_OF_2(n) && (n > 1))
144 
145 #define HL_PCI_NUM_BARS			6
146 
147 /* Completion queue entry relates to completed job */
148 #define HL_COMPLETION_MODE_JOB		0
149 /* Completion queue entry relates to completed command submission */
150 #define HL_COMPLETION_MODE_CS		1
151 
152 #define HL_MAX_DCORES			8
153 
154 /* DMA alloc/free wrappers */
155 #define hl_asic_dma_alloc_coherent(hdev, size, dma_handle, flags) \
156 	hl_asic_dma_alloc_coherent_caller(hdev, size, dma_handle, flags, __func__)
157 
158 #define hl_asic_dma_pool_zalloc(hdev, size, mem_flags, dma_handle) \
159 	hl_asic_dma_pool_zalloc_caller(hdev, size, mem_flags, dma_handle, __func__)
160 
161 #define hl_asic_dma_free_coherent(hdev, size, cpu_addr, dma_handle) \
162 	hl_asic_dma_free_coherent_caller(hdev, size, cpu_addr, dma_handle, __func__)
163 
164 #define hl_asic_dma_pool_free(hdev, vaddr, dma_addr) \
165 	hl_asic_dma_pool_free_caller(hdev, vaddr, dma_addr, __func__)
166 
167 /*
168  * Reset Flags
169  *
170  * - HL_DRV_RESET_HARD
171  *       If set do hard reset to all engines. If not set reset just
172  *       compute/DMA engines.
173  *
174  * - HL_DRV_RESET_FROM_RESET_THR
175  *       Set if the caller is the hard-reset thread
176  *
177  * - HL_DRV_RESET_HEARTBEAT
178  *       Set if reset is due to heartbeat
179  *
180  * - HL_DRV_RESET_TDR
181  *       Set if reset is due to TDR
182  *
183  * - HL_DRV_RESET_DEV_RELEASE
184  *       Set if reset is due to device release
185  *
186  * - HL_DRV_RESET_BYPASS_REQ_TO_FW
187  *       F/W will perform the reset. No need to ask it to reset the device. This is relevant
188  *       only when running with secured f/w
189  *
190  * - HL_DRV_RESET_FW_FATAL_ERR
191  *       Set if reset is due to a fatal error from FW
192  *
193  * - HL_DRV_RESET_DELAY
194  *       Set if a delay should be added before the reset
195  *
196  * - HL_DRV_RESET_FROM_WD_THR
197  *       Set if the caller is the device release watchdog thread
198  */
199 
200 #define HL_DRV_RESET_HARD		(1 << 0)
201 #define HL_DRV_RESET_FROM_RESET_THR	(1 << 1)
202 #define HL_DRV_RESET_HEARTBEAT		(1 << 2)
203 #define HL_DRV_RESET_TDR		(1 << 3)
204 #define HL_DRV_RESET_DEV_RELEASE	(1 << 4)
205 #define HL_DRV_RESET_BYPASS_REQ_TO_FW	(1 << 5)
206 #define HL_DRV_RESET_FW_FATAL_ERR	(1 << 6)
207 #define HL_DRV_RESET_DELAY		(1 << 7)
208 #define HL_DRV_RESET_FROM_WD_THR	(1 << 8)
209 
210 /*
211  * Security
212  */
213 
214 #define HL_PB_SHARED		1
215 #define HL_PB_NA		0
216 #define HL_PB_SINGLE_INSTANCE	1
217 #define HL_BLOCK_SIZE		0x1000
218 #define HL_BLOCK_GLBL_ERR_MASK	0xF40
219 #define HL_BLOCK_GLBL_ERR_ADDR	0xF44
220 #define HL_BLOCK_GLBL_ERR_CAUSE	0xF48
221 #define HL_BLOCK_GLBL_SEC_OFFS	0xF80
222 #define HL_BLOCK_GLBL_SEC_SIZE	(HL_BLOCK_SIZE - HL_BLOCK_GLBL_SEC_OFFS)
223 #define HL_BLOCK_GLBL_SEC_LEN	(HL_BLOCK_GLBL_SEC_SIZE / sizeof(u32))
224 #define UNSET_GLBL_SEC_BIT(array, b) ((array)[((b) / 32)] |= (1 << ((b) % 32)))
225 
226 enum hl_protection_levels {
227 	SECURED_LVL,
228 	PRIVILEGED_LVL,
229 	NON_SECURED_LVL
230 };
231 
232 /**
233  * struct iterate_module_ctx - HW module iterator
234  * @fn: function to apply to each HW module instance
235  * @data: optional internal data to the function iterator
236  * @rc: return code for optional use of iterator/iterator-caller
237  */
238 struct iterate_module_ctx {
239 	/*
240 	 * callback for the HW module iterator
241 	 * @hdev: pointer to the habanalabs device structure
242 	 * @block: block (ASIC specific definition can be dcore/hdcore)
243 	 * @inst: HW module instance within the block
244 	 * @offset: current HW module instance offset from the 1-st HW module instance
245 	 *          in the 1-st block
246 	 * @ctx: the iterator context.
247 	 */
248 	void (*fn)(struct hl_device *hdev, int block, int inst, u32 offset,
249 			struct iterate_module_ctx *ctx);
250 	void *data;
251 	int rc;
252 };
253 
254 struct hl_block_glbl_sec {
255 	u32 sec_array[HL_BLOCK_GLBL_SEC_LEN];
256 };
257 
258 #define HL_MAX_SOBS_PER_MONITOR	8
259 
260 /**
261  * struct hl_gen_wait_properties - properties for generating a wait CB
262  * @data: command buffer
263  * @q_idx: queue id is used to extract fence register address
264  * @size: offset in command buffer
265  * @sob_base: SOB base to use in this wait CB
266  * @sob_val: SOB value to wait for
267  * @mon_id: monitor to use in this wait CB
268  * @sob_mask: each bit represents a SOB offset from sob_base to be used
269  */
270 struct hl_gen_wait_properties {
271 	void	*data;
272 	u32	q_idx;
273 	u32	size;
274 	u16	sob_base;
275 	u16	sob_val;
276 	u16	mon_id;
277 	u8	sob_mask;
278 };
279 
280 /**
281  * struct pgt_info - MMU hop page info.
282  * @node: hash linked-list node for the pgts on host (shadow pgts for device resident MMU and
283  *        actual pgts for host resident MMU).
284  * @phys_addr: physical address of the pgt.
285  * @virt_addr: host virtual address of the pgt (see above device/host resident).
286  * @shadow_addr: shadow hop in the host for device resident MMU.
287  * @ctx: pointer to the owner ctx.
288  * @num_of_ptes: indicates how many ptes are used in the pgt. used only for dynamically
289  *               allocated HOPs (all HOPs but HOP0)
290  *
291  * The MMU page tables hierarchy can be placed either on the device's DRAM (in which case shadow
292  * pgts will be stored on host memory) or on host memory (in which case no shadow is required).
293  *
294  * When a new level (hop) is needed during mapping this structure will be used to describe
295  * the newly allocated hop as well as to track number of PTEs in it.
296  * During unmapping, if no valid PTEs remained in the page of a newly allocated hop, it is
297  * freed with its pgt_info structure.
298  */
299 struct pgt_info {
300 	struct hlist_node	node;
301 	u64			phys_addr;
302 	u64			virt_addr;
303 	u64			shadow_addr;
304 	struct hl_ctx		*ctx;
305 	int			num_of_ptes;
306 };
307 
308 /**
309  * enum hl_pci_match_mode - pci match mode per region
310  * @PCI_ADDRESS_MATCH_MODE: address match mode
311  * @PCI_BAR_MATCH_MODE: bar match mode
312  */
313 enum hl_pci_match_mode {
314 	PCI_ADDRESS_MATCH_MODE,
315 	PCI_BAR_MATCH_MODE
316 };
317 
318 /**
319  * enum hl_fw_component - F/W components to read version through registers.
320  * @FW_COMP_BOOT_FIT: boot fit.
321  * @FW_COMP_PREBOOT: preboot.
322  * @FW_COMP_LINUX: linux.
323  */
324 enum hl_fw_component {
325 	FW_COMP_BOOT_FIT,
326 	FW_COMP_PREBOOT,
327 	FW_COMP_LINUX,
328 };
329 
330 /**
331  * enum hl_fw_types - F/W types present in the system
332  * @FW_TYPE_NONE: no FW component indication
333  * @FW_TYPE_LINUX: Linux image for device CPU
334  * @FW_TYPE_BOOT_CPU: Boot image for device CPU
335  * @FW_TYPE_PREBOOT_CPU: Indicates pre-loaded CPUs are present in the system
336  *                       (preboot, ppboot etc...)
337  * @FW_TYPE_ALL_TYPES: Mask for all types
338  */
339 enum hl_fw_types {
340 	FW_TYPE_NONE = 0x0,
341 	FW_TYPE_LINUX = 0x1,
342 	FW_TYPE_BOOT_CPU = 0x2,
343 	FW_TYPE_PREBOOT_CPU = 0x4,
344 	FW_TYPE_ALL_TYPES =
345 		(FW_TYPE_LINUX | FW_TYPE_BOOT_CPU | FW_TYPE_PREBOOT_CPU)
346 };
347 
348 /**
349  * enum hl_queue_type - Supported QUEUE types.
350  * @QUEUE_TYPE_NA: queue is not available.
351  * @QUEUE_TYPE_EXT: external queue which is a DMA channel that may access the
352  *                  host.
353  * @QUEUE_TYPE_INT: internal queue that performs DMA inside the device's
354  *			memories and/or operates the compute engines.
355  * @QUEUE_TYPE_CPU: S/W queue for communication with the device's CPU.
356  * @QUEUE_TYPE_HW: queue of DMA and compute engines jobs, for which completion
357  *                 notifications are sent by H/W.
358  */
359 enum hl_queue_type {
360 	QUEUE_TYPE_NA,
361 	QUEUE_TYPE_EXT,
362 	QUEUE_TYPE_INT,
363 	QUEUE_TYPE_CPU,
364 	QUEUE_TYPE_HW
365 };
366 
367 enum hl_cs_type {
368 	CS_TYPE_DEFAULT,
369 	CS_TYPE_SIGNAL,
370 	CS_TYPE_WAIT,
371 	CS_TYPE_COLLECTIVE_WAIT,
372 	CS_RESERVE_SIGNALS,
373 	CS_UNRESERVE_SIGNALS,
374 	CS_TYPE_ENGINE_CORE,
375 	CS_TYPE_ENGINES,
376 	CS_TYPE_FLUSH_PCI_HBW_WRITES,
377 };
378 
379 /*
380  * struct hl_inbound_pci_region - inbound region descriptor
381  * @mode: pci match mode for this region
382  * @addr: region target address
383  * @size: region size in bytes
384  * @offset_in_bar: offset within bar (address match mode)
385  * @bar: bar id
386  */
387 struct hl_inbound_pci_region {
388 	enum hl_pci_match_mode	mode;
389 	u64			addr;
390 	u64			size;
391 	u64			offset_in_bar;
392 	u8			bar;
393 };
394 
395 /*
396  * struct hl_outbound_pci_region - outbound region descriptor
397  * @addr: region target address
398  * @size: region size in bytes
399  */
400 struct hl_outbound_pci_region {
401 	u64	addr;
402 	u64	size;
403 };
404 
405 /*
406  * enum queue_cb_alloc_flags - Indicates queue support for CBs that
407  * allocated by Kernel or by User
408  * @CB_ALLOC_KERNEL: support only CBs that allocated by Kernel
409  * @CB_ALLOC_USER: support only CBs that allocated by User
410  */
411 enum queue_cb_alloc_flags {
412 	CB_ALLOC_KERNEL = 0x1,
413 	CB_ALLOC_USER   = 0x2
414 };
415 
416 /*
417  * struct hl_hw_sob - H/W SOB info.
418  * @hdev: habanalabs device structure.
419  * @kref: refcount of this SOB. The SOB will reset once the refcount is zero.
420  * @sob_id: id of this SOB.
421  * @sob_addr: the sob offset from the base address.
422  * @q_idx: the H/W queue that uses this SOB.
423  * @need_reset: reset indication set when switching to the other sob.
424  */
425 struct hl_hw_sob {
426 	struct hl_device	*hdev;
427 	struct kref		kref;
428 	u32			sob_id;
429 	u32			sob_addr;
430 	u32			q_idx;
431 	bool			need_reset;
432 };
433 
434 enum hl_collective_mode {
435 	HL_COLLECTIVE_NOT_SUPPORTED = 0x0,
436 	HL_COLLECTIVE_MASTER = 0x1,
437 	HL_COLLECTIVE_SLAVE = 0x2
438 };
439 
440 /**
441  * struct hw_queue_properties - queue information.
442  * @type: queue type.
443  * @cb_alloc_flags: bitmap which indicates if the hw queue supports CB
444  *                  that allocated by the Kernel driver and therefore,
445  *                  a CB handle can be provided for jobs on this queue.
446  *                  Otherwise, a CB address must be provided.
447  * @collective_mode: collective mode of current queue
448  * @driver_only: true if only the driver is allowed to send a job to this queue,
449  *               false otherwise.
450  * @binned: True if the queue is binned out and should not be used
451  * @supports_sync_stream: True if queue supports sync stream
452  */
453 struct hw_queue_properties {
454 	enum hl_queue_type		type;
455 	enum queue_cb_alloc_flags	cb_alloc_flags;
456 	enum hl_collective_mode		collective_mode;
457 	u8				driver_only;
458 	u8				binned;
459 	u8				supports_sync_stream;
460 };
461 
462 /**
463  * enum vm_type - virtual memory mapping request information.
464  * @VM_TYPE_USERPTR: mapping of user memory to device virtual address.
465  * @VM_TYPE_PHYS_PACK: mapping of DRAM memory to device virtual address.
466  */
467 enum vm_type {
468 	VM_TYPE_USERPTR = 0x1,
469 	VM_TYPE_PHYS_PACK = 0x2
470 };
471 
472 /**
473  * enum mmu_op_flags - mmu operation relevant information.
474  * @MMU_OP_USERPTR: operation on user memory (host resident).
475  * @MMU_OP_PHYS_PACK: operation on DRAM (device resident).
476  * @MMU_OP_CLEAR_MEMCACHE: operation has to clear memcache.
477  * @MMU_OP_SKIP_LOW_CACHE_INV: operation is allowed to skip parts of cache invalidation.
478  */
479 enum mmu_op_flags {
480 	MMU_OP_USERPTR = 0x1,
481 	MMU_OP_PHYS_PACK = 0x2,
482 	MMU_OP_CLEAR_MEMCACHE = 0x4,
483 	MMU_OP_SKIP_LOW_CACHE_INV = 0x8,
484 };
485 
486 
487 /**
488  * enum hl_device_hw_state - H/W device state. use this to understand whether
489  *                           to do reset before hw_init or not
490  * @HL_DEVICE_HW_STATE_CLEAN: H/W state is clean. i.e. after hard reset
491  * @HL_DEVICE_HW_STATE_DIRTY: H/W state is dirty. i.e. we started to execute
492  *                            hw_init
493  */
494 enum hl_device_hw_state {
495 	HL_DEVICE_HW_STATE_CLEAN = 0,
496 	HL_DEVICE_HW_STATE_DIRTY
497 };
498 
499 #define HL_MMU_VA_ALIGNMENT_NOT_NEEDED 0
500 
501 /**
502  * struct hl_mmu_properties - ASIC specific MMU address translation properties.
503  * @start_addr: virtual start address of the memory region.
504  * @end_addr: virtual end address of the memory region.
505  * @hop_shifts: array holds HOPs shifts.
506  * @hop_masks: array holds HOPs masks.
507  * @last_mask: mask to get the bit indicating this is the last hop.
508  * @pgt_size: size for page tables.
509  * @supported_pages_mask: bitmask for supported page size (relevant only for MMUs
510  *                        supporting multiple page size).
511  * @page_size: default page size used to allocate memory.
512  * @num_hops: The amount of hops supported by the translation table.
513  * @hop_table_size: HOP table size.
514  * @hop0_tables_total_size: total size for all HOP0 tables.
515  * @host_resident: Should the MMU page table reside in host memory or in the
516  *                 device DRAM.
517  */
518 struct hl_mmu_properties {
519 	u64	start_addr;
520 	u64	end_addr;
521 	u64	hop_shifts[MMU_HOP_MAX];
522 	u64	hop_masks[MMU_HOP_MAX];
523 	u64	last_mask;
524 	u64	pgt_size;
525 	u64	supported_pages_mask;
526 	u32	page_size;
527 	u32	num_hops;
528 	u32	hop_table_size;
529 	u32	hop0_tables_total_size;
530 	u8	host_resident;
531 };
532 
533 /**
534  * struct hl_hints_range - hint addresses reserved va range.
535  * @start_addr: start address of the va range.
536  * @end_addr: end address of the va range.
537  */
538 struct hl_hints_range {
539 	u64 start_addr;
540 	u64 end_addr;
541 };
542 
543 /**
544  * struct asic_fixed_properties - ASIC specific immutable properties.
545  * @hw_queues_props: H/W queues properties.
546  * @special_blocks: points to an array containing special blocks info.
547  * @skip_special_blocks_cfg: special blocks skip configs.
548  * @cpucp_info: received various information from CPU-CP regarding the H/W, e.g.
549  *		available sensors.
550  * @uboot_ver: F/W U-boot version.
551  * @preboot_ver: F/W Preboot version.
552  * @dmmu: DRAM MMU address translation properties.
553  * @pmmu: PCI (host) MMU address translation properties.
554  * @pmmu_huge: PCI (host) MMU address translation properties for memory
555  *              allocated with huge pages.
556  * @hints_dram_reserved_va_range: dram hint addresses reserved range.
557  * @hints_host_reserved_va_range: host hint addresses reserved range.
558  * @hints_host_hpage_reserved_va_range: host huge page hint addresses reserved
559  *                                      range.
560  * @sram_base_address: SRAM physical start address.
561  * @sram_end_address: SRAM physical end address.
562  * @sram_user_base_address - SRAM physical start address for user access.
563  * @dram_base_address: DRAM physical start address.
564  * @dram_end_address: DRAM physical end address.
565  * @dram_user_base_address: DRAM physical start address for user access.
566  * @dram_size: DRAM total size.
567  * @dram_pci_bar_size: size of PCI bar towards DRAM.
568  * @max_power_default: max power of the device after reset.
569  * @dc_power_default: power consumed by the device in mode idle.
570  * @dram_size_for_default_page_mapping: DRAM size needed to map to avoid page
571  *                                      fault.
572  * @pcie_dbi_base_address: Base address of the PCIE_DBI block.
573  * @pcie_aux_dbi_reg_addr: Address of the PCIE_AUX DBI register.
574  * @mmu_pgt_addr: base physical address in DRAM of MMU page tables.
575  * @mmu_dram_default_page_addr: DRAM default page physical address.
576  * @tpc_enabled_mask: which TPCs are enabled.
577  * @tpc_binning_mask: which TPCs are binned. 0 means usable and 1 means binned.
578  * @dram_enabled_mask: which DRAMs are enabled.
579  * @dram_binning_mask: which DRAMs are binned. 0 means usable, 1 means binned.
580  * @dram_hints_align_mask: dram va hint addresses alignment mask which is used
581  *                  for hints validity check.
582  * @cfg_base_address: config space base address.
583  * @mmu_cache_mng_addr: address of the MMU cache.
584  * @mmu_cache_mng_size: size of the MMU cache.
585  * @device_dma_offset_for_host_access: the offset to add to host DMA addresses
586  *                                     to enable the device to access them.
587  * @host_base_address: host physical start address for host DMA from device
588  * @host_end_address: host physical end address for host DMA from device
589  * @max_freq_value: current max clk frequency.
590  * @engine_core_interrupt_reg_addr: interrupt register address for engine core to use
591  *                                  in order to raise events toward FW.
592  * @clk_pll_index: clock PLL index that specify which PLL determines the clock
593  *                 we display to the user
594  * @mmu_pgt_size: MMU page tables total size.
595  * @mmu_pte_size: PTE size in MMU page tables.
596  * @mmu_hop_table_size: MMU hop table size.
597  * @mmu_hop0_tables_total_size: total size of MMU hop0 tables.
598  * @dram_page_size: page size for MMU DRAM allocation.
599  * @cfg_size: configuration space size on SRAM.
600  * @sram_size: total size of SRAM.
601  * @max_asid: maximum number of open contexts (ASIDs).
602  * @num_of_events: number of possible internal H/W IRQs.
603  * @psoc_pci_pll_nr: PCI PLL NR value.
604  * @psoc_pci_pll_nf: PCI PLL NF value.
605  * @psoc_pci_pll_od: PCI PLL OD value.
606  * @psoc_pci_pll_div_factor: PCI PLL DIV FACTOR 1 value.
607  * @psoc_timestamp_frequency: frequency of the psoc timestamp clock.
608  * @high_pll: high PLL frequency used by the device.
609  * @cb_pool_cb_cnt: number of CBs in the CB pool.
610  * @cb_pool_cb_size: size of each CB in the CB pool.
611  * @decoder_enabled_mask: which decoders are enabled.
612  * @decoder_binning_mask: which decoders are binned, 0 means usable and 1 means binned.
613  * @rotator_enabled_mask: which rotators are enabled.
614  * @edma_enabled_mask: which EDMAs are enabled.
615  * @edma_binning_mask: which EDMAs are binned, 0 means usable and 1 means
616  *                     binned (at most one binned DMA).
617  * @max_pending_cs: maximum of concurrent pending command submissions
618  * @max_queues: maximum amount of queues in the system
619  * @fw_preboot_cpu_boot_dev_sts0: bitmap representation of preboot cpu
620  *                                capabilities reported by FW, bit description
621  *                                can be found in CPU_BOOT_DEV_STS0
622  * @fw_preboot_cpu_boot_dev_sts1: bitmap representation of preboot cpu
623  *                                capabilities reported by FW, bit description
624  *                                can be found in CPU_BOOT_DEV_STS1
625  * @fw_bootfit_cpu_boot_dev_sts0: bitmap representation of boot cpu security
626  *                                status reported by FW, bit description can be
627  *                                found in CPU_BOOT_DEV_STS0
628  * @fw_bootfit_cpu_boot_dev_sts1: bitmap representation of boot cpu security
629  *                                status reported by FW, bit description can be
630  *                                found in CPU_BOOT_DEV_STS1
631  * @fw_app_cpu_boot_dev_sts0: bitmap representation of application security
632  *                            status reported by FW, bit description can be
633  *                            found in CPU_BOOT_DEV_STS0
634  * @fw_app_cpu_boot_dev_sts1: bitmap representation of application security
635  *                            status reported by FW, bit description can be
636  *                            found in CPU_BOOT_DEV_STS1
637  * @max_dec: maximum number of decoders
638  * @hmmu_hif_enabled_mask: mask of HMMUs/HIFs that are not isolated (enabled)
639  *                         1- enabled, 0- isolated.
640  * @faulty_dram_cluster_map: mask of faulty DRAM cluster.
641  *                         1- faulty cluster, 0- good cluster.
642  * @xbar_edge_enabled_mask: mask of XBAR_EDGEs that are not isolated (enabled)
643  *                          1- enabled, 0- isolated.
644  * @device_mem_alloc_default_page_size: may be different than dram_page_size only for ASICs for
645  *                                      which the property supports_user_set_page_size is true
646  *                                      (i.e. the DRAM supports multiple page sizes), otherwise
647  *                                      it will shall  be equal to dram_page_size.
648  * @num_engine_cores: number of engine cpu cores.
649  * @max_num_of_engines: maximum number of all engines in the ASIC.
650  * @num_of_special_blocks: special_blocks array size.
651  * @glbl_err_cause_num: global err cause number.
652  * @hbw_flush_reg: register to read to generate HBW flush. value of 0 means HBW flush is
653  *                 not supported.
654  * @collective_first_sob: first sync object available for collective use
655  * @collective_first_mon: first monitor available for collective use
656  * @sync_stream_first_sob: first sync object available for sync stream use
657  * @sync_stream_first_mon: first monitor available for sync stream use
658  * @first_available_user_sob: first sob available for the user
659  * @first_available_user_mon: first monitor available for the user
660  * @first_available_user_interrupt: first available interrupt reserved for the user
661  * @first_available_cq: first available CQ for the user.
662  * @user_interrupt_count: number of user interrupts.
663  * @user_dec_intr_count: number of decoder interrupts exposed to user.
664  * @tpc_interrupt_id: interrupt id for TPC to use in order to raise events towards the host.
665  * @eq_interrupt_id: interrupt id for EQ, uses to synchronize EQ interrupts in hard-reset.
666  * @cache_line_size: device cache line size.
667  * @server_type: Server type that the ASIC is currently installed in.
668  *               The value is according to enum hl_server_type in uapi file.
669  * @completion_queues_count: number of completion queues.
670  * @completion_mode: 0 - job based completion, 1 - cs based completion
671  * @mme_master_slave_mode: 0 - Each MME works independently, 1 - MME works
672  *                         in Master/Slave mode
673  * @fw_security_enabled: true if security measures are enabled in firmware,
674  *                       false otherwise
675  * @fw_cpu_boot_dev_sts0_valid: status bits are valid and can be fetched from
676  *                              BOOT_DEV_STS0
677  * @fw_cpu_boot_dev_sts1_valid: status bits are valid and can be fetched from
678  *                              BOOT_DEV_STS1
679  * @dram_supports_virtual_memory: is there an MMU towards the DRAM
680  * @hard_reset_done_by_fw: true if firmware is handling hard reset flow
681  * @num_functional_hbms: number of functional HBMs in each DCORE.
682  * @hints_range_reservation: device support hint addresses range reservation.
683  * @iatu_done_by_fw: true if iATU configuration is being done by FW.
684  * @dynamic_fw_load: is dynamic FW load is supported.
685  * @gic_interrupts_enable: true if FW is not blocking GIC controller,
686  *                         false otherwise.
687  * @use_get_power_for_reset_history: To support backward compatibility for Goya
688  *                                   and Gaudi
689  * @supports_compute_reset: is a reset which is not a hard-reset supported by this asic.
690  * @allow_inference_soft_reset: true if the ASIC supports soft reset that is
691  *                              initiated by user or TDR. This is only true
692  *                              in inference ASICs, as there is no real-world
693  *                              use-case of doing soft-reset in training (due
694  *                              to the fact that training runs on multiple
695  *                              devices)
696  * @configurable_stop_on_err: is stop-on-error option configurable via debugfs.
697  * @set_max_power_on_device_init: true if need to set max power in F/W on device init.
698  * @supports_user_set_page_size: true if user can set the allocation page size.
699  * @dma_mask: the dma mask to be set for this device
700  * @supports_advanced_cpucp_rc: true if new cpucp opcodes are supported.
701  * @supports_engine_modes: true if changing engines/engine_cores modes is supported.
702  */
703 struct asic_fixed_properties {
704 	struct hw_queue_properties	*hw_queues_props;
705 	struct hl_special_block_info	*special_blocks;
706 	struct hl_skip_blocks_cfg	skip_special_blocks_cfg;
707 	struct cpucp_info		cpucp_info;
708 	char				uboot_ver[VERSION_MAX_LEN];
709 	char				preboot_ver[VERSION_MAX_LEN];
710 	struct hl_mmu_properties	dmmu;
711 	struct hl_mmu_properties	pmmu;
712 	struct hl_mmu_properties	pmmu_huge;
713 	struct hl_hints_range		hints_dram_reserved_va_range;
714 	struct hl_hints_range		hints_host_reserved_va_range;
715 	struct hl_hints_range		hints_host_hpage_reserved_va_range;
716 	u64				sram_base_address;
717 	u64				sram_end_address;
718 	u64				sram_user_base_address;
719 	u64				dram_base_address;
720 	u64				dram_end_address;
721 	u64				dram_user_base_address;
722 	u64				dram_size;
723 	u64				dram_pci_bar_size;
724 	u64				max_power_default;
725 	u64				dc_power_default;
726 	u64				dram_size_for_default_page_mapping;
727 	u64				pcie_dbi_base_address;
728 	u64				pcie_aux_dbi_reg_addr;
729 	u64				mmu_pgt_addr;
730 	u64				mmu_dram_default_page_addr;
731 	u64				tpc_enabled_mask;
732 	u64				tpc_binning_mask;
733 	u64				dram_enabled_mask;
734 	u64				dram_binning_mask;
735 	u64				dram_hints_align_mask;
736 	u64				cfg_base_address;
737 	u64				mmu_cache_mng_addr;
738 	u64				mmu_cache_mng_size;
739 	u64				device_dma_offset_for_host_access;
740 	u64				host_base_address;
741 	u64				host_end_address;
742 	u64				max_freq_value;
743 	u64				engine_core_interrupt_reg_addr;
744 	u32				clk_pll_index;
745 	u32				mmu_pgt_size;
746 	u32				mmu_pte_size;
747 	u32				mmu_hop_table_size;
748 	u32				mmu_hop0_tables_total_size;
749 	u32				dram_page_size;
750 	u32				cfg_size;
751 	u32				sram_size;
752 	u32				max_asid;
753 	u32				num_of_events;
754 	u32				psoc_pci_pll_nr;
755 	u32				psoc_pci_pll_nf;
756 	u32				psoc_pci_pll_od;
757 	u32				psoc_pci_pll_div_factor;
758 	u32				psoc_timestamp_frequency;
759 	u32				high_pll;
760 	u32				cb_pool_cb_cnt;
761 	u32				cb_pool_cb_size;
762 	u32				decoder_enabled_mask;
763 	u32				decoder_binning_mask;
764 	u32				rotator_enabled_mask;
765 	u32				edma_enabled_mask;
766 	u32				edma_binning_mask;
767 	u32				max_pending_cs;
768 	u32				max_queues;
769 	u32				fw_preboot_cpu_boot_dev_sts0;
770 	u32				fw_preboot_cpu_boot_dev_sts1;
771 	u32				fw_bootfit_cpu_boot_dev_sts0;
772 	u32				fw_bootfit_cpu_boot_dev_sts1;
773 	u32				fw_app_cpu_boot_dev_sts0;
774 	u32				fw_app_cpu_boot_dev_sts1;
775 	u32				max_dec;
776 	u32				hmmu_hif_enabled_mask;
777 	u32				faulty_dram_cluster_map;
778 	u32				xbar_edge_enabled_mask;
779 	u32				device_mem_alloc_default_page_size;
780 	u32				num_engine_cores;
781 	u32				max_num_of_engines;
782 	u32				num_of_special_blocks;
783 	u32				glbl_err_cause_num;
784 	u32				hbw_flush_reg;
785 	u16				collective_first_sob;
786 	u16				collective_first_mon;
787 	u16				sync_stream_first_sob;
788 	u16				sync_stream_first_mon;
789 	u16				first_available_user_sob[HL_MAX_DCORES];
790 	u16				first_available_user_mon[HL_MAX_DCORES];
791 	u16				first_available_user_interrupt;
792 	u16				first_available_cq[HL_MAX_DCORES];
793 	u16				user_interrupt_count;
794 	u16				user_dec_intr_count;
795 	u16				tpc_interrupt_id;
796 	u16				eq_interrupt_id;
797 	u16				cache_line_size;
798 	u16				server_type;
799 	u8				completion_queues_count;
800 	u8				completion_mode;
801 	u8				mme_master_slave_mode;
802 	u8				fw_security_enabled;
803 	u8				fw_cpu_boot_dev_sts0_valid;
804 	u8				fw_cpu_boot_dev_sts1_valid;
805 	u8				dram_supports_virtual_memory;
806 	u8				hard_reset_done_by_fw;
807 	u8				num_functional_hbms;
808 	u8				hints_range_reservation;
809 	u8				iatu_done_by_fw;
810 	u8				dynamic_fw_load;
811 	u8				gic_interrupts_enable;
812 	u8				use_get_power_for_reset_history;
813 	u8				supports_compute_reset;
814 	u8				allow_inference_soft_reset;
815 	u8				configurable_stop_on_err;
816 	u8				set_max_power_on_device_init;
817 	u8				supports_user_set_page_size;
818 	u8				dma_mask;
819 	u8				supports_advanced_cpucp_rc;
820 	u8				supports_engine_modes;
821 };
822 
823 /**
824  * struct hl_fence - software synchronization primitive
825  * @completion: fence is implemented using completion
826  * @refcount: refcount for this fence
827  * @cs_sequence: sequence of the corresponding command submission
828  * @stream_master_qid_map: streams masters QID bitmap to represent all streams
829  *                         masters QIDs that multi cs is waiting on
830  * @error: mark this fence with error
831  * @timestamp: timestamp upon completion
832  * @mcs_handling_done: indicates that corresponding command submission has
833  *                     finished msc handling, this does not mean it was part
834  *                     of the mcs
835  */
836 struct hl_fence {
837 	struct completion	completion;
838 	struct kref		refcount;
839 	u64			cs_sequence;
840 	u32			stream_master_qid_map;
841 	int			error;
842 	ktime_t			timestamp;
843 	u8			mcs_handling_done;
844 };
845 
846 /**
847  * struct hl_cs_compl - command submission completion object.
848  * @base_fence: hl fence object.
849  * @lock: spinlock to protect fence.
850  * @hdev: habanalabs device structure.
851  * @hw_sob: the H/W SOB used in this signal/wait CS.
852  * @encaps_sig_hdl: encaps signals handler.
853  * @cs_seq: command submission sequence number.
854  * @type: type of the CS - signal/wait.
855  * @sob_val: the SOB value that is used in this signal/wait CS.
856  * @sob_group: the SOB group that is used in this collective wait CS.
857  * @encaps_signals: indication whether it's a completion object of cs with
858  * encaps signals or not.
859  */
860 struct hl_cs_compl {
861 	struct hl_fence		base_fence;
862 	spinlock_t		lock;
863 	struct hl_device	*hdev;
864 	struct hl_hw_sob	*hw_sob;
865 	struct hl_cs_encaps_sig_handle *encaps_sig_hdl;
866 	u64			cs_seq;
867 	enum hl_cs_type		type;
868 	u16			sob_val;
869 	u16			sob_group;
870 	bool			encaps_signals;
871 };
872 
873 /*
874  * Command Buffers
875  */
876 
877 /**
878  * struct hl_ts_buff - describes a timestamp buffer.
879  * @kernel_buff_address: Holds the internal buffer's kernel virtual address.
880  * @user_buff_address: Holds the user buffer's kernel virtual address.
881  * @kernel_buff_size: Holds the internal kernel buffer size.
882  */
883 struct hl_ts_buff {
884 	void			*kernel_buff_address;
885 	void			*user_buff_address;
886 	u32			kernel_buff_size;
887 };
888 
889 struct hl_mmap_mem_buf;
890 
891 /**
892  * struct hl_mem_mgr - describes unified memory manager for mappable memory chunks.
893  * @dev: back pointer to the owning device
894  * @lock: protects handles
895  * @handles: an idr holding all active handles to the memory buffers in the system.
896  */
897 struct hl_mem_mgr {
898 	struct device *dev;
899 	spinlock_t lock;
900 	struct idr handles;
901 };
902 
903 /**
904  * struct hl_mmap_mem_buf_behavior - describes unified memory manager buffer behavior
905  * @topic: string identifier used for logging
906  * @mem_id: memory type identifier, embedded in the handle and used to identify
907  *          the memory type by handle.
908  * @alloc: callback executed on buffer allocation, shall allocate the memory,
909  *         set it under buffer private, and set mappable size.
910  * @mmap: callback executed on mmap, must map the buffer to vma
911  * @release: callback executed on release, must free the resources used by the buffer
912  */
913 struct hl_mmap_mem_buf_behavior {
914 	const char *topic;
915 	u64 mem_id;
916 
917 	int (*alloc)(struct hl_mmap_mem_buf *buf, gfp_t gfp, void *args);
918 	int (*mmap)(struct hl_mmap_mem_buf *buf, struct vm_area_struct *vma, void *args);
919 	void (*release)(struct hl_mmap_mem_buf *buf);
920 };
921 
922 /**
923  * struct hl_mmap_mem_buf - describes a single unified memory buffer
924  * @behavior: buffer behavior
925  * @mmg: back pointer to the unified memory manager
926  * @refcount: reference counter for buffer users
927  * @private: pointer to buffer behavior private data
928  * @mmap: atomic boolean indicating whether or not the buffer is mapped right now
929  * @real_mapped_size: the actual size of buffer mapped, after part of it may be released,
930  *                   may change at runtime.
931  * @mappable_size: the original mappable size of the buffer, does not change after
932  *                 the allocation.
933  * @handle: the buffer id in mmg handles store
934  */
935 struct hl_mmap_mem_buf {
936 	struct hl_mmap_mem_buf_behavior *behavior;
937 	struct hl_mem_mgr *mmg;
938 	struct kref refcount;
939 	void *private;
940 	atomic_t mmap;
941 	u64 real_mapped_size;
942 	u64 mappable_size;
943 	u64 handle;
944 };
945 
946 /**
947  * struct hl_cb - describes a Command Buffer.
948  * @hdev: pointer to device this CB belongs to.
949  * @ctx: pointer to the CB owner's context.
950  * @buf: back pointer to the parent mappable memory buffer
951  * @debugfs_list: node in debugfs list of command buffers.
952  * @pool_list: node in pool list of command buffers.
953  * @kernel_address: Holds the CB's kernel virtual address.
954  * @virtual_addr: Holds the CB's virtual address.
955  * @bus_address: Holds the CB's DMA address.
956  * @size: holds the CB's size.
957  * @roundup_size: holds the cb size after roundup to page size.
958  * @cs_cnt: holds number of CS that this CB participates in.
959  * @is_handle_destroyed: atomic boolean indicating whether or not the CB handle was destroyed.
960  * @is_pool: true if CB was acquired from the pool, false otherwise.
961  * @is_internal: internally allocated
962  * @is_mmu_mapped: true if the CB is mapped to the device's MMU.
963  */
964 struct hl_cb {
965 	struct hl_device	*hdev;
966 	struct hl_ctx		*ctx;
967 	struct hl_mmap_mem_buf	*buf;
968 	struct list_head	debugfs_list;
969 	struct list_head	pool_list;
970 	void			*kernel_address;
971 	u64			virtual_addr;
972 	dma_addr_t		bus_address;
973 	u32			size;
974 	u32			roundup_size;
975 	atomic_t		cs_cnt;
976 	atomic_t		is_handle_destroyed;
977 	u8			is_pool;
978 	u8			is_internal;
979 	u8			is_mmu_mapped;
980 };
981 
982 
983 /*
984  * QUEUES
985  */
986 
987 struct hl_cs_job;
988 
989 /* Queue length of external and HW queues */
990 #define HL_QUEUE_LENGTH			4096
991 #define HL_QUEUE_SIZE_IN_BYTES		(HL_QUEUE_LENGTH * HL_BD_SIZE)
992 
993 #if (HL_MAX_JOBS_PER_CS > HL_QUEUE_LENGTH)
994 #error "HL_QUEUE_LENGTH must be greater than HL_MAX_JOBS_PER_CS"
995 #endif
996 
997 /* HL_CQ_LENGTH is in units of struct hl_cq_entry */
998 #define HL_CQ_LENGTH			HL_QUEUE_LENGTH
999 #define HL_CQ_SIZE_IN_BYTES		(HL_CQ_LENGTH * HL_CQ_ENTRY_SIZE)
1000 
1001 /* Must be power of 2 */
1002 #define HL_EQ_LENGTH			64
1003 #define HL_EQ_SIZE_IN_BYTES		(HL_EQ_LENGTH * HL_EQ_ENTRY_SIZE)
1004 
1005 /* Host <-> CPU-CP shared memory size */
1006 #define HL_CPU_ACCESSIBLE_MEM_SIZE	SZ_2M
1007 
1008 /**
1009  * struct hl_sync_stream_properties -
1010  *     describes a H/W queue sync stream properties
1011  * @hw_sob: array of the used H/W SOBs by this H/W queue.
1012  * @next_sob_val: the next value to use for the currently used SOB.
1013  * @base_sob_id: the base SOB id of the SOBs used by this queue.
1014  * @base_mon_id: the base MON id of the MONs used by this queue.
1015  * @collective_mstr_mon_id: the MON ids of the MONs used by this master queue
1016  *                          in order to sync with all slave queues.
1017  * @collective_slave_mon_id: the MON id used by this slave queue in order to
1018  *                           sync with its master queue.
1019  * @collective_sob_id: current SOB id used by this collective slave queue
1020  *                     to signal its collective master queue upon completion.
1021  * @curr_sob_offset: the id offset to the currently used SOB from the
1022  *                   HL_RSVD_SOBS that are being used by this queue.
1023  */
1024 struct hl_sync_stream_properties {
1025 	struct hl_hw_sob hw_sob[HL_RSVD_SOBS];
1026 	u16		next_sob_val;
1027 	u16		base_sob_id;
1028 	u16		base_mon_id;
1029 	u16		collective_mstr_mon_id[HL_COLLECTIVE_RSVD_MSTR_MONS];
1030 	u16		collective_slave_mon_id;
1031 	u16		collective_sob_id;
1032 	u8		curr_sob_offset;
1033 };
1034 
1035 /**
1036  * struct hl_encaps_signals_mgr - describes sync stream encapsulated signals
1037  * handlers manager
1038  * @lock: protects handles.
1039  * @handles: an idr to hold all encapsulated signals handles.
1040  */
1041 struct hl_encaps_signals_mgr {
1042 	spinlock_t		lock;
1043 	struct idr		handles;
1044 };
1045 
1046 /**
1047  * struct hl_hw_queue - describes a H/W transport queue.
1048  * @shadow_queue: pointer to a shadow queue that holds pointers to jobs.
1049  * @sync_stream_prop: sync stream queue properties
1050  * @queue_type: type of queue.
1051  * @collective_mode: collective mode of current queue
1052  * @kernel_address: holds the queue's kernel virtual address.
1053  * @bus_address: holds the queue's DMA address.
1054  * @pi: holds the queue's pi value.
1055  * @ci: holds the queue's ci value, AS CALCULATED BY THE DRIVER (not real ci).
1056  * @hw_queue_id: the id of the H/W queue.
1057  * @cq_id: the id for the corresponding CQ for this H/W queue.
1058  * @msi_vec: the IRQ number of the H/W queue.
1059  * @int_queue_len: length of internal queue (number of entries).
1060  * @valid: is the queue valid (we have array of 32 queues, not all of them
1061  *         exist).
1062  * @supports_sync_stream: True if queue supports sync stream
1063  */
1064 struct hl_hw_queue {
1065 	struct hl_cs_job			**shadow_queue;
1066 	struct hl_sync_stream_properties	sync_stream_prop;
1067 	enum hl_queue_type			queue_type;
1068 	enum hl_collective_mode			collective_mode;
1069 	void					*kernel_address;
1070 	dma_addr_t				bus_address;
1071 	u32					pi;
1072 	atomic_t				ci;
1073 	u32					hw_queue_id;
1074 	u32					cq_id;
1075 	u32					msi_vec;
1076 	u16					int_queue_len;
1077 	u8					valid;
1078 	u8					supports_sync_stream;
1079 };
1080 
1081 /**
1082  * struct hl_cq - describes a completion queue
1083  * @hdev: pointer to the device structure
1084  * @kernel_address: holds the queue's kernel virtual address
1085  * @bus_address: holds the queue's DMA address
1086  * @cq_idx: completion queue index in array
1087  * @hw_queue_id: the id of the matching H/W queue
1088  * @ci: ci inside the queue
1089  * @pi: pi inside the queue
1090  * @free_slots_cnt: counter of free slots in queue
1091  */
1092 struct hl_cq {
1093 	struct hl_device	*hdev;
1094 	void			*kernel_address;
1095 	dma_addr_t		bus_address;
1096 	u32			cq_idx;
1097 	u32			hw_queue_id;
1098 	u32			ci;
1099 	u32			pi;
1100 	atomic_t		free_slots_cnt;
1101 };
1102 
1103 enum hl_user_interrupt_type {
1104 	HL_USR_INTERRUPT_CQ = 0,
1105 	HL_USR_INTERRUPT_DECODER,
1106 	HL_USR_INTERRUPT_TPC,
1107 	HL_USR_INTERRUPT_UNEXPECTED
1108 };
1109 
1110 /**
1111  * struct hl_user_interrupt - holds user interrupt information
1112  * @hdev: pointer to the device structure
1113  * @type: user interrupt type
1114  * @wait_list_head: head to the list of user threads pending on this interrupt
1115  * @wait_list_lock: protects wait_list_head
1116  * @timestamp: last timestamp taken upon interrupt
1117  * @interrupt_id: msix interrupt id
1118  */
1119 struct hl_user_interrupt {
1120 	struct hl_device		*hdev;
1121 	enum hl_user_interrupt_type	type;
1122 	struct list_head		wait_list_head;
1123 	spinlock_t			wait_list_lock;
1124 	ktime_t				timestamp;
1125 	u32				interrupt_id;
1126 };
1127 
1128 /**
1129  * struct timestamp_reg_free_node - holds the timestamp registration free objects node
1130  * @free_objects_node: node in the list free_obj_jobs
1131  * @cq_cb: pointer to cq command buffer to be freed
1132  * @buf: pointer to timestamp buffer to be freed
1133  */
1134 struct timestamp_reg_free_node {
1135 	struct list_head	free_objects_node;
1136 	struct hl_cb		*cq_cb;
1137 	struct hl_mmap_mem_buf	*buf;
1138 };
1139 
1140 /* struct timestamp_reg_work_obj - holds the timestamp registration free objects job
1141  * the job will be to pass over the free_obj_jobs list and put refcount to objects
1142  * in each node of the list
1143  * @free_obj: workqueue object to free timestamp registration node objects
1144  * @hdev: pointer to the device structure
1145  * @free_obj_head: list of free jobs nodes (node type timestamp_reg_free_node)
1146  */
1147 struct timestamp_reg_work_obj {
1148 	struct work_struct	free_obj;
1149 	struct hl_device	*hdev;
1150 	struct list_head	*free_obj_head;
1151 };
1152 
1153 /* struct timestamp_reg_info - holds the timestamp registration related data.
1154  * @buf: pointer to the timestamp buffer which include both user/kernel buffers.
1155  *       relevant only when doing timestamps records registration.
1156  * @cq_cb: pointer to CQ counter CB.
1157  * @timestamp_kernel_addr: timestamp handle address, where to set timestamp
1158  *                         relevant only when doing timestamps records
1159  *                         registration.
1160  * @in_use: indicates if the node already in use. relevant only when doing
1161  *          timestamps records registration, since in this case the driver
1162  *          will have it's own buffer which serve as a records pool instead of
1163  *          allocating records dynamically.
1164  */
1165 struct timestamp_reg_info {
1166 	struct hl_mmap_mem_buf	*buf;
1167 	struct hl_cb		*cq_cb;
1168 	u64			*timestamp_kernel_addr;
1169 	u8			in_use;
1170 };
1171 
1172 /**
1173  * struct hl_user_pending_interrupt - holds a context to a user thread
1174  *                                    pending on an interrupt
1175  * @ts_reg_info: holds the timestamps registration nodes info
1176  * @wait_list_node: node in the list of user threads pending on an interrupt
1177  * @fence: hl fence object for interrupt completion
1178  * @cq_target_value: CQ target value
1179  * @cq_kernel_addr: CQ kernel address, to be used in the cq interrupt
1180  *                  handler for target value comparison
1181  */
1182 struct hl_user_pending_interrupt {
1183 	struct timestamp_reg_info	ts_reg_info;
1184 	struct list_head		wait_list_node;
1185 	struct hl_fence			fence;
1186 	u64				cq_target_value;
1187 	u64				*cq_kernel_addr;
1188 };
1189 
1190 /**
1191  * struct hl_eq - describes the event queue (single one per device)
1192  * @hdev: pointer to the device structure
1193  * @kernel_address: holds the queue's kernel virtual address
1194  * @bus_address: holds the queue's DMA address
1195  * @ci: ci inside the queue
1196  * @prev_eqe_index: the index of the previous event queue entry. The index of
1197  *                  the current entry's index must be +1 of the previous one.
1198  * @check_eqe_index: do we need to check the index of the current entry vs. the
1199  *                   previous one. This is for backward compatibility with older
1200  *                   firmwares
1201  */
1202 struct hl_eq {
1203 	struct hl_device	*hdev;
1204 	void			*kernel_address;
1205 	dma_addr_t		bus_address;
1206 	u32			ci;
1207 	u32			prev_eqe_index;
1208 	bool			check_eqe_index;
1209 };
1210 
1211 /**
1212  * struct hl_dec - describes a decoder sw instance.
1213  * @hdev: pointer to the device structure.
1214  * @abnrm_intr_work: workqueue work item to run when decoder generates an error interrupt.
1215  * @core_id: ID of the decoder.
1216  * @base_addr: base address of the decoder.
1217  */
1218 struct hl_dec {
1219 	struct hl_device	*hdev;
1220 	struct work_struct	abnrm_intr_work;
1221 	u32			core_id;
1222 	u32			base_addr;
1223 };
1224 
1225 /**
1226  * enum hl_asic_type - supported ASIC types.
1227  * @ASIC_INVALID: Invalid ASIC type.
1228  * @ASIC_GOYA: Goya device (HL-1000).
1229  * @ASIC_GAUDI: Gaudi device (HL-2000).
1230  * @ASIC_GAUDI_SEC: Gaudi secured device (HL-2000).
1231  * @ASIC_GAUDI2: Gaudi2 device.
1232  * @ASIC_GAUDI2B: Gaudi2B device.
1233  */
1234 enum hl_asic_type {
1235 	ASIC_INVALID,
1236 	ASIC_GOYA,
1237 	ASIC_GAUDI,
1238 	ASIC_GAUDI_SEC,
1239 	ASIC_GAUDI2,
1240 	ASIC_GAUDI2B,
1241 };
1242 
1243 struct hl_cs_parser;
1244 
1245 /**
1246  * enum hl_pm_mng_profile - power management profile.
1247  * @PM_AUTO: internal clock is set by the Linux driver.
1248  * @PM_MANUAL: internal clock is set by the user.
1249  * @PM_LAST: last power management type.
1250  */
1251 enum hl_pm_mng_profile {
1252 	PM_AUTO = 1,
1253 	PM_MANUAL,
1254 	PM_LAST
1255 };
1256 
1257 /**
1258  * enum hl_pll_frequency - PLL frequency.
1259  * @PLL_HIGH: high frequency.
1260  * @PLL_LOW: low frequency.
1261  * @PLL_LAST: last frequency values that were configured by the user.
1262  */
1263 enum hl_pll_frequency {
1264 	PLL_HIGH = 1,
1265 	PLL_LOW,
1266 	PLL_LAST
1267 };
1268 
1269 #define PLL_REF_CLK 50
1270 
1271 enum div_select_defs {
1272 	DIV_SEL_REF_CLK = 0,
1273 	DIV_SEL_PLL_CLK = 1,
1274 	DIV_SEL_DIVIDED_REF = 2,
1275 	DIV_SEL_DIVIDED_PLL = 3,
1276 };
1277 
1278 enum debugfs_access_type {
1279 	DEBUGFS_READ8,
1280 	DEBUGFS_WRITE8,
1281 	DEBUGFS_READ32,
1282 	DEBUGFS_WRITE32,
1283 	DEBUGFS_READ64,
1284 	DEBUGFS_WRITE64,
1285 };
1286 
1287 enum pci_region {
1288 	PCI_REGION_CFG,
1289 	PCI_REGION_SRAM,
1290 	PCI_REGION_DRAM,
1291 	PCI_REGION_SP_SRAM,
1292 	PCI_REGION_NUMBER,
1293 };
1294 
1295 /**
1296  * struct pci_mem_region - describe memory region in a PCI bar
1297  * @region_base: region base address
1298  * @region_size: region size
1299  * @bar_size: size of the BAR
1300  * @offset_in_bar: region offset into the bar
1301  * @bar_id: bar ID of the region
1302  * @used: if used 1, otherwise 0
1303  */
1304 struct pci_mem_region {
1305 	u64 region_base;
1306 	u64 region_size;
1307 	u64 bar_size;
1308 	u64 offset_in_bar;
1309 	u8 bar_id;
1310 	u8 used;
1311 };
1312 
1313 /**
1314  * struct static_fw_load_mgr - static FW load manager
1315  * @preboot_version_max_off: max offset to preboot version
1316  * @boot_fit_version_max_off: max offset to boot fit version
1317  * @kmd_msg_to_cpu_reg: register address for KDM->CPU messages
1318  * @cpu_cmd_status_to_host_reg: register address for CPU command status response
1319  * @cpu_boot_status_reg: boot status register
1320  * @cpu_boot_dev_status0_reg: boot device status register 0
1321  * @cpu_boot_dev_status1_reg: boot device status register 1
1322  * @boot_err0_reg: boot error register 0
1323  * @boot_err1_reg: boot error register 1
1324  * @preboot_version_offset_reg: SRAM offset to preboot version register
1325  * @boot_fit_version_offset_reg: SRAM offset to boot fit version register
1326  * @sram_offset_mask: mask for getting offset into the SRAM
1327  * @cpu_reset_wait_msec: used when setting WFE via kmd_msg_to_cpu_reg
1328  */
1329 struct static_fw_load_mgr {
1330 	u64 preboot_version_max_off;
1331 	u64 boot_fit_version_max_off;
1332 	u32 kmd_msg_to_cpu_reg;
1333 	u32 cpu_cmd_status_to_host_reg;
1334 	u32 cpu_boot_status_reg;
1335 	u32 cpu_boot_dev_status0_reg;
1336 	u32 cpu_boot_dev_status1_reg;
1337 	u32 boot_err0_reg;
1338 	u32 boot_err1_reg;
1339 	u32 preboot_version_offset_reg;
1340 	u32 boot_fit_version_offset_reg;
1341 	u32 sram_offset_mask;
1342 	u32 cpu_reset_wait_msec;
1343 };
1344 
1345 /**
1346  * struct fw_response - FW response to LKD command
1347  * @ram_offset: descriptor offset into the RAM
1348  * @ram_type: RAM type containing the descriptor (SRAM/DRAM)
1349  * @status: command status
1350  */
1351 struct fw_response {
1352 	u32 ram_offset;
1353 	u8 ram_type;
1354 	u8 status;
1355 };
1356 
1357 /**
1358  * struct dynamic_fw_load_mgr - dynamic FW load manager
1359  * @response: FW to LKD response
1360  * @comm_desc: the communication descriptor with FW
1361  * @image_region: region to copy the FW image to
1362  * @fw_image_size: size of FW image to load
1363  * @wait_for_bl_timeout: timeout for waiting for boot loader to respond
1364  * @fw_desc_valid: true if FW descriptor has been validated and hence the data can be used
1365  */
1366 struct dynamic_fw_load_mgr {
1367 	struct fw_response response;
1368 	struct lkd_fw_comms_desc comm_desc;
1369 	struct pci_mem_region *image_region;
1370 	size_t fw_image_size;
1371 	u32 wait_for_bl_timeout;
1372 	bool fw_desc_valid;
1373 };
1374 
1375 /**
1376  * struct pre_fw_load_props - needed properties for pre-FW load
1377  * @cpu_boot_status_reg: cpu_boot_status register address
1378  * @sts_boot_dev_sts0_reg: sts_boot_dev_sts0 register address
1379  * @sts_boot_dev_sts1_reg: sts_boot_dev_sts1 register address
1380  * @boot_err0_reg: boot_err0 register address
1381  * @boot_err1_reg: boot_err1 register address
1382  * @wait_for_preboot_timeout: timeout to poll for preboot ready
1383  */
1384 struct pre_fw_load_props {
1385 	u32 cpu_boot_status_reg;
1386 	u32 sts_boot_dev_sts0_reg;
1387 	u32 sts_boot_dev_sts1_reg;
1388 	u32 boot_err0_reg;
1389 	u32 boot_err1_reg;
1390 	u32 wait_for_preboot_timeout;
1391 };
1392 
1393 /**
1394  * struct fw_image_props - properties of FW image
1395  * @image_name: name of the image
1396  * @src_off: offset in src FW to copy from
1397  * @copy_size: amount of bytes to copy (0 to copy the whole binary)
1398  */
1399 struct fw_image_props {
1400 	char *image_name;
1401 	u32 src_off;
1402 	u32 copy_size;
1403 };
1404 
1405 /**
1406  * struct fw_load_mgr - manager FW loading process
1407  * @dynamic_loader: specific structure for dynamic load
1408  * @static_loader: specific structure for static load
1409  * @pre_fw_load_props: parameter for pre FW load
1410  * @boot_fit_img: boot fit image properties
1411  * @linux_img: linux image properties
1412  * @cpu_timeout: CPU response timeout in usec
1413  * @boot_fit_timeout: Boot fit load timeout in usec
1414  * @skip_bmc: should BMC be skipped
1415  * @sram_bar_id: SRAM bar ID
1416  * @dram_bar_id: DRAM bar ID
1417  * @fw_comp_loaded: bitmask of loaded FW components. set bit meaning loaded
1418  *                  component. values are set according to enum hl_fw_types.
1419  */
1420 struct fw_load_mgr {
1421 	union {
1422 		struct dynamic_fw_load_mgr dynamic_loader;
1423 		struct static_fw_load_mgr static_loader;
1424 	};
1425 	struct pre_fw_load_props pre_fw_load;
1426 	struct fw_image_props boot_fit_img;
1427 	struct fw_image_props linux_img;
1428 	u32 cpu_timeout;
1429 	u32 boot_fit_timeout;
1430 	u8 skip_bmc;
1431 	u8 sram_bar_id;
1432 	u8 dram_bar_id;
1433 	u8 fw_comp_loaded;
1434 };
1435 
1436 struct hl_cs;
1437 
1438 /**
1439  * struct engines_data - asic engines data
1440  * @buf: buffer for engines data in ascii
1441  * @actual_size: actual size of data that was written by the driver to the allocated buffer
1442  * @allocated_buf_size: total size of allocated buffer
1443  */
1444 struct engines_data {
1445 	char *buf;
1446 	int actual_size;
1447 	u32 allocated_buf_size;
1448 };
1449 
1450 /**
1451  * struct hl_asic_funcs - ASIC specific functions that are can be called from
1452  *                        common code.
1453  * @early_init: sets up early driver state (pre sw_init), doesn't configure H/W.
1454  * @early_fini: tears down what was done in early_init.
1455  * @late_init: sets up late driver/hw state (post hw_init) - Optional.
1456  * @late_fini: tears down what was done in late_init (pre hw_fini) - Optional.
1457  * @sw_init: sets up driver state, does not configure H/W.
1458  * @sw_fini: tears down driver state, does not configure H/W.
1459  * @hw_init: sets up the H/W state.
1460  * @hw_fini: tears down the H/W state.
1461  * @halt_engines: halt engines, needed for reset sequence. This also disables
1462  *                interrupts from the device. Should be called before
1463  *                hw_fini and before CS rollback.
1464  * @suspend: handles IP specific H/W or SW changes for suspend.
1465  * @resume: handles IP specific H/W or SW changes for resume.
1466  * @mmap: maps a memory.
1467  * @ring_doorbell: increment PI on a given QMAN.
1468  * @pqe_write: Write the PQ entry to the PQ. This is ASIC-specific
1469  *             function because the PQs are located in different memory areas
1470  *             per ASIC (SRAM, DRAM, Host memory) and therefore, the method of
1471  *             writing the PQE must match the destination memory area
1472  *             properties.
1473  * @asic_dma_alloc_coherent: Allocate coherent DMA memory by calling
1474  *                           dma_alloc_coherent(). This is ASIC function because
1475  *                           its implementation is not trivial when the driver
1476  *                           is loaded in simulation mode (not upstreamed).
1477  * @asic_dma_free_coherent:  Free coherent DMA memory by calling
1478  *                           dma_free_coherent(). This is ASIC function because
1479  *                           its implementation is not trivial when the driver
1480  *                           is loaded in simulation mode (not upstreamed).
1481  * @scrub_device_mem: Scrub the entire SRAM and DRAM.
1482  * @scrub_device_dram: Scrub the dram memory of the device.
1483  * @get_int_queue_base: get the internal queue base address.
1484  * @test_queues: run simple test on all queues for sanity check.
1485  * @asic_dma_pool_zalloc: small DMA allocation of coherent memory from DMA pool.
1486  *                        size of allocation is HL_DMA_POOL_BLK_SIZE.
1487  * @asic_dma_pool_free: free small DMA allocation from pool.
1488  * @cpu_accessible_dma_pool_alloc: allocate CPU PQ packet from DMA pool.
1489  * @cpu_accessible_dma_pool_free: free CPU PQ packet from DMA pool.
1490  * @asic_dma_unmap_single: unmap a single DMA buffer
1491  * @asic_dma_map_single: map a single buffer to a DMA
1492  * @hl_dma_unmap_sgtable: DMA unmap scatter-gather table.
1493  * @cs_parser: parse Command Submission.
1494  * @asic_dma_map_sgtable: DMA map scatter-gather table.
1495  * @add_end_of_cb_packets: Add packets to the end of CB, if device requires it.
1496  * @update_eq_ci: update event queue CI.
1497  * @context_switch: called upon ASID context switch.
1498  * @restore_phase_topology: clear all SOBs amd MONs.
1499  * @debugfs_read_dma: debug interface for reading up to 2MB from the device's
1500  *                    internal memory via DMA engine.
1501  * @add_device_attr: add ASIC specific device attributes.
1502  * @handle_eqe: handle event queue entry (IRQ) from CPU-CP.
1503  * @get_events_stat: retrieve event queue entries histogram.
1504  * @read_pte: read MMU page table entry from DRAM.
1505  * @write_pte: write MMU page table entry to DRAM.
1506  * @mmu_invalidate_cache: flush MMU STLB host/DRAM cache, either with soft
1507  *                        (L1 only) or hard (L0 & L1) flush.
1508  * @mmu_invalidate_cache_range: flush specific MMU STLB cache lines with ASID-VA-size mask.
1509  * @mmu_prefetch_cache_range: pre-fetch specific MMU STLB cache lines with ASID-VA-size mask.
1510  * @send_heartbeat: send is-alive packet to CPU-CP and verify response.
1511  * @debug_coresight: perform certain actions on Coresight for debugging.
1512  * @is_device_idle: return true if device is idle, false otherwise.
1513  * @compute_reset_late_init: perform certain actions needed after a compute reset
1514  * @hw_queues_lock: acquire H/W queues lock.
1515  * @hw_queues_unlock: release H/W queues lock.
1516  * @get_pci_id: retrieve PCI ID.
1517  * @get_eeprom_data: retrieve EEPROM data from F/W.
1518  * @get_monitor_dump: retrieve monitor registers dump from F/W.
1519  * @send_cpu_message: send message to F/W. If the message is timedout, the
1520  *                    driver will eventually reset the device. The timeout can
1521  *                    be determined by the calling function or it can be 0 and
1522  *                    then the timeout is the default timeout for the specific
1523  *                    ASIC
1524  * @get_hw_state: retrieve the H/W state
1525  * @pci_bars_map: Map PCI BARs.
1526  * @init_iatu: Initialize the iATU unit inside the PCI controller.
1527  * @rreg: Read a register. Needed for simulator support.
1528  * @wreg: Write a register. Needed for simulator support.
1529  * @halt_coresight: stop the ETF and ETR traces.
1530  * @ctx_init: context dependent initialization.
1531  * @ctx_fini: context dependent cleanup.
1532  * @pre_schedule_cs: Perform pre-CS-scheduling operations.
1533  * @get_queue_id_for_cq: Get the H/W queue id related to the given CQ index.
1534  * @load_firmware_to_device: load the firmware to the device's memory
1535  * @load_boot_fit_to_device: load boot fit to device's memory
1536  * @get_signal_cb_size: Get signal CB size.
1537  * @get_wait_cb_size: Get wait CB size.
1538  * @gen_signal_cb: Generate a signal CB.
1539  * @gen_wait_cb: Generate a wait CB.
1540  * @reset_sob: Reset a SOB.
1541  * @reset_sob_group: Reset SOB group
1542  * @get_device_time: Get the device time.
1543  * @pb_print_security_errors: print security errors according block and cause
1544  * @collective_wait_init_cs: Generate collective master/slave packets
1545  *                           and place them in the relevant cs jobs
1546  * @collective_wait_create_jobs: allocate collective wait cs jobs
1547  * @get_dec_base_addr: get the base address of a given decoder.
1548  * @scramble_addr: Routine to scramble the address prior of mapping it
1549  *                 in the MMU.
1550  * @descramble_addr: Routine to de-scramble the address prior of
1551  *                   showing it to users.
1552  * @ack_protection_bits_errors: ack and dump all security violations
1553  * @get_hw_block_id: retrieve a HW block id to be used by the user to mmap it.
1554  *                   also returns the size of the block if caller supplies
1555  *                   a valid pointer for it
1556  * @hw_block_mmap: mmap a HW block with a given id.
1557  * @enable_events_from_fw: send interrupt to firmware to notify them the
1558  *                         driver is ready to receive asynchronous events. This
1559  *                         function should be called during the first init and
1560  *                         after every hard-reset of the device
1561  * @ack_mmu_errors: check and ack mmu errors, page fault, access violation.
1562  * @get_msi_info: Retrieve asic-specific MSI ID of the f/w async event
1563  * @map_pll_idx_to_fw_idx: convert driver specific per asic PLL index to
1564  *                         generic f/w compatible PLL Indexes
1565  * @init_firmware_preload_params: initialize pre FW-load parameters.
1566  * @init_firmware_loader: initialize data for FW loader.
1567  * @init_cpu_scrambler_dram: Enable CPU specific DRAM scrambling
1568  * @state_dump_init: initialize constants required for state dump
1569  * @get_sob_addr: get SOB base address offset.
1570  * @set_pci_memory_regions: setting properties of PCI memory regions
1571  * @get_stream_master_qid_arr: get pointer to stream masters QID array
1572  * @check_if_razwi_happened: check if there was a razwi due to RR violation.
1573  * @access_dev_mem: access device memory
1574  * @set_dram_bar_base: set the base of the DRAM BAR
1575  * @set_engine_cores: set a config command to engine cores
1576  * @set_engines: set a config command to user engines
1577  * @send_device_activity: indication to FW about device availability
1578  * @set_dram_properties: set DRAM related properties.
1579  * @set_binning_masks: set binning/enable masks for all relevant components.
1580  */
1581 struct hl_asic_funcs {
1582 	int (*early_init)(struct hl_device *hdev);
1583 	int (*early_fini)(struct hl_device *hdev);
1584 	int (*late_init)(struct hl_device *hdev);
1585 	void (*late_fini)(struct hl_device *hdev);
1586 	int (*sw_init)(struct hl_device *hdev);
1587 	int (*sw_fini)(struct hl_device *hdev);
1588 	int (*hw_init)(struct hl_device *hdev);
1589 	int (*hw_fini)(struct hl_device *hdev, bool hard_reset, bool fw_reset);
1590 	void (*halt_engines)(struct hl_device *hdev, bool hard_reset, bool fw_reset);
1591 	int (*suspend)(struct hl_device *hdev);
1592 	int (*resume)(struct hl_device *hdev);
1593 	int (*mmap)(struct hl_device *hdev, struct vm_area_struct *vma,
1594 			void *cpu_addr, dma_addr_t dma_addr, size_t size);
1595 	void (*ring_doorbell)(struct hl_device *hdev, u32 hw_queue_id, u32 pi);
1596 	void (*pqe_write)(struct hl_device *hdev, __le64 *pqe,
1597 			struct hl_bd *bd);
1598 	void* (*asic_dma_alloc_coherent)(struct hl_device *hdev, size_t size,
1599 					dma_addr_t *dma_handle, gfp_t flag);
1600 	void (*asic_dma_free_coherent)(struct hl_device *hdev, size_t size,
1601 					void *cpu_addr, dma_addr_t dma_handle);
1602 	int (*scrub_device_mem)(struct hl_device *hdev);
1603 	int (*scrub_device_dram)(struct hl_device *hdev, u64 val);
1604 	void* (*get_int_queue_base)(struct hl_device *hdev, u32 queue_id,
1605 				dma_addr_t *dma_handle, u16 *queue_len);
1606 	int (*test_queues)(struct hl_device *hdev);
1607 	void* (*asic_dma_pool_zalloc)(struct hl_device *hdev, size_t size,
1608 				gfp_t mem_flags, dma_addr_t *dma_handle);
1609 	void (*asic_dma_pool_free)(struct hl_device *hdev, void *vaddr,
1610 				dma_addr_t dma_addr);
1611 	void* (*cpu_accessible_dma_pool_alloc)(struct hl_device *hdev,
1612 				size_t size, dma_addr_t *dma_handle);
1613 	void (*cpu_accessible_dma_pool_free)(struct hl_device *hdev,
1614 				size_t size, void *vaddr);
1615 	void (*asic_dma_unmap_single)(struct hl_device *hdev,
1616 				dma_addr_t dma_addr, int len,
1617 				enum dma_data_direction dir);
1618 	dma_addr_t (*asic_dma_map_single)(struct hl_device *hdev,
1619 				void *addr, int len,
1620 				enum dma_data_direction dir);
1621 	void (*hl_dma_unmap_sgtable)(struct hl_device *hdev,
1622 				struct sg_table *sgt,
1623 				enum dma_data_direction dir);
1624 	int (*cs_parser)(struct hl_device *hdev, struct hl_cs_parser *parser);
1625 	int (*asic_dma_map_sgtable)(struct hl_device *hdev, struct sg_table *sgt,
1626 				enum dma_data_direction dir);
1627 	void (*add_end_of_cb_packets)(struct hl_device *hdev,
1628 					void *kernel_address, u32 len,
1629 					u32 original_len,
1630 					u64 cq_addr, u32 cq_val, u32 msix_num,
1631 					bool eb);
1632 	void (*update_eq_ci)(struct hl_device *hdev, u32 val);
1633 	int (*context_switch)(struct hl_device *hdev, u32 asid);
1634 	void (*restore_phase_topology)(struct hl_device *hdev);
1635 	int (*debugfs_read_dma)(struct hl_device *hdev, u64 addr, u32 size,
1636 				void *blob_addr);
1637 	void (*add_device_attr)(struct hl_device *hdev, struct attribute_group *dev_clk_attr_grp,
1638 				struct attribute_group *dev_vrm_attr_grp);
1639 	void (*handle_eqe)(struct hl_device *hdev,
1640 				struct hl_eq_entry *eq_entry);
1641 	void* (*get_events_stat)(struct hl_device *hdev, bool aggregate,
1642 				u32 *size);
1643 	u64 (*read_pte)(struct hl_device *hdev, u64 addr);
1644 	void (*write_pte)(struct hl_device *hdev, u64 addr, u64 val);
1645 	int (*mmu_invalidate_cache)(struct hl_device *hdev, bool is_hard,
1646 					u32 flags);
1647 	int (*mmu_invalidate_cache_range)(struct hl_device *hdev, bool is_hard,
1648 				u32 flags, u32 asid, u64 va, u64 size);
1649 	int (*mmu_prefetch_cache_range)(struct hl_ctx *ctx, u32 flags, u32 asid, u64 va, u64 size);
1650 	int (*send_heartbeat)(struct hl_device *hdev);
1651 	int (*debug_coresight)(struct hl_device *hdev, struct hl_ctx *ctx, void *data);
1652 	bool (*is_device_idle)(struct hl_device *hdev, u64 *mask_arr, u8 mask_len,
1653 				struct engines_data *e);
1654 	int (*compute_reset_late_init)(struct hl_device *hdev);
1655 	void (*hw_queues_lock)(struct hl_device *hdev);
1656 	void (*hw_queues_unlock)(struct hl_device *hdev);
1657 	u32 (*get_pci_id)(struct hl_device *hdev);
1658 	int (*get_eeprom_data)(struct hl_device *hdev, void *data, size_t max_size);
1659 	int (*get_monitor_dump)(struct hl_device *hdev, void *data);
1660 	int (*send_cpu_message)(struct hl_device *hdev, u32 *msg,
1661 				u16 len, u32 timeout, u64 *result);
1662 	int (*pci_bars_map)(struct hl_device *hdev);
1663 	int (*init_iatu)(struct hl_device *hdev);
1664 	u32 (*rreg)(struct hl_device *hdev, u32 reg);
1665 	void (*wreg)(struct hl_device *hdev, u32 reg, u32 val);
1666 	void (*halt_coresight)(struct hl_device *hdev, struct hl_ctx *ctx);
1667 	int (*ctx_init)(struct hl_ctx *ctx);
1668 	void (*ctx_fini)(struct hl_ctx *ctx);
1669 	int (*pre_schedule_cs)(struct hl_cs *cs);
1670 	u32 (*get_queue_id_for_cq)(struct hl_device *hdev, u32 cq_idx);
1671 	int (*load_firmware_to_device)(struct hl_device *hdev);
1672 	int (*load_boot_fit_to_device)(struct hl_device *hdev);
1673 	u32 (*get_signal_cb_size)(struct hl_device *hdev);
1674 	u32 (*get_wait_cb_size)(struct hl_device *hdev);
1675 	u32 (*gen_signal_cb)(struct hl_device *hdev, void *data, u16 sob_id,
1676 			u32 size, bool eb);
1677 	u32 (*gen_wait_cb)(struct hl_device *hdev,
1678 			struct hl_gen_wait_properties *prop);
1679 	void (*reset_sob)(struct hl_device *hdev, void *data);
1680 	void (*reset_sob_group)(struct hl_device *hdev, u16 sob_group);
1681 	u64 (*get_device_time)(struct hl_device *hdev);
1682 	void (*pb_print_security_errors)(struct hl_device *hdev,
1683 			u32 block_addr, u32 cause, u32 offended_addr);
1684 	int (*collective_wait_init_cs)(struct hl_cs *cs);
1685 	int (*collective_wait_create_jobs)(struct hl_device *hdev,
1686 			struct hl_ctx *ctx, struct hl_cs *cs,
1687 			u32 wait_queue_id, u32 collective_engine_id,
1688 			u32 encaps_signal_offset);
1689 	u32 (*get_dec_base_addr)(struct hl_device *hdev, u32 core_id);
1690 	u64 (*scramble_addr)(struct hl_device *hdev, u64 addr);
1691 	u64 (*descramble_addr)(struct hl_device *hdev, u64 addr);
1692 	void (*ack_protection_bits_errors)(struct hl_device *hdev);
1693 	int (*get_hw_block_id)(struct hl_device *hdev, u64 block_addr,
1694 				u32 *block_size, u32 *block_id);
1695 	int (*hw_block_mmap)(struct hl_device *hdev, struct vm_area_struct *vma,
1696 			u32 block_id, u32 block_size);
1697 	void (*enable_events_from_fw)(struct hl_device *hdev);
1698 	int (*ack_mmu_errors)(struct hl_device *hdev, u64 mmu_cap_mask);
1699 	void (*get_msi_info)(__le32 *table);
1700 	int (*map_pll_idx_to_fw_idx)(u32 pll_idx);
1701 	void (*init_firmware_preload_params)(struct hl_device *hdev);
1702 	void (*init_firmware_loader)(struct hl_device *hdev);
1703 	void (*init_cpu_scrambler_dram)(struct hl_device *hdev);
1704 	void (*state_dump_init)(struct hl_device *hdev);
1705 	u32 (*get_sob_addr)(struct hl_device *hdev, u32 sob_id);
1706 	void (*set_pci_memory_regions)(struct hl_device *hdev);
1707 	u32* (*get_stream_master_qid_arr)(void);
1708 	void (*check_if_razwi_happened)(struct hl_device *hdev);
1709 	int (*mmu_get_real_page_size)(struct hl_device *hdev, struct hl_mmu_properties *mmu_prop,
1710 					u32 page_size, u32 *real_page_size, bool is_dram_addr);
1711 	int (*access_dev_mem)(struct hl_device *hdev, enum pci_region region_type,
1712 				u64 addr, u64 *val, enum debugfs_access_type acc_type);
1713 	u64 (*set_dram_bar_base)(struct hl_device *hdev, u64 addr);
1714 	int (*set_engine_cores)(struct hl_device *hdev, u32 *core_ids,
1715 					u32 num_cores, u32 core_command);
1716 	int (*set_engines)(struct hl_device *hdev, u32 *engine_ids,
1717 					u32 num_engines, u32 engine_command);
1718 	int (*send_device_activity)(struct hl_device *hdev, bool open);
1719 	int (*set_dram_properties)(struct hl_device *hdev);
1720 	int (*set_binning_masks)(struct hl_device *hdev);
1721 };
1722 
1723 
1724 /*
1725  * CONTEXTS
1726  */
1727 
1728 #define HL_KERNEL_ASID_ID	0
1729 
1730 /**
1731  * enum hl_va_range_type - virtual address range type.
1732  * @HL_VA_RANGE_TYPE_HOST: range type of host pages
1733  * @HL_VA_RANGE_TYPE_HOST_HUGE: range type of host huge pages
1734  * @HL_VA_RANGE_TYPE_DRAM: range type of dram pages
1735  */
1736 enum hl_va_range_type {
1737 	HL_VA_RANGE_TYPE_HOST,
1738 	HL_VA_RANGE_TYPE_HOST_HUGE,
1739 	HL_VA_RANGE_TYPE_DRAM,
1740 	HL_VA_RANGE_TYPE_MAX
1741 };
1742 
1743 /**
1744  * struct hl_va_range - virtual addresses range.
1745  * @lock: protects the virtual addresses list.
1746  * @list: list of virtual addresses blocks available for mappings.
1747  * @start_addr: range start address.
1748  * @end_addr: range end address.
1749  * @page_size: page size of this va range.
1750  */
1751 struct hl_va_range {
1752 	struct mutex		lock;
1753 	struct list_head	list;
1754 	u64			start_addr;
1755 	u64			end_addr;
1756 	u32			page_size;
1757 };
1758 
1759 /**
1760  * struct hl_cs_counters_atomic - command submission counters
1761  * @out_of_mem_drop_cnt: dropped due to memory allocation issue
1762  * @parsing_drop_cnt: dropped due to error in packet parsing
1763  * @queue_full_drop_cnt: dropped due to queue full
1764  * @device_in_reset_drop_cnt: dropped due to device in reset
1765  * @max_cs_in_flight_drop_cnt: dropped due to maximum CS in-flight
1766  * @validation_drop_cnt: dropped due to error in validation
1767  */
1768 struct hl_cs_counters_atomic {
1769 	atomic64_t out_of_mem_drop_cnt;
1770 	atomic64_t parsing_drop_cnt;
1771 	atomic64_t queue_full_drop_cnt;
1772 	atomic64_t device_in_reset_drop_cnt;
1773 	atomic64_t max_cs_in_flight_drop_cnt;
1774 	atomic64_t validation_drop_cnt;
1775 };
1776 
1777 /**
1778  * struct hl_dmabuf_priv - a dma-buf private object.
1779  * @dmabuf: pointer to dma-buf object.
1780  * @ctx: pointer to the dma-buf owner's context.
1781  * @phys_pg_pack: pointer to physical page pack if the dma-buf was exported
1782  *                where virtual memory is supported.
1783  * @memhash_hnode: pointer to the memhash node. this object holds the export count.
1784  * @device_address: physical address of the device's memory. Relevant only
1785  *                  if phys_pg_pack is NULL (dma-buf was exported from address).
1786  *                  The total size can be taken from the dmabuf object.
1787  */
1788 struct hl_dmabuf_priv {
1789 	struct dma_buf			*dmabuf;
1790 	struct hl_ctx			*ctx;
1791 	struct hl_vm_phys_pg_pack	*phys_pg_pack;
1792 	struct hl_vm_hash_node		*memhash_hnode;
1793 	uint64_t			device_address;
1794 };
1795 
1796 #define HL_CS_OUTCOME_HISTORY_LEN 256
1797 
1798 /**
1799  * struct hl_cs_outcome - represents a single completed CS outcome
1800  * @list_link: link to either container's used list or free list
1801  * @map_link: list to the container hash map
1802  * @ts: completion ts
1803  * @seq: the original cs sequence
1804  * @error: error code cs completed with, if any
1805  */
1806 struct hl_cs_outcome {
1807 	struct list_head list_link;
1808 	struct hlist_node map_link;
1809 	ktime_t ts;
1810 	u64 seq;
1811 	int error;
1812 };
1813 
1814 /**
1815  * struct hl_cs_outcome_store - represents a limited store of completed CS outcomes
1816  * @outcome_map: index of completed CS searchable by sequence number
1817  * @used_list: list of outcome objects currently in use
1818  * @free_list: list of outcome objects currently not in use
1819  * @nodes_pool: a static pool of pre-allocated outcome objects
1820  * @db_lock: any operation on the store must take this lock
1821  */
1822 struct hl_cs_outcome_store {
1823 	DECLARE_HASHTABLE(outcome_map, 8);
1824 	struct list_head used_list;
1825 	struct list_head free_list;
1826 	struct hl_cs_outcome nodes_pool[HL_CS_OUTCOME_HISTORY_LEN];
1827 	spinlock_t db_lock;
1828 };
1829 
1830 /**
1831  * struct hl_ctx - user/kernel context.
1832  * @mem_hash: holds mapping from virtual address to virtual memory area
1833  *		descriptor (hl_vm_phys_pg_list or hl_userptr).
1834  * @mmu_shadow_hash: holds a mapping from shadow address to pgt_info structure.
1835  * @hr_mmu_phys_hash: if host-resident MMU is used, holds a mapping from
1836  *                    MMU-hop-page physical address to its host-resident
1837  *                    pgt_info structure.
1838  * @hpriv: pointer to the private (Kernel Driver) data of the process (fd).
1839  * @hdev: pointer to the device structure.
1840  * @refcount: reference counter for the context. Context is released only when
1841  *		this hits 0. It is incremented on CS and CS_WAIT.
1842  * @cs_pending: array of hl fence objects representing pending CS.
1843  * @outcome_store: storage data structure used to remember outcomes of completed
1844  *                 command submissions for a long time after CS id wraparound.
1845  * @va_range: holds available virtual addresses for host and dram mappings.
1846  * @mem_hash_lock: protects the mem_hash.
1847  * @hw_block_list_lock: protects the HW block memory list.
1848  * @debugfs_list: node in debugfs list of contexts.
1849  * @hw_block_mem_list: list of HW block virtual mapped addresses.
1850  * @cs_counters: context command submission counters.
1851  * @cb_va_pool: device VA pool for command buffers which are mapped to the
1852  *              device's MMU.
1853  * @sig_mgr: encaps signals handle manager.
1854  * @cb_va_pool_base: the base address for the device VA pool
1855  * @cs_sequence: sequence number for CS. Value is assigned to a CS and passed
1856  *			to user so user could inquire about CS. It is used as
1857  *			index to cs_pending array.
1858  * @dram_default_hops: array that holds all hops addresses needed for default
1859  *                     DRAM mapping.
1860  * @cs_lock: spinlock to protect cs_sequence.
1861  * @dram_phys_mem: amount of used physical DRAM memory by this context.
1862  * @thread_ctx_switch_token: token to prevent multiple threads of the same
1863  *				context	from running the context switch phase.
1864  *				Only a single thread should run it.
1865  * @thread_ctx_switch_wait_token: token to prevent the threads that didn't run
1866  *				the context switch phase from moving to their
1867  *				execution phase before the context switch phase
1868  *				has finished.
1869  * @asid: context's unique address space ID in the device's MMU.
1870  * @handle: context's opaque handle for user
1871  */
1872 struct hl_ctx {
1873 	DECLARE_HASHTABLE(mem_hash, MEM_HASH_TABLE_BITS);
1874 	DECLARE_HASHTABLE(mmu_shadow_hash, MMU_HASH_TABLE_BITS);
1875 	DECLARE_HASHTABLE(hr_mmu_phys_hash, MMU_HASH_TABLE_BITS);
1876 	struct hl_fpriv			*hpriv;
1877 	struct hl_device		*hdev;
1878 	struct kref			refcount;
1879 	struct hl_fence			**cs_pending;
1880 	struct hl_cs_outcome_store	outcome_store;
1881 	struct hl_va_range		*va_range[HL_VA_RANGE_TYPE_MAX];
1882 	struct mutex			mem_hash_lock;
1883 	struct mutex			hw_block_list_lock;
1884 	struct list_head		debugfs_list;
1885 	struct list_head		hw_block_mem_list;
1886 	struct hl_cs_counters_atomic	cs_counters;
1887 	struct gen_pool			*cb_va_pool;
1888 	struct hl_encaps_signals_mgr	sig_mgr;
1889 	u64				cb_va_pool_base;
1890 	u64				cs_sequence;
1891 	u64				*dram_default_hops;
1892 	spinlock_t			cs_lock;
1893 	atomic64_t			dram_phys_mem;
1894 	atomic_t			thread_ctx_switch_token;
1895 	u32				thread_ctx_switch_wait_token;
1896 	u32				asid;
1897 	u32				handle;
1898 };
1899 
1900 /**
1901  * struct hl_ctx_mgr - for handling multiple contexts.
1902  * @lock: protects ctx_handles.
1903  * @handles: idr to hold all ctx handles.
1904  */
1905 struct hl_ctx_mgr {
1906 	struct mutex	lock;
1907 	struct idr	handles;
1908 };
1909 
1910 
1911 /*
1912  * COMMAND SUBMISSIONS
1913  */
1914 
1915 /**
1916  * struct hl_userptr - memory mapping chunk information
1917  * @vm_type: type of the VM.
1918  * @job_node: linked-list node for hanging the object on the Job's list.
1919  * @pages: pointer to struct page array
1920  * @npages: size of @pages array
1921  * @sgt: pointer to the scatter-gather table that holds the pages.
1922  * @dir: for DMA unmapping, the direction must be supplied, so save it.
1923  * @debugfs_list: node in debugfs list of command submissions.
1924  * @pid: the pid of the user process owning the memory
1925  * @addr: user-space virtual address of the start of the memory area.
1926  * @size: size of the memory area to pin & map.
1927  * @dma_mapped: true if the SG was mapped to DMA addresses, false otherwise.
1928  */
1929 struct hl_userptr {
1930 	enum vm_type		vm_type; /* must be first */
1931 	struct list_head	job_node;
1932 	struct page		**pages;
1933 	unsigned int		npages;
1934 	struct sg_table		*sgt;
1935 	enum dma_data_direction dir;
1936 	struct list_head	debugfs_list;
1937 	pid_t			pid;
1938 	u64			addr;
1939 	u64			size;
1940 	u8			dma_mapped;
1941 };
1942 
1943 /**
1944  * struct hl_cs - command submission.
1945  * @jobs_in_queue_cnt: per each queue, maintain counter of submitted jobs.
1946  * @ctx: the context this CS belongs to.
1947  * @job_list: list of the CS's jobs in the various queues.
1948  * @job_lock: spinlock for the CS's jobs list. Needed for free_job.
1949  * @refcount: reference counter for usage of the CS.
1950  * @fence: pointer to the fence object of this CS.
1951  * @signal_fence: pointer to the fence object of the signal CS (used by wait
1952  *                CS only).
1953  * @finish_work: workqueue object to run when CS is completed by H/W.
1954  * @work_tdr: delayed work node for TDR.
1955  * @mirror_node : node in device mirror list of command submissions.
1956  * @staged_cs_node: node in the staged cs list.
1957  * @debugfs_list: node in debugfs list of command submissions.
1958  * @encaps_sig_hdl: holds the encaps signals handle.
1959  * @sequence: the sequence number of this CS.
1960  * @staged_sequence: the sequence of the staged submission this CS is part of,
1961  *                   relevant only if staged_cs is set.
1962  * @timeout_jiffies: cs timeout in jiffies.
1963  * @submission_time_jiffies: submission time of the cs
1964  * @type: CS_TYPE_*.
1965  * @jobs_cnt: counter of submitted jobs on all queues.
1966  * @encaps_sig_hdl_id: encaps signals handle id, set for the first staged cs.
1967  * @completion_timestamp: timestamp of the last completed cs job.
1968  * @sob_addr_offset: sob offset from the configuration base address.
1969  * @initial_sob_count: count of completed signals in SOB before current submission of signal or
1970  *                     cs with encaps signals.
1971  * @submitted: true if CS was submitted to H/W.
1972  * @completed: true if CS was completed by device.
1973  * @timedout : true if CS was timedout.
1974  * @tdr_active: true if TDR was activated for this CS (to prevent
1975  *		double TDR activation).
1976  * @aborted: true if CS was aborted due to some device error.
1977  * @timestamp: true if a timestamp must be captured upon completion.
1978  * @staged_last: true if this is the last staged CS and needs completion.
1979  * @staged_first: true if this is the first staged CS and we need to receive
1980  *                timeout for this CS.
1981  * @staged_cs: true if this CS is part of a staged submission.
1982  * @skip_reset_on_timeout: true if we shall not reset the device in case
1983  *                         timeout occurs (debug scenario).
1984  * @encaps_signals: true if this CS has encaps reserved signals.
1985  */
1986 struct hl_cs {
1987 	u16			*jobs_in_queue_cnt;
1988 	struct hl_ctx		*ctx;
1989 	struct list_head	job_list;
1990 	spinlock_t		job_lock;
1991 	struct kref		refcount;
1992 	struct hl_fence		*fence;
1993 	struct hl_fence		*signal_fence;
1994 	struct work_struct	finish_work;
1995 	struct delayed_work	work_tdr;
1996 	struct list_head	mirror_node;
1997 	struct list_head	staged_cs_node;
1998 	struct list_head	debugfs_list;
1999 	struct hl_cs_encaps_sig_handle *encaps_sig_hdl;
2000 	ktime_t			completion_timestamp;
2001 	u64			sequence;
2002 	u64			staged_sequence;
2003 	u64			timeout_jiffies;
2004 	u64			submission_time_jiffies;
2005 	enum hl_cs_type		type;
2006 	u32			jobs_cnt;
2007 	u32			encaps_sig_hdl_id;
2008 	u32			sob_addr_offset;
2009 	u16			initial_sob_count;
2010 	u8			submitted;
2011 	u8			completed;
2012 	u8			timedout;
2013 	u8			tdr_active;
2014 	u8			aborted;
2015 	u8			timestamp;
2016 	u8			staged_last;
2017 	u8			staged_first;
2018 	u8			staged_cs;
2019 	u8			skip_reset_on_timeout;
2020 	u8			encaps_signals;
2021 };
2022 
2023 /**
2024  * struct hl_cs_job - command submission job.
2025  * @cs_node: the node to hang on the CS jobs list.
2026  * @cs: the CS this job belongs to.
2027  * @user_cb: the CB we got from the user.
2028  * @patched_cb: in case of patching, this is internal CB which is submitted on
2029  *		the queue instead of the CB we got from the IOCTL.
2030  * @finish_work: workqueue object to run when job is completed.
2031  * @userptr_list: linked-list of userptr mappings that belong to this job and
2032  *			wait for completion.
2033  * @debugfs_list: node in debugfs list of command submission jobs.
2034  * @refcount: reference counter for usage of the CS job.
2035  * @queue_type: the type of the H/W queue this job is submitted to.
2036  * @timestamp: timestamp upon job completion
2037  * @id: the id of this job inside a CS.
2038  * @hw_queue_id: the id of the H/W queue this job is submitted to.
2039  * @user_cb_size: the actual size of the CB we got from the user.
2040  * @job_cb_size: the actual size of the CB that we put on the queue.
2041  * @encaps_sig_wait_offset: encapsulated signals offset, which allow user
2042  *                          to wait on part of the reserved signals.
2043  * @is_kernel_allocated_cb: true if the CB handle we got from the user holds a
2044  *                          handle to a kernel-allocated CB object, false
2045  *                          otherwise (SRAM/DRAM/host address).
2046  * @contains_dma_pkt: whether the JOB contains at least one DMA packet. This
2047  *                    info is needed later, when adding the 2xMSG_PROT at the
2048  *                    end of the JOB, to know which barriers to put in the
2049  *                    MSG_PROT packets. Relevant only for GAUDI as GOYA doesn't
2050  *                    have streams so the engine can't be busy by another
2051  *                    stream.
2052  */
2053 struct hl_cs_job {
2054 	struct list_head	cs_node;
2055 	struct hl_cs		*cs;
2056 	struct hl_cb		*user_cb;
2057 	struct hl_cb		*patched_cb;
2058 	struct work_struct	finish_work;
2059 	struct list_head	userptr_list;
2060 	struct list_head	debugfs_list;
2061 	struct kref		refcount;
2062 	enum hl_queue_type	queue_type;
2063 	ktime_t			timestamp;
2064 	u32			id;
2065 	u32			hw_queue_id;
2066 	u32			user_cb_size;
2067 	u32			job_cb_size;
2068 	u32			encaps_sig_wait_offset;
2069 	u8			is_kernel_allocated_cb;
2070 	u8			contains_dma_pkt;
2071 };
2072 
2073 /**
2074  * struct hl_cs_parser - command submission parser properties.
2075  * @user_cb: the CB we got from the user.
2076  * @patched_cb: in case of patching, this is internal CB which is submitted on
2077  *		the queue instead of the CB we got from the IOCTL.
2078  * @job_userptr_list: linked-list of userptr mappings that belong to the related
2079  *			job and wait for completion.
2080  * @cs_sequence: the sequence number of the related CS.
2081  * @queue_type: the type of the H/W queue this job is submitted to.
2082  * @ctx_id: the ID of the context the related CS belongs to.
2083  * @hw_queue_id: the id of the H/W queue this job is submitted to.
2084  * @user_cb_size: the actual size of the CB we got from the user.
2085  * @patched_cb_size: the size of the CB after parsing.
2086  * @job_id: the id of the related job inside the related CS.
2087  * @is_kernel_allocated_cb: true if the CB handle we got from the user holds a
2088  *                          handle to a kernel-allocated CB object, false
2089  *                          otherwise (SRAM/DRAM/host address).
2090  * @contains_dma_pkt: whether the JOB contains at least one DMA packet. This
2091  *                    info is needed later, when adding the 2xMSG_PROT at the
2092  *                    end of the JOB, to know which barriers to put in the
2093  *                    MSG_PROT packets. Relevant only for GAUDI as GOYA doesn't
2094  *                    have streams so the engine can't be busy by another
2095  *                    stream.
2096  * @completion: true if we need completion for this CS.
2097  */
2098 struct hl_cs_parser {
2099 	struct hl_cb		*user_cb;
2100 	struct hl_cb		*patched_cb;
2101 	struct list_head	*job_userptr_list;
2102 	u64			cs_sequence;
2103 	enum hl_queue_type	queue_type;
2104 	u32			ctx_id;
2105 	u32			hw_queue_id;
2106 	u32			user_cb_size;
2107 	u32			patched_cb_size;
2108 	u8			job_id;
2109 	u8			is_kernel_allocated_cb;
2110 	u8			contains_dma_pkt;
2111 	u8			completion;
2112 };
2113 
2114 /*
2115  * MEMORY STRUCTURE
2116  */
2117 
2118 /**
2119  * struct hl_vm_hash_node - hash element from virtual address to virtual
2120  *				memory area descriptor (hl_vm_phys_pg_list or
2121  *				hl_userptr).
2122  * @node: node to hang on the hash table in context object.
2123  * @vaddr: key virtual address.
2124  * @handle: memory handle for device memory allocation.
2125  * @ptr: value pointer (hl_vm_phys_pg_list or hl_userptr).
2126  * @export_cnt: number of exports from within the VA block.
2127  */
2128 struct hl_vm_hash_node {
2129 	struct hlist_node	node;
2130 	u64			vaddr;
2131 	u64			handle;
2132 	void			*ptr;
2133 	int			export_cnt;
2134 };
2135 
2136 /**
2137  * struct hl_vm_hw_block_list_node - list element from user virtual address to
2138  *				HW block id.
2139  * @node: node to hang on the list in context object.
2140  * @ctx: the context this node belongs to.
2141  * @vaddr: virtual address of the HW block.
2142  * @block_size: size of the block.
2143  * @mapped_size: size of the block which is mapped. May change if partial un-mappings are done.
2144  * @id: HW block id (handle).
2145  */
2146 struct hl_vm_hw_block_list_node {
2147 	struct list_head	node;
2148 	struct hl_ctx		*ctx;
2149 	unsigned long		vaddr;
2150 	u32			block_size;
2151 	u32			mapped_size;
2152 	u32			id;
2153 };
2154 
2155 /**
2156  * struct hl_vm_phys_pg_pack - physical page pack.
2157  * @vm_type: describes the type of the virtual area descriptor.
2158  * @pages: the physical page array.
2159  * @npages: num physical pages in the pack.
2160  * @total_size: total size of all the pages in this list.
2161  * @exported_size: buffer exported size.
2162  * @node: used to attach to deletion list that is used when all the allocations are cleared
2163  *        at the teardown of the context.
2164  * @mapping_cnt: number of shared mappings.
2165  * @asid: the context related to this list.
2166  * @page_size: size of each page in the pack.
2167  * @flags: HL_MEM_* flags related to this list.
2168  * @handle: the provided handle related to this list.
2169  * @offset: offset from the first page.
2170  * @contiguous: is contiguous physical memory.
2171  * @created_from_userptr: is product of host virtual address.
2172  */
2173 struct hl_vm_phys_pg_pack {
2174 	enum vm_type		vm_type; /* must be first */
2175 	u64			*pages;
2176 	u64			npages;
2177 	u64			total_size;
2178 	u64			exported_size;
2179 	struct list_head	node;
2180 	atomic_t		mapping_cnt;
2181 	u32			asid;
2182 	u32			page_size;
2183 	u32			flags;
2184 	u32			handle;
2185 	u32			offset;
2186 	u8			contiguous;
2187 	u8			created_from_userptr;
2188 };
2189 
2190 /**
2191  * struct hl_vm_va_block - virtual range block information.
2192  * @node: node to hang on the virtual range list in context object.
2193  * @start: virtual range start address.
2194  * @end: virtual range end address.
2195  * @size: virtual range size.
2196  */
2197 struct hl_vm_va_block {
2198 	struct list_head	node;
2199 	u64			start;
2200 	u64			end;
2201 	u64			size;
2202 };
2203 
2204 /**
2205  * struct hl_vm - virtual memory manager for MMU.
2206  * @dram_pg_pool: pool for DRAM physical pages of 2MB.
2207  * @dram_pg_pool_refcount: reference counter for the pool usage.
2208  * @idr_lock: protects the phys_pg_list_handles.
2209  * @phys_pg_pack_handles: idr to hold all device allocations handles.
2210  * @init_done: whether initialization was done. We need this because VM
2211  *		initialization might be skipped during device initialization.
2212  */
2213 struct hl_vm {
2214 	struct gen_pool		*dram_pg_pool;
2215 	struct kref		dram_pg_pool_refcount;
2216 	spinlock_t		idr_lock;
2217 	struct idr		phys_pg_pack_handles;
2218 	u8			init_done;
2219 };
2220 
2221 
2222 /*
2223  * DEBUG, PROFILING STRUCTURE
2224  */
2225 
2226 /**
2227  * struct hl_debug_params - Coresight debug parameters.
2228  * @input: pointer to component specific input parameters.
2229  * @output: pointer to component specific output parameters.
2230  * @output_size: size of output buffer.
2231  * @reg_idx: relevant register ID.
2232  * @op: component operation to execute.
2233  * @enable: true if to enable component debugging, false otherwise.
2234  */
2235 struct hl_debug_params {
2236 	void *input;
2237 	void *output;
2238 	u32 output_size;
2239 	u32 reg_idx;
2240 	u32 op;
2241 	bool enable;
2242 };
2243 
2244 /**
2245  * struct hl_notifier_event - holds the notifier data structure
2246  * @eventfd: the event file descriptor to raise the notifications
2247  * @lock: mutex lock to protect the notifier data flows
2248  * @events_mask: indicates the bitmap events
2249  */
2250 struct hl_notifier_event {
2251 	struct eventfd_ctx	*eventfd;
2252 	struct mutex		lock;
2253 	u64			events_mask;
2254 };
2255 
2256 /*
2257  * FILE PRIVATE STRUCTURE
2258  */
2259 
2260 /**
2261  * struct hl_fpriv - process information stored in FD private data.
2262  * @hdev: habanalabs device structure.
2263  * @filp: pointer to the given file structure.
2264  * @taskpid: current process ID.
2265  * @ctx: current executing context. TODO: remove for multiple ctx per process
2266  * @ctx_mgr: context manager to handle multiple context for this FD.
2267  * @mem_mgr: manager descriptor for memory exportable via mmap
2268  * @notifier_event: notifier eventfd towards user process
2269  * @debugfs_list: list of relevant ASIC debugfs.
2270  * @dev_node: node in the device list of file private data
2271  * @refcount: number of related contexts.
2272  * @restore_phase_mutex: lock for context switch and restore phase.
2273  * @ctx_lock: protects the pointer to current executing context pointer. TODO: remove for multiple
2274  *            ctx per process.
2275  */
2276 struct hl_fpriv {
2277 	struct hl_device		*hdev;
2278 	struct file			*filp;
2279 	struct pid			*taskpid;
2280 	struct hl_ctx			*ctx;
2281 	struct hl_ctx_mgr		ctx_mgr;
2282 	struct hl_mem_mgr		mem_mgr;
2283 	struct hl_notifier_event	notifier_event;
2284 	struct list_head		debugfs_list;
2285 	struct list_head		dev_node;
2286 	struct kref			refcount;
2287 	struct mutex			restore_phase_mutex;
2288 	struct mutex			ctx_lock;
2289 };
2290 
2291 
2292 /*
2293  * DebugFS
2294  */
2295 
2296 /**
2297  * struct hl_info_list - debugfs file ops.
2298  * @name: file name.
2299  * @show: function to output information.
2300  * @write: function to write to the file.
2301  */
2302 struct hl_info_list {
2303 	const char	*name;
2304 	int		(*show)(struct seq_file *s, void *data);
2305 	ssize_t		(*write)(struct file *file, const char __user *buf,
2306 				size_t count, loff_t *f_pos);
2307 };
2308 
2309 /**
2310  * struct hl_debugfs_entry - debugfs dentry wrapper.
2311  * @info_ent: dentry related ops.
2312  * @dev_entry: ASIC specific debugfs manager.
2313  */
2314 struct hl_debugfs_entry {
2315 	const struct hl_info_list	*info_ent;
2316 	struct hl_dbg_device_entry	*dev_entry;
2317 };
2318 
2319 /**
2320  * struct hl_dbg_device_entry - ASIC specific debugfs manager.
2321  * @root: root dentry.
2322  * @hdev: habanalabs device structure.
2323  * @entry_arr: array of available hl_debugfs_entry.
2324  * @file_list: list of available debugfs files.
2325  * @file_mutex: protects file_list.
2326  * @cb_list: list of available CBs.
2327  * @cb_spinlock: protects cb_list.
2328  * @cs_list: list of available CSs.
2329  * @cs_spinlock: protects cs_list.
2330  * @cs_job_list: list of available CB jobs.
2331  * @cs_job_spinlock: protects cs_job_list.
2332  * @userptr_list: list of available userptrs (virtual memory chunk descriptor).
2333  * @userptr_spinlock: protects userptr_list.
2334  * @ctx_mem_hash_list: list of available contexts with MMU mappings.
2335  * @ctx_mem_hash_mutex: protects list of available contexts with MMU mappings.
2336  * @data_dma_blob_desc: data DMA descriptor of blob.
2337  * @mon_dump_blob_desc: monitor dump descriptor of blob.
2338  * @state_dump: data of the system states in case of a bad cs.
2339  * @state_dump_sem: protects state_dump.
2340  * @addr: next address to read/write from/to in read/write32.
2341  * @mmu_addr: next virtual address to translate to physical address in mmu_show.
2342  * @mmu_cap_mask: mmu hw capability mask, to be used in mmu_ack_error.
2343  * @userptr_lookup: the target user ptr to look up for on demand.
2344  * @mmu_asid: ASID to use while translating in mmu_show.
2345  * @state_dump_head: index of the latest state dump
2346  * @i2c_bus: generic u8 debugfs file for bus value to use in i2c_data_read.
2347  * @i2c_addr: generic u8 debugfs file for address value to use in i2c_data_read.
2348  * @i2c_reg: generic u8 debugfs file for register value to use in i2c_data_read.
2349  * @i2c_len: generic u8 debugfs file for length value to use in i2c_data_read.
2350  */
2351 struct hl_dbg_device_entry {
2352 	struct dentry			*root;
2353 	struct hl_device		*hdev;
2354 	struct hl_debugfs_entry		*entry_arr;
2355 	struct list_head		file_list;
2356 	struct mutex			file_mutex;
2357 	struct list_head		cb_list;
2358 	spinlock_t			cb_spinlock;
2359 	struct list_head		cs_list;
2360 	spinlock_t			cs_spinlock;
2361 	struct list_head		cs_job_list;
2362 	spinlock_t			cs_job_spinlock;
2363 	struct list_head		userptr_list;
2364 	spinlock_t			userptr_spinlock;
2365 	struct list_head		ctx_mem_hash_list;
2366 	struct mutex			ctx_mem_hash_mutex;
2367 	struct debugfs_blob_wrapper	data_dma_blob_desc;
2368 	struct debugfs_blob_wrapper	mon_dump_blob_desc;
2369 	char				*state_dump[HL_STATE_DUMP_HIST_LEN];
2370 	struct rw_semaphore		state_dump_sem;
2371 	u64				addr;
2372 	u64				mmu_addr;
2373 	u64				mmu_cap_mask;
2374 	u64				userptr_lookup;
2375 	u32				mmu_asid;
2376 	u32				state_dump_head;
2377 	u8				i2c_bus;
2378 	u8				i2c_addr;
2379 	u8				i2c_reg;
2380 	u8				i2c_len;
2381 };
2382 
2383 /**
2384  * struct hl_hw_obj_name_entry - single hw object name, member of
2385  * hl_state_dump_specs
2386  * @node: link to the containing hash table
2387  * @name: hw object name
2388  * @id: object identifier
2389  */
2390 struct hl_hw_obj_name_entry {
2391 	struct hlist_node	node;
2392 	const char		*name;
2393 	u32			id;
2394 };
2395 
2396 enum hl_state_dump_specs_props {
2397 	SP_SYNC_OBJ_BASE_ADDR,
2398 	SP_NEXT_SYNC_OBJ_ADDR,
2399 	SP_SYNC_OBJ_AMOUNT,
2400 	SP_MON_OBJ_WR_ADDR_LOW,
2401 	SP_MON_OBJ_WR_ADDR_HIGH,
2402 	SP_MON_OBJ_WR_DATA,
2403 	SP_MON_OBJ_ARM_DATA,
2404 	SP_MON_OBJ_STATUS,
2405 	SP_MONITORS_AMOUNT,
2406 	SP_TPC0_CMDQ,
2407 	SP_TPC0_CFG_SO,
2408 	SP_NEXT_TPC,
2409 	SP_MME_CMDQ,
2410 	SP_MME_CFG_SO,
2411 	SP_NEXT_MME,
2412 	SP_DMA_CMDQ,
2413 	SP_DMA_CFG_SO,
2414 	SP_DMA_QUEUES_OFFSET,
2415 	SP_NUM_OF_MME_ENGINES,
2416 	SP_SUB_MME_ENG_NUM,
2417 	SP_NUM_OF_DMA_ENGINES,
2418 	SP_NUM_OF_TPC_ENGINES,
2419 	SP_ENGINE_NUM_OF_QUEUES,
2420 	SP_ENGINE_NUM_OF_STREAMS,
2421 	SP_ENGINE_NUM_OF_FENCES,
2422 	SP_FENCE0_CNT_OFFSET,
2423 	SP_FENCE0_RDATA_OFFSET,
2424 	SP_CP_STS_OFFSET,
2425 	SP_NUM_CORES,
2426 
2427 	SP_MAX
2428 };
2429 
2430 enum hl_sync_engine_type {
2431 	ENGINE_TPC,
2432 	ENGINE_DMA,
2433 	ENGINE_MME,
2434 };
2435 
2436 /**
2437  * struct hl_mon_state_dump - represents a state dump of a single monitor
2438  * @id: monitor id
2439  * @wr_addr_low: address monitor will write to, low bits
2440  * @wr_addr_high: address monitor will write to, high bits
2441  * @wr_data: data monitor will write
2442  * @arm_data: register value containing monitor configuration
2443  * @status: monitor status
2444  */
2445 struct hl_mon_state_dump {
2446 	u32		id;
2447 	u32		wr_addr_low;
2448 	u32		wr_addr_high;
2449 	u32		wr_data;
2450 	u32		arm_data;
2451 	u32		status;
2452 };
2453 
2454 /**
2455  * struct hl_sync_to_engine_map_entry - sync object id to engine mapping entry
2456  * @engine_type: type of the engine
2457  * @engine_id: id of the engine
2458  * @sync_id: id of the sync object
2459  */
2460 struct hl_sync_to_engine_map_entry {
2461 	struct hlist_node		node;
2462 	enum hl_sync_engine_type	engine_type;
2463 	u32				engine_id;
2464 	u32				sync_id;
2465 };
2466 
2467 /**
2468  * struct hl_sync_to_engine_map - maps sync object id to associated engine id
2469  * @tb: hash table containing the mapping, each element is of type
2470  *      struct hl_sync_to_engine_map_entry
2471  */
2472 struct hl_sync_to_engine_map {
2473 	DECLARE_HASHTABLE(tb, SYNC_TO_ENGINE_HASH_TABLE_BITS);
2474 };
2475 
2476 /**
2477  * struct hl_state_dump_specs_funcs - virtual functions used by the state dump
2478  * @gen_sync_to_engine_map: generate a hash map from sync obj id to its engine
2479  * @print_single_monitor: format monitor data as string
2480  * @monitor_valid: return true if given monitor dump is valid
2481  * @print_fences_single_engine: format fences data as string
2482  */
2483 struct hl_state_dump_specs_funcs {
2484 	int (*gen_sync_to_engine_map)(struct hl_device *hdev,
2485 				struct hl_sync_to_engine_map *map);
2486 	int (*print_single_monitor)(char **buf, size_t *size, size_t *offset,
2487 				    struct hl_device *hdev,
2488 				    struct hl_mon_state_dump *mon);
2489 	int (*monitor_valid)(struct hl_mon_state_dump *mon);
2490 	int (*print_fences_single_engine)(struct hl_device *hdev,
2491 					u64 base_offset,
2492 					u64 status_base_offset,
2493 					enum hl_sync_engine_type engine_type,
2494 					u32 engine_id, char **buf,
2495 					size_t *size, size_t *offset);
2496 };
2497 
2498 /**
2499  * struct hl_state_dump_specs - defines ASIC known hw objects names
2500  * @so_id_to_str_tb: sync objects names index table
2501  * @monitor_id_to_str_tb: monitors names index table
2502  * @funcs: virtual functions used for state dump
2503  * @sync_namager_names: readable names for sync manager if available (ex: N_E)
2504  * @props: pointer to a per asic const props array required for state dump
2505  */
2506 struct hl_state_dump_specs {
2507 	DECLARE_HASHTABLE(so_id_to_str_tb, OBJ_NAMES_HASH_TABLE_BITS);
2508 	DECLARE_HASHTABLE(monitor_id_to_str_tb, OBJ_NAMES_HASH_TABLE_BITS);
2509 	struct hl_state_dump_specs_funcs	funcs;
2510 	const char * const			*sync_namager_names;
2511 	s64					*props;
2512 };
2513 
2514 
2515 /*
2516  * DEVICES
2517  */
2518 
2519 #define HL_STR_MAX	32
2520 
2521 #define HL_DEV_STS_MAX (HL_DEVICE_STATUS_LAST + 1)
2522 
2523 /* Theoretical limit only. A single host can only contain up to 4 or 8 PCIe
2524  * x16 cards. In extreme cases, there are hosts that can accommodate 16 cards.
2525  */
2526 #define HL_MAX_MINORS	256
2527 
2528 /*
2529  * Registers read & write functions.
2530  */
2531 
2532 u32 hl_rreg(struct hl_device *hdev, u32 reg);
2533 void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
2534 
2535 #define RREG32(reg) hdev->asic_funcs->rreg(hdev, (reg))
2536 #define WREG32(reg, v) hdev->asic_funcs->wreg(hdev, (reg), (v))
2537 #define DREG32(reg) pr_info("REGISTER: " #reg " : 0x%08X\n",	\
2538 			hdev->asic_funcs->rreg(hdev, (reg)))
2539 
2540 #define WREG32_P(reg, val, mask)				\
2541 	do {							\
2542 		u32 tmp_ = RREG32(reg);				\
2543 		tmp_ &= (mask);					\
2544 		tmp_ |= ((val) & ~(mask));			\
2545 		WREG32(reg, tmp_);				\
2546 	} while (0)
2547 #define WREG32_AND(reg, and) WREG32_P(reg, 0, and)
2548 #define WREG32_OR(reg, or) WREG32_P(reg, or, ~(or))
2549 
2550 #define RMWREG32_SHIFTED(reg, val, mask) WREG32_P(reg, val, ~(mask))
2551 
2552 #define RMWREG32(reg, val, mask) RMWREG32_SHIFTED(reg, (val) << __ffs(mask), mask)
2553 
2554 #define RREG32_MASK(reg, mask) ((RREG32(reg) & mask) >> __ffs(mask))
2555 
2556 #define REG_FIELD_SHIFT(reg, field) reg##_##field##_SHIFT
2557 #define REG_FIELD_MASK(reg, field) reg##_##field##_MASK
2558 #define WREG32_FIELD(reg, offset, field, val)	\
2559 	WREG32(mm##reg + offset, (RREG32(mm##reg + offset) & \
2560 				~REG_FIELD_MASK(reg, field)) | \
2561 				(val) << REG_FIELD_SHIFT(reg, field))
2562 
2563 /* Timeout should be longer when working with simulator but cap the
2564  * increased timeout to some maximum
2565  */
2566 #define hl_poll_timeout_common(hdev, addr, val, cond, sleep_us, timeout_us, elbi) \
2567 ({ \
2568 	ktime_t __timeout; \
2569 	u32 __elbi_read; \
2570 	int __rc = 0; \
2571 	if (hdev->pdev) \
2572 		__timeout = ktime_add_us(ktime_get(), timeout_us); \
2573 	else \
2574 		__timeout = ktime_add_us(ktime_get(),\
2575 				min((u64)(timeout_us * 10), \
2576 					(u64) HL_SIM_MAX_TIMEOUT_US)); \
2577 	might_sleep_if(sleep_us); \
2578 	for (;;) { \
2579 		if (elbi) { \
2580 			__rc = hl_pci_elbi_read(hdev, addr, &__elbi_read); \
2581 			if (__rc) \
2582 				break; \
2583 			(val) = __elbi_read; \
2584 		} else {\
2585 			(val) = RREG32(lower_32_bits(addr)); \
2586 		} \
2587 		if (cond) \
2588 			break; \
2589 		if (timeout_us && ktime_compare(ktime_get(), __timeout) > 0) { \
2590 			if (elbi) { \
2591 				__rc = hl_pci_elbi_read(hdev, addr, &__elbi_read); \
2592 				if (__rc) \
2593 					break; \
2594 				(val) = __elbi_read; \
2595 			} else {\
2596 				(val) = RREG32(lower_32_bits(addr)); \
2597 			} \
2598 			break; \
2599 		} \
2600 		if (sleep_us) \
2601 			usleep_range((sleep_us >> 2) + 1, sleep_us); \
2602 	} \
2603 	__rc ? __rc : ((cond) ? 0 : -ETIMEDOUT); \
2604 })
2605 
2606 #define hl_poll_timeout(hdev, addr, val, cond, sleep_us, timeout_us) \
2607 		hl_poll_timeout_common(hdev, addr, val, cond, sleep_us, timeout_us, false)
2608 
2609 #define hl_poll_timeout_elbi(hdev, addr, val, cond, sleep_us, timeout_us) \
2610 		hl_poll_timeout_common(hdev, addr, val, cond, sleep_us, timeout_us, true)
2611 
2612 /*
2613  * poll array of register addresses.
2614  * condition is satisfied if all registers values match the expected value.
2615  * once some register in the array satisfies the condition it will not be polled again,
2616  * this is done both for efficiency and due to some registers are "clear on read".
2617  * TODO: use read from PCI bar in other places in the code (SW-91406)
2618  */
2619 #define hl_poll_reg_array_timeout_common(hdev, addr_arr, arr_size, expected_val, sleep_us, \
2620 						timeout_us, elbi) \
2621 ({ \
2622 	ktime_t __timeout; \
2623 	u64 __elem_bitmask; \
2624 	u32 __read_val;	\
2625 	u8 __arr_idx;	\
2626 	int __rc = 0; \
2627 	\
2628 	if (hdev->pdev) \
2629 		__timeout = ktime_add_us(ktime_get(), timeout_us); \
2630 	else \
2631 		__timeout = ktime_add_us(ktime_get(),\
2632 				min(((u64)timeout_us * 10), \
2633 					(u64) HL_SIM_MAX_TIMEOUT_US)); \
2634 	\
2635 	might_sleep_if(sleep_us); \
2636 	if (arr_size >= 64) \
2637 		__rc = -EINVAL; \
2638 	else \
2639 		__elem_bitmask = BIT_ULL(arr_size) - 1; \
2640 	for (;;) { \
2641 		if (__rc) \
2642 			break; \
2643 		for (__arr_idx = 0; __arr_idx < (arr_size); __arr_idx++) {	\
2644 			if (!(__elem_bitmask & BIT_ULL(__arr_idx)))	\
2645 				continue;	\
2646 			if (elbi) { \
2647 				__rc = hl_pci_elbi_read(hdev, (addr_arr)[__arr_idx], &__read_val); \
2648 				if (__rc) \
2649 					break; \
2650 			} else { \
2651 				__read_val = RREG32(lower_32_bits(addr_arr[__arr_idx])); \
2652 			} \
2653 			if (__read_val == (expected_val))	\
2654 				__elem_bitmask &= ~BIT_ULL(__arr_idx);	\
2655 		}	\
2656 		if (__rc || (__elem_bitmask == 0)) \
2657 			break; \
2658 		if (timeout_us && ktime_compare(ktime_get(), __timeout) > 0) \
2659 			break; \
2660 		if (sleep_us) \
2661 			usleep_range((sleep_us >> 2) + 1, sleep_us); \
2662 	} \
2663 	__rc ? __rc : ((__elem_bitmask == 0) ? 0 : -ETIMEDOUT); \
2664 })
2665 
2666 #define hl_poll_reg_array_timeout(hdev, addr_arr, arr_size, expected_val, sleep_us, \
2667 					timeout_us) \
2668 	hl_poll_reg_array_timeout_common(hdev, addr_arr, arr_size, expected_val, sleep_us, \
2669 						timeout_us, false)
2670 
2671 #define hl_poll_reg_array_timeout_elbi(hdev, addr_arr, arr_size, expected_val, sleep_us, \
2672 					timeout_us) \
2673 	hl_poll_reg_array_timeout_common(hdev, addr_arr, arr_size, expected_val, sleep_us, \
2674 						timeout_us, true)
2675 
2676 /*
2677  * address in this macro points always to a memory location in the
2678  * host's (server's) memory. That location is updated asynchronously
2679  * either by the direct access of the device or by another core.
2680  *
2681  * To work both in LE and BE architectures, we need to distinguish between the
2682  * two states (device or another core updates the memory location). Therefore,
2683  * if mem_written_by_device is true, the host memory being polled will be
2684  * updated directly by the device. If false, the host memory being polled will
2685  * be updated by host CPU. Required so host knows whether or not the memory
2686  * might need to be byte-swapped before returning value to caller.
2687  */
2688 #define hl_poll_timeout_memory(hdev, addr, val, cond, sleep_us, timeout_us, \
2689 				mem_written_by_device) \
2690 ({ \
2691 	ktime_t __timeout; \
2692 	if (hdev->pdev) \
2693 		__timeout = ktime_add_us(ktime_get(), timeout_us); \
2694 	else \
2695 		__timeout = ktime_add_us(ktime_get(),\
2696 				min((u64)(timeout_us * 100), \
2697 					(u64) HL_SIM_MAX_TIMEOUT_US)); \
2698 	might_sleep_if(sleep_us); \
2699 	for (;;) { \
2700 		/* Verify we read updates done by other cores or by device */ \
2701 		mb(); \
2702 		(val) = *((u32 *)(addr)); \
2703 		if (mem_written_by_device) \
2704 			(val) = le32_to_cpu(*(__le32 *) &(val)); \
2705 		if (cond) \
2706 			break; \
2707 		if (timeout_us && ktime_compare(ktime_get(), __timeout) > 0) { \
2708 			(val) = *((u32 *)(addr)); \
2709 			if (mem_written_by_device) \
2710 				(val) = le32_to_cpu(*(__le32 *) &(val)); \
2711 			break; \
2712 		} \
2713 		if (sleep_us) \
2714 			usleep_range((sleep_us >> 2) + 1, sleep_us); \
2715 	} \
2716 	(cond) ? 0 : -ETIMEDOUT; \
2717 })
2718 
2719 #define HL_USR_MAPPED_BLK_INIT(blk, base, sz) \
2720 ({ \
2721 	struct user_mapped_block *p = blk; \
2722 \
2723 	p->address = base; \
2724 	p->size = sz; \
2725 })
2726 
2727 #define HL_USR_INTR_STRUCT_INIT(usr_intr, hdev, intr_id, intr_type) \
2728 ({ \
2729 	usr_intr.hdev = hdev; \
2730 	usr_intr.interrupt_id = intr_id; \
2731 	usr_intr.type = intr_type; \
2732 	INIT_LIST_HEAD(&usr_intr.wait_list_head); \
2733 	spin_lock_init(&usr_intr.wait_list_lock); \
2734 })
2735 
2736 struct hwmon_chip_info;
2737 
2738 /**
2739  * struct hl_device_reset_work - reset work wrapper.
2740  * @reset_work: reset work to be done.
2741  * @hdev: habanalabs device structure.
2742  * @flags: reset flags.
2743  */
2744 struct hl_device_reset_work {
2745 	struct delayed_work	reset_work;
2746 	struct hl_device	*hdev;
2747 	u32			flags;
2748 };
2749 
2750 /**
2751  * struct hl_mmu_hr_pgt_priv - used for holding per-device mmu host-resident
2752  * page-table internal information.
2753  * @mmu_pgt_pool: pool of page tables used by a host-resident MMU for
2754  *                allocating hops.
2755  * @mmu_asid_hop0: per-ASID array of host-resident hop0 tables.
2756  */
2757 struct hl_mmu_hr_priv {
2758 	struct gen_pool	*mmu_pgt_pool;
2759 	struct pgt_info	*mmu_asid_hop0;
2760 };
2761 
2762 /**
2763  * struct hl_mmu_dr_pgt_priv - used for holding per-device mmu device-resident
2764  * page-table internal information.
2765  * @mmu_pgt_pool: pool of page tables used by MMU for allocating hops.
2766  * @mmu_shadow_hop0: shadow array of hop0 tables.
2767  */
2768 struct hl_mmu_dr_priv {
2769 	struct gen_pool *mmu_pgt_pool;
2770 	void *mmu_shadow_hop0;
2771 };
2772 
2773 /**
2774  * struct hl_mmu_priv - used for holding per-device mmu internal information.
2775  * @dr: information on the device-resident MMU, when exists.
2776  * @hr: information on the host-resident MMU, when exists.
2777  */
2778 struct hl_mmu_priv {
2779 	struct hl_mmu_dr_priv dr;
2780 	struct hl_mmu_hr_priv hr;
2781 };
2782 
2783 /**
2784  * struct hl_mmu_per_hop_info - A structure describing one TLB HOP and its entry
2785  *                that was created in order to translate a virtual address to a
2786  *                physical one.
2787  * @hop_addr: The address of the hop.
2788  * @hop_pte_addr: The address of the hop entry.
2789  * @hop_pte_val: The value in the hop entry.
2790  */
2791 struct hl_mmu_per_hop_info {
2792 	u64 hop_addr;
2793 	u64 hop_pte_addr;
2794 	u64 hop_pte_val;
2795 };
2796 
2797 /**
2798  * struct hl_mmu_hop_info - A structure describing the TLB hops and their
2799  * hop-entries that were created in order to translate a virtual address to a
2800  * physical one.
2801  * @scrambled_vaddr: The value of the virtual address after scrambling. This
2802  *                   address replaces the original virtual-address when mapped
2803  *                   in the MMU tables.
2804  * @unscrambled_paddr: The un-scrambled physical address.
2805  * @hop_info: Array holding the per-hop information used for the translation.
2806  * @used_hops: The number of hops used for the translation.
2807  * @range_type: virtual address range type.
2808  */
2809 struct hl_mmu_hop_info {
2810 	u64 scrambled_vaddr;
2811 	u64 unscrambled_paddr;
2812 	struct hl_mmu_per_hop_info hop_info[MMU_ARCH_6_HOPS];
2813 	u32 used_hops;
2814 	enum hl_va_range_type range_type;
2815 };
2816 
2817 /**
2818  * struct hl_hr_mmu_funcs - Device related host resident MMU functions.
2819  * @get_hop0_pgt_info: get page table info structure for HOP0.
2820  * @get_pgt_info: get page table info structure for HOP other than HOP0.
2821  * @add_pgt_info: add page table info structure to hash.
2822  * @get_tlb_mapping_params: get mapping parameters needed for getting TLB info for specific mapping.
2823  */
2824 struct hl_hr_mmu_funcs {
2825 	struct pgt_info *(*get_hop0_pgt_info)(struct hl_ctx *ctx);
2826 	struct pgt_info *(*get_pgt_info)(struct hl_ctx *ctx, u64 phys_hop_addr);
2827 	void (*add_pgt_info)(struct hl_ctx *ctx, struct pgt_info *pgt_info, dma_addr_t phys_addr);
2828 	int (*get_tlb_mapping_params)(struct hl_device *hdev, struct hl_mmu_properties **mmu_prop,
2829 								struct hl_mmu_hop_info *hops,
2830 								u64 virt_addr, bool *is_huge);
2831 };
2832 
2833 /**
2834  * struct hl_mmu_funcs - Device related MMU functions.
2835  * @init: initialize the MMU module.
2836  * @fini: release the MMU module.
2837  * @ctx_init: Initialize a context for using the MMU module.
2838  * @ctx_fini: disable a ctx from using the mmu module.
2839  * @map: maps a virtual address to physical address for a context.
2840  * @unmap: unmap a virtual address of a context.
2841  * @flush: flush all writes from all cores to reach device MMU.
2842  * @swap_out: marks all mapping of the given context as swapped out.
2843  * @swap_in: marks all mapping of the given context as swapped in.
2844  * @get_tlb_info: returns the list of hops and hop-entries used that were
2845  *                created in order to translate the giver virtual address to a
2846  *                physical one.
2847  * @hr_funcs: functions specific to host resident MMU.
2848  */
2849 struct hl_mmu_funcs {
2850 	int (*init)(struct hl_device *hdev);
2851 	void (*fini)(struct hl_device *hdev);
2852 	int (*ctx_init)(struct hl_ctx *ctx);
2853 	void (*ctx_fini)(struct hl_ctx *ctx);
2854 	int (*map)(struct hl_ctx *ctx, u64 virt_addr, u64 phys_addr, u32 page_size,
2855 				bool is_dram_addr);
2856 	int (*unmap)(struct hl_ctx *ctx, u64 virt_addr, bool is_dram_addr);
2857 	void (*flush)(struct hl_ctx *ctx);
2858 	void (*swap_out)(struct hl_ctx *ctx);
2859 	void (*swap_in)(struct hl_ctx *ctx);
2860 	int (*get_tlb_info)(struct hl_ctx *ctx, u64 virt_addr, struct hl_mmu_hop_info *hops);
2861 	struct hl_hr_mmu_funcs hr_funcs;
2862 };
2863 
2864 /**
2865  * struct hl_prefetch_work - prefetch work structure handler
2866  * @prefetch_work: actual work struct.
2867  * @ctx: compute context.
2868  * @va: virtual address to pre-fetch.
2869  * @size: pre-fetch size.
2870  * @flags: operation flags.
2871  * @asid: ASID for maintenance operation.
2872  */
2873 struct hl_prefetch_work {
2874 	struct work_struct	prefetch_work;
2875 	struct hl_ctx		*ctx;
2876 	u64			va;
2877 	u64			size;
2878 	u32			flags;
2879 	u32			asid;
2880 };
2881 
2882 /*
2883  * number of user contexts allowed to call wait_for_multi_cs ioctl in
2884  * parallel
2885  */
2886 #define MULTI_CS_MAX_USER_CTX	2
2887 
2888 /**
2889  * struct multi_cs_completion - multi CS wait completion.
2890  * @completion: completion of any of the CS in the list
2891  * @lock: spinlock for the completion structure
2892  * @timestamp: timestamp for the multi-CS completion
2893  * @stream_master_qid_map: bitmap of all stream masters on which the multi-CS
2894  *                        is waiting
2895  * @used: 1 if in use, otherwise 0
2896  */
2897 struct multi_cs_completion {
2898 	struct completion	completion;
2899 	spinlock_t		lock;
2900 	s64			timestamp;
2901 	u32			stream_master_qid_map;
2902 	u8			used;
2903 };
2904 
2905 /**
2906  * struct multi_cs_data - internal data for multi CS call
2907  * @ctx: pointer to the context structure
2908  * @fence_arr: array of fences of all CSs
2909  * @seq_arr: array of CS sequence numbers
2910  * @timeout_jiffies: timeout in jiffies for waiting for CS to complete
2911  * @timestamp: timestamp of first completed CS
2912  * @wait_status: wait for CS status
2913  * @completion_bitmap: bitmap of completed CSs (1- completed, otherwise 0)
2914  * @arr_len: fence_arr and seq_arr array length
2915  * @gone_cs: indication of gone CS (1- there was gone CS, otherwise 0)
2916  * @update_ts: update timestamp. 1- update the timestamp, otherwise 0.
2917  */
2918 struct multi_cs_data {
2919 	struct hl_ctx	*ctx;
2920 	struct hl_fence	**fence_arr;
2921 	u64		*seq_arr;
2922 	s64		timeout_jiffies;
2923 	s64		timestamp;
2924 	long		wait_status;
2925 	u32		completion_bitmap;
2926 	u8		arr_len;
2927 	u8		gone_cs;
2928 	u8		update_ts;
2929 };
2930 
2931 /**
2932  * struct hl_clk_throttle_timestamp - current/last clock throttling timestamp
2933  * @start: timestamp taken when 'start' event is received in driver
2934  * @end: timestamp taken when 'end' event is received in driver
2935  */
2936 struct hl_clk_throttle_timestamp {
2937 	ktime_t		start;
2938 	ktime_t		end;
2939 };
2940 
2941 /**
2942  * struct hl_clk_throttle - keeps current/last clock throttling timestamps
2943  * @timestamp: timestamp taken by driver and firmware, index 0 refers to POWER
2944  *             index 1 refers to THERMAL
2945  * @lock: protects this structure as it can be accessed from both event queue
2946  *        context and info_ioctl context
2947  * @current_reason: bitmask represents the current clk throttling reasons
2948  * @aggregated_reason: bitmask represents aggregated clk throttling reasons since driver load
2949  */
2950 struct hl_clk_throttle {
2951 	struct hl_clk_throttle_timestamp timestamp[HL_CLK_THROTTLE_TYPE_MAX];
2952 	struct mutex	lock;
2953 	u32		current_reason;
2954 	u32		aggregated_reason;
2955 };
2956 
2957 /**
2958  * struct user_mapped_block - describes a hw block allowed to be mmapped by user
2959  * @address: physical HW block address
2960  * @size: allowed size for mmap
2961  */
2962 struct user_mapped_block {
2963 	u32 address;
2964 	u32 size;
2965 };
2966 
2967 /**
2968  * struct cs_timeout_info - info of last CS timeout occurred.
2969  * @timestamp: CS timeout timestamp.
2970  * @write_enable: if set writing to CS parameters in the structure is enabled. otherwise - disabled,
2971  *                so the first (root cause) CS timeout will not be overwritten.
2972  * @seq: CS timeout sequence number.
2973  */
2974 struct cs_timeout_info {
2975 	ktime_t		timestamp;
2976 	atomic_t	write_enable;
2977 	u64		seq;
2978 };
2979 
2980 #define MAX_QMAN_STREAMS_INFO		4
2981 #define OPCODE_INFO_MAX_ADDR_SIZE	8
2982 /**
2983  * struct undefined_opcode_info - info about last undefined opcode error
2984  * @timestamp: timestamp of the undefined opcode error
2985  * @cb_addr_streams: CB addresses (per stream) that are currently exists in the PQ
2986  *                   entries. In case all streams array entries are
2987  *                   filled with values, it means the execution was in Lower-CP.
2988  * @cq_addr: the address of the current handled command buffer
2989  * @cq_size: the size of the current handled command buffer
2990  * @cb_addr_streams_len: num of streams - actual len of cb_addr_streams array.
2991  *                       should be equal to 1 in case of undefined opcode
2992  *                       in Upper-CP (specific stream) and equal to 4 in case
2993  *                       of undefined opcode in Lower-CP.
2994  * @engine_id: engine-id that the error occurred on
2995  * @stream_id: the stream id the error occurred on. In case the stream equals to
2996  *             MAX_QMAN_STREAMS_INFO it means the error occurred on a Lower-CP.
2997  * @write_enable: if set, writing to undefined opcode parameters in the structure
2998  *                 is enable so the first (root cause) undefined opcode will not be
2999  *                 overwritten.
3000  */
3001 struct undefined_opcode_info {
3002 	ktime_t timestamp;
3003 	u64 cb_addr_streams[MAX_QMAN_STREAMS_INFO][OPCODE_INFO_MAX_ADDR_SIZE];
3004 	u64 cq_addr;
3005 	u32 cq_size;
3006 	u32 cb_addr_streams_len;
3007 	u32 engine_id;
3008 	u32 stream_id;
3009 	bool write_enable;
3010 };
3011 
3012 /**
3013  * struct page_fault_info - page fault information.
3014  * @page_fault: holds information collected during a page fault.
3015  * @user_mappings: buffer containing user mappings.
3016  * @num_of_user_mappings: number of user mappings.
3017  * @page_fault_detected: if set as 1, then a page-fault was discovered for the
3018  *                       first time after the driver has finished booting-up.
3019  *                       Since we're looking for the page-fault's root cause,
3020  *                       we don't care of the others that might follow it-
3021  *                       so once changed to 1, it will remain that way.
3022  * @page_fault_info_available: indicates that a page fault info is now available.
3023  */
3024 struct page_fault_info {
3025 	struct hl_page_fault_info	page_fault;
3026 	struct hl_user_mapping		*user_mappings;
3027 	u64				num_of_user_mappings;
3028 	atomic_t			page_fault_detected;
3029 	bool				page_fault_info_available;
3030 };
3031 
3032 /**
3033  * struct razwi_info - RAZWI information.
3034  * @razwi: holds information collected during a RAZWI
3035  * @razwi_detected: if set as 1, then a RAZWI was discovered for the
3036  *                  first time after the driver has finished booting-up.
3037  *                  Since we're looking for the RAZWI's root cause,
3038  *                  we don't care of the others that might follow it-
3039  *                  so once changed to 1, it will remain that way.
3040  * @razwi_info_available: indicates that a RAZWI info is now available.
3041  */
3042 struct razwi_info {
3043 	struct hl_info_razwi_event	razwi;
3044 	atomic_t			razwi_detected;
3045 	bool				razwi_info_available;
3046 };
3047 
3048 /**
3049  * struct hw_err_info - HW error information.
3050  * @event: holds information on the event.
3051  * @event_detected: if set as 1, then a HW event was discovered for the
3052  *                  first time after the driver has finished booting-up.
3053  *                  currently we assume that only fatal events (that require hard-reset) are
3054  *                  reported so we don't care of the others that might follow it.
3055  *                  so once changed to 1, it will remain that way.
3056  *                  TODO: support multiple events.
3057  * @event_info_available: indicates that a HW event info is now available.
3058  */
3059 struct hw_err_info {
3060 	struct hl_info_hw_err_event	event;
3061 	atomic_t			event_detected;
3062 	bool				event_info_available;
3063 };
3064 
3065 /**
3066  * struct fw_err_info - FW error information.
3067  * @event: holds information on the event.
3068  * @event_detected: if set as 1, then a FW event was discovered for the
3069  *                  first time after the driver has finished booting-up.
3070  *                  currently we assume that only fatal events (that require hard-reset) are
3071  *                  reported so we don't care of the others that might follow it.
3072  *                  so once changed to 1, it will remain that way.
3073  *                  TODO: support multiple events.
3074  * @event_info_available: indicates that a HW event info is now available.
3075  */
3076 struct fw_err_info {
3077 	struct hl_info_fw_err_event	event;
3078 	atomic_t			event_detected;
3079 	bool				event_info_available;
3080 };
3081 
3082 /**
3083  * struct hl_error_info - holds information collected during an error.
3084  * @cs_timeout: CS timeout error information.
3085  * @razwi_info: RAZWI information.
3086  * @undef_opcode: undefined opcode information.
3087  * @page_fault_info: page fault information.
3088  * @hw_err: (fatal) hardware error information.
3089  * @fw_err: firmware error information.
3090  */
3091 struct hl_error_info {
3092 	struct cs_timeout_info		cs_timeout;
3093 	struct razwi_info		razwi_info;
3094 	struct undefined_opcode_info	undef_opcode;
3095 	struct page_fault_info		page_fault_info;
3096 	struct hw_err_info		hw_err;
3097 	struct fw_err_info		fw_err;
3098 };
3099 
3100 /**
3101  * struct hl_reset_info - holds current device reset information.
3102  * @lock: lock to protect critical reset flows.
3103  * @compute_reset_cnt: number of compute resets since the driver was loaded.
3104  * @hard_reset_cnt: number of hard resets since the driver was loaded.
3105  * @hard_reset_schedule_flags: hard reset is scheduled to after current compute reset,
3106  *                             here we hold the hard reset flags.
3107  * @in_reset: is device in reset flow.
3108  * @in_compute_reset: Device is currently in reset but not in hard-reset.
3109  * @needs_reset: true if reset_on_lockup is false and device should be reset
3110  *               due to lockup.
3111  * @hard_reset_pending: is there a hard reset work pending.
3112  * @curr_reset_cause: saves an enumerated reset cause when a hard reset is
3113  *                    triggered, and cleared after it is shared with preboot.
3114  * @prev_reset_trigger: saves the previous trigger which caused a reset, overridden
3115  *                      with a new value on next reset
3116  * @reset_trigger_repeated: set if device reset is triggered more than once with
3117  *                          same cause.
3118  * @skip_reset_on_timeout: Skip device reset if CS has timed out, wait for it to
3119  *                         complete instead.
3120  * @watchdog_active: true if a device release watchdog work is scheduled.
3121  */
3122 struct hl_reset_info {
3123 	spinlock_t	lock;
3124 	u32		compute_reset_cnt;
3125 	u32		hard_reset_cnt;
3126 	u32		hard_reset_schedule_flags;
3127 	u8		in_reset;
3128 	u8		in_compute_reset;
3129 	u8		needs_reset;
3130 	u8		hard_reset_pending;
3131 	u8		curr_reset_cause;
3132 	u8		prev_reset_trigger;
3133 	u8		reset_trigger_repeated;
3134 	u8		skip_reset_on_timeout;
3135 	u8		watchdog_active;
3136 };
3137 
3138 /**
3139  * struct hl_device - habanalabs device structure.
3140  * @pdev: pointer to PCI device, can be NULL in case of simulator device.
3141  * @pcie_bar_phys: array of available PCIe bars physical addresses.
3142  *		   (required only for PCI address match mode)
3143  * @pcie_bar: array of available PCIe bars virtual addresses.
3144  * @rmmio: configuration area address on SRAM.
3145  * @hclass: pointer to the habanalabs class.
3146  * @cdev: related char device.
3147  * @cdev_ctrl: char device for control operations only (INFO IOCTL)
3148  * @dev: related kernel basic device structure.
3149  * @dev_ctrl: related kernel device structure for the control device
3150  * @work_heartbeat: delayed work for CPU-CP is-alive check.
3151  * @device_reset_work: delayed work which performs hard reset
3152  * @device_release_watchdog_work: watchdog work that performs hard reset if user doesn't release
3153  *                                device upon certain error cases.
3154  * @asic_name: ASIC specific name.
3155  * @asic_type: ASIC specific type.
3156  * @completion_queue: array of hl_cq.
3157  * @user_interrupt: array of hl_user_interrupt. upon the corresponding user
3158  *                  interrupt, driver will monitor the list of fences
3159  *                  registered to this interrupt.
3160  * @tpc_interrupt: single TPC interrupt for all TPCs.
3161  * @unexpected_error_interrupt: single interrupt for unexpected user error indication.
3162  * @common_user_cq_interrupt: common user CQ interrupt for all user CQ interrupts.
3163  *                         upon any user CQ interrupt, driver will monitor the
3164  *                         list of fences registered to this common structure.
3165  * @common_decoder_interrupt: common decoder interrupt for all user decoder interrupts.
3166  * @shadow_cs_queue: pointer to a shadow queue that holds pointers to
3167  *                   outstanding command submissions.
3168  * @cq_wq: work queues of completion queues for executing work in process
3169  *         context.
3170  * @eq_wq: work queue of event queue for executing work in process context.
3171  * @cs_cmplt_wq: work queue of CS completions for executing work in process
3172  *               context.
3173  * @ts_free_obj_wq: work queue for timestamp registration objects release.
3174  * @prefetch_wq: work queue for MMU pre-fetch operations.
3175  * @reset_wq: work queue for device reset procedure.
3176  * @kernel_ctx: Kernel driver context structure.
3177  * @kernel_queues: array of hl_hw_queue.
3178  * @cs_mirror_list: CS mirror list for TDR.
3179  * @cs_mirror_lock: protects cs_mirror_list.
3180  * @kernel_mem_mgr: memory manager for memory buffers with lifespan of driver.
3181  * @event_queue: event queue for IRQ from CPU-CP.
3182  * @dma_pool: DMA pool for small allocations.
3183  * @cpu_accessible_dma_mem: Host <-> CPU-CP shared memory CPU address.
3184  * @cpu_accessible_dma_address: Host <-> CPU-CP shared memory DMA address.
3185  * @cpu_accessible_dma_pool: Host <-> CPU-CP shared memory pool.
3186  * @asid_bitmap: holds used/available ASIDs.
3187  * @asid_mutex: protects asid_bitmap.
3188  * @send_cpu_message_lock: enforces only one message in Host <-> CPU-CP queue.
3189  * @debug_lock: protects critical section of setting debug mode for device
3190  * @mmu_lock: protects the MMU page tables and invalidation h/w. Although the
3191  *            page tables are per context, the invalidation h/w is per MMU.
3192  *            Therefore, we can't allow multiple contexts (we only have two,
3193  *            user and kernel) to access the invalidation h/w at the same time.
3194  *            In addition, any change to the PGT, modifying the MMU hash or
3195  *            walking the PGT requires talking this lock.
3196  * @asic_prop: ASIC specific immutable properties.
3197  * @asic_funcs: ASIC specific functions.
3198  * @asic_specific: ASIC specific information to use only from ASIC files.
3199  * @vm: virtual memory manager for MMU.
3200  * @hwmon_dev: H/W monitor device.
3201  * @hl_chip_info: ASIC's sensors information.
3202  * @device_status_description: device status description.
3203  * @hl_debugfs: device's debugfs manager.
3204  * @cb_pool: list of pre allocated CBs.
3205  * @cb_pool_lock: protects the CB pool.
3206  * @internal_cb_pool_virt_addr: internal command buffer pool virtual address.
3207  * @internal_cb_pool_dma_addr: internal command buffer pool dma address.
3208  * @internal_cb_pool: internal command buffer memory pool.
3209  * @internal_cb_va_base: internal cb pool mmu virtual address base
3210  * @fpriv_list: list of file private data structures. Each structure is created
3211  *              when a user opens the device
3212  * @fpriv_ctrl_list: list of file private data structures. Each structure is created
3213  *              when a user opens the control device
3214  * @fpriv_list_lock: protects the fpriv_list
3215  * @fpriv_ctrl_list_lock: protects the fpriv_ctrl_list
3216  * @aggregated_cs_counters: aggregated cs counters among all contexts
3217  * @mmu_priv: device-specific MMU data.
3218  * @mmu_func: device-related MMU functions.
3219  * @dec: list of decoder sw instance
3220  * @fw_loader: FW loader manager.
3221  * @pci_mem_region: array of memory regions in the PCI
3222  * @state_dump_specs: constants and dictionaries needed to dump system state.
3223  * @multi_cs_completion: array of multi-CS completion.
3224  * @clk_throttling: holds information about current/previous clock throttling events
3225  * @captured_err_info: holds information about errors.
3226  * @reset_info: holds current device reset information.
3227  * @stream_master_qid_arr: pointer to array with QIDs of master streams.
3228  * @fw_major_version: major version of current loaded preboot.
3229  * @fw_minor_version: minor version of current loaded preboot.
3230  * @dram_used_mem: current DRAM memory consumption.
3231  * @memory_scrub_val: the value to which the dram will be scrubbed to using cb scrub_device_dram
3232  * @timeout_jiffies: device CS timeout value.
3233  * @max_power: the max power of the device, as configured by the sysadmin. This
3234  *             value is saved so in case of hard-reset, the driver will restore
3235  *             this value and update the F/W after the re-initialization
3236  * @boot_error_status_mask: contains a mask of the device boot error status.
3237  *                          Each bit represents a different error, according to
3238  *                          the defines in hl_boot_if.h. If the bit is cleared,
3239  *                          the error will be ignored by the driver during
3240  *                          device initialization. Mainly used to debug and
3241  *                          workaround firmware bugs
3242  * @dram_pci_bar_start: start bus address of PCIe bar towards DRAM.
3243  * @last_successful_open_ktime: timestamp (ktime) of the last successful device open.
3244  * @last_successful_open_jif: timestamp (jiffies) of the last successful
3245  *                            device open.
3246  * @last_open_session_duration_jif: duration (jiffies) of the last device open
3247  *                                  session.
3248  * @open_counter: number of successful device open operations.
3249  * @fw_poll_interval_usec: FW status poll interval in usec.
3250  *                         used for CPU boot status
3251  * @fw_comms_poll_interval_usec: FW comms/protocol poll interval in usec.
3252  *                                  used for COMMs protocols cmds(COMMS_STS_*)
3253  * @dram_binning: contains mask of drams that is received from the f/w which indicates which
3254  *                drams are binned-out
3255  * @tpc_binning: contains mask of tpc engines that is received from the f/w which indicates which
3256  *               tpc engines are binned-out
3257  * @dmabuf_export_cnt: number of dma-buf exporting.
3258  * @card_type: Various ASICs have several card types. This indicates the card
3259  *             type of the current device.
3260  * @major: habanalabs kernel driver major.
3261  * @high_pll: high PLL profile frequency.
3262  * @decoder_binning: contains mask of decoder engines that is received from the f/w which
3263  *                   indicates which decoder engines are binned-out
3264  * @edma_binning: contains mask of edma engines that is received from the f/w which
3265  *                   indicates which edma engines are binned-out
3266  * @device_release_watchdog_timeout_sec: device release watchdog timeout value in seconds.
3267  * @rotator_binning: contains mask of rotators engines that is received from the f/w
3268  *			which indicates which rotator engines are binned-out(Gaudi3 and above).
3269  * @id: device minor.
3270  * @id_control: minor of the control device.
3271  * @cdev_idx: char device index. Used for setting its name.
3272  * @cpu_pci_msb_addr: 50-bit extension bits for the device CPU's 40-bit
3273  *                    addresses.
3274  * @is_in_dram_scrub: true if dram scrub operation is on going.
3275  * @disabled: is device disabled.
3276  * @late_init_done: is late init stage was done during initialization.
3277  * @hwmon_initialized: is H/W monitor sensors was initialized.
3278  * @reset_on_lockup: true if a reset should be done in case of stuck CS, false
3279  *                   otherwise.
3280  * @dram_default_page_mapping: is DRAM default page mapping enabled.
3281  * @memory_scrub: true to perform device memory scrub in various locations,
3282  *                such as context-switch, context close, page free, etc.
3283  * @pmmu_huge_range: is a different virtual addresses range used for PMMU with
3284  *                   huge pages.
3285  * @init_done: is the initialization of the device done.
3286  * @device_cpu_disabled: is the device CPU disabled (due to timeouts)
3287  * @in_debug: whether the device is in a state where the profiling/tracing infrastructure
3288  *            can be used. This indication is needed because in some ASICs we need to do
3289  *            specific operations to enable that infrastructure.
3290  * @cdev_sysfs_created: were char devices and sysfs nodes created.
3291  * @stop_on_err: true if engines should stop on error.
3292  * @supports_sync_stream: is sync stream supported.
3293  * @sync_stream_queue_idx: helper index for sync stream queues initialization.
3294  * @collective_mon_idx: helper index for collective initialization
3295  * @supports_coresight: is CoreSight supported.
3296  * @supports_cb_mapping: is mapping a CB to the device's MMU supported.
3297  * @process_kill_trial_cnt: number of trials reset thread tried killing
3298  *                          user processes
3299  * @device_fini_pending: true if device_fini was called and might be
3300  *                       waiting for the reset thread to finish
3301  * @supports_staged_submission: true if staged submissions are supported
3302  * @device_cpu_is_halted: Flag to indicate whether the device CPU was already
3303  *                        halted. We can't halt it again because the COMMS
3304  *                        protocol will throw an error. Relevant only for
3305  *                        cases where Linux was not loaded to device CPU
3306  * @supports_wait_for_multi_cs: true if wait for multi CS is supported
3307  * @is_compute_ctx_active: Whether there is an active compute context executing.
3308  * @compute_ctx_in_release: true if the current compute context is being released.
3309  * @supports_mmu_prefetch: true if prefetch is supported, otherwise false.
3310  * @reset_upon_device_release: reset the device when the user closes the file descriptor of the
3311  *                             device.
3312  * @supports_ctx_switch: true if a ctx switch is required upon first submission.
3313  * @support_preboot_binning: true if we support read binning info from preboot.
3314  * @nic_ports_mask: Controls which NIC ports are enabled. Used only for testing.
3315  * @fw_components: Controls which f/w components to load to the device. There are multiple f/w
3316  *                 stages and sometimes we want to stop at a certain stage. Used only for testing.
3317  * @mmu_enable: Whether to enable or disable the device MMU(s). Used only for testing.
3318  * @cpu_queues_enable: Whether to enable queues communication vs. the f/w. Used only for testing.
3319  * @pldm: Whether we are running in Palladium environment. Used only for testing.
3320  * @hard_reset_on_fw_events: Whether to do device hard-reset when a fatal event is received from
3321  *                           the f/w. Used only for testing.
3322  * @bmc_enable: Whether we are running in a box with BMC. Used only for testing.
3323  * @reset_on_preboot_fail: Whether to reset the device if preboot f/w fails to load.
3324  *                         Used only for testing.
3325  * @heartbeat: Controls if we want to enable the heartbeat mechanism vs. the f/w, which verifies
3326  *             that the f/w is always alive. Used only for testing.
3327  */
3328 struct hl_device {
3329 	struct pci_dev			*pdev;
3330 	u64				pcie_bar_phys[HL_PCI_NUM_BARS];
3331 	void __iomem			*pcie_bar[HL_PCI_NUM_BARS];
3332 	void __iomem			*rmmio;
3333 	struct class			*hclass;
3334 	struct cdev			cdev;
3335 	struct cdev			cdev_ctrl;
3336 	struct device			*dev;
3337 	struct device			*dev_ctrl;
3338 	struct delayed_work		work_heartbeat;
3339 	struct hl_device_reset_work	device_reset_work;
3340 	struct hl_device_reset_work	device_release_watchdog_work;
3341 	char				asic_name[HL_STR_MAX];
3342 	char				status[HL_DEV_STS_MAX][HL_STR_MAX];
3343 	enum hl_asic_type		asic_type;
3344 	struct hl_cq			*completion_queue;
3345 	struct hl_user_interrupt	*user_interrupt;
3346 	struct hl_user_interrupt	tpc_interrupt;
3347 	struct hl_user_interrupt	unexpected_error_interrupt;
3348 	struct hl_user_interrupt	common_user_cq_interrupt;
3349 	struct hl_user_interrupt	common_decoder_interrupt;
3350 	struct hl_cs			**shadow_cs_queue;
3351 	struct workqueue_struct		**cq_wq;
3352 	struct workqueue_struct		*eq_wq;
3353 	struct workqueue_struct		*cs_cmplt_wq;
3354 	struct workqueue_struct		*ts_free_obj_wq;
3355 	struct workqueue_struct		*prefetch_wq;
3356 	struct workqueue_struct		*reset_wq;
3357 	struct hl_ctx			*kernel_ctx;
3358 	struct hl_hw_queue		*kernel_queues;
3359 	struct list_head		cs_mirror_list;
3360 	spinlock_t			cs_mirror_lock;
3361 	struct hl_mem_mgr		kernel_mem_mgr;
3362 	struct hl_eq			event_queue;
3363 	struct dma_pool			*dma_pool;
3364 	void				*cpu_accessible_dma_mem;
3365 	dma_addr_t			cpu_accessible_dma_address;
3366 	struct gen_pool			*cpu_accessible_dma_pool;
3367 	unsigned long			*asid_bitmap;
3368 	struct mutex			asid_mutex;
3369 	struct mutex			send_cpu_message_lock;
3370 	struct mutex			debug_lock;
3371 	struct mutex			mmu_lock;
3372 	struct asic_fixed_properties	asic_prop;
3373 	const struct hl_asic_funcs	*asic_funcs;
3374 	void				*asic_specific;
3375 	struct hl_vm			vm;
3376 	struct device			*hwmon_dev;
3377 	struct hwmon_chip_info		*hl_chip_info;
3378 
3379 	struct hl_dbg_device_entry	hl_debugfs;
3380 
3381 	struct list_head		cb_pool;
3382 	spinlock_t			cb_pool_lock;
3383 
3384 	void				*internal_cb_pool_virt_addr;
3385 	dma_addr_t			internal_cb_pool_dma_addr;
3386 	struct gen_pool			*internal_cb_pool;
3387 	u64				internal_cb_va_base;
3388 
3389 	struct list_head		fpriv_list;
3390 	struct list_head		fpriv_ctrl_list;
3391 	struct mutex			fpriv_list_lock;
3392 	struct mutex			fpriv_ctrl_list_lock;
3393 
3394 	struct hl_cs_counters_atomic	aggregated_cs_counters;
3395 
3396 	struct hl_mmu_priv		mmu_priv;
3397 	struct hl_mmu_funcs		mmu_func[MMU_NUM_PGT_LOCATIONS];
3398 
3399 	struct hl_dec			*dec;
3400 
3401 	struct fw_load_mgr		fw_loader;
3402 
3403 	struct pci_mem_region		pci_mem_region[PCI_REGION_NUMBER];
3404 
3405 	struct hl_state_dump_specs	state_dump_specs;
3406 
3407 	struct multi_cs_completion	multi_cs_completion[
3408 							MULTI_CS_MAX_USER_CTX];
3409 	struct hl_clk_throttle		clk_throttling;
3410 	struct hl_error_info		captured_err_info;
3411 
3412 	struct hl_reset_info		reset_info;
3413 
3414 	u32				*stream_master_qid_arr;
3415 	u32				fw_major_version;
3416 	u32				fw_minor_version;
3417 	atomic64_t			dram_used_mem;
3418 	u64				memory_scrub_val;
3419 	u64				timeout_jiffies;
3420 	u64				max_power;
3421 	u64				boot_error_status_mask;
3422 	u64				dram_pci_bar_start;
3423 	u64				last_successful_open_jif;
3424 	u64				last_open_session_duration_jif;
3425 	u64				open_counter;
3426 	u64				fw_poll_interval_usec;
3427 	ktime_t				last_successful_open_ktime;
3428 	u64				fw_comms_poll_interval_usec;
3429 	u64				dram_binning;
3430 	u64				tpc_binning;
3431 	atomic_t			dmabuf_export_cnt;
3432 	enum cpucp_card_types		card_type;
3433 	u32				major;
3434 	u32				high_pll;
3435 	u32				decoder_binning;
3436 	u32				edma_binning;
3437 	u32				device_release_watchdog_timeout_sec;
3438 	u32				rotator_binning;
3439 	u16				id;
3440 	u16				id_control;
3441 	u16				cdev_idx;
3442 	u16				cpu_pci_msb_addr;
3443 	u8				is_in_dram_scrub;
3444 	u8				disabled;
3445 	u8				late_init_done;
3446 	u8				hwmon_initialized;
3447 	u8				reset_on_lockup;
3448 	u8				dram_default_page_mapping;
3449 	u8				memory_scrub;
3450 	u8				pmmu_huge_range;
3451 	u8				init_done;
3452 	u8				device_cpu_disabled;
3453 	u8				in_debug;
3454 	u8				cdev_sysfs_created;
3455 	u8				stop_on_err;
3456 	u8				supports_sync_stream;
3457 	u8				sync_stream_queue_idx;
3458 	u8				collective_mon_idx;
3459 	u8				supports_coresight;
3460 	u8				supports_cb_mapping;
3461 	u8				process_kill_trial_cnt;
3462 	u8				device_fini_pending;
3463 	u8				supports_staged_submission;
3464 	u8				device_cpu_is_halted;
3465 	u8				supports_wait_for_multi_cs;
3466 	u8				stream_master_qid_arr_size;
3467 	u8				is_compute_ctx_active;
3468 	u8				compute_ctx_in_release;
3469 	u8				supports_mmu_prefetch;
3470 	u8				reset_upon_device_release;
3471 	u8				supports_ctx_switch;
3472 	u8				support_preboot_binning;
3473 
3474 	/* Parameters for bring-up to be upstreamed */
3475 	u64				nic_ports_mask;
3476 	u64				fw_components;
3477 	u8				mmu_enable;
3478 	u8				cpu_queues_enable;
3479 	u8				pldm;
3480 	u8				hard_reset_on_fw_events;
3481 	u8				bmc_enable;
3482 	u8				reset_on_preboot_fail;
3483 	u8				heartbeat;
3484 };
3485 
3486 
3487 /**
3488  * struct hl_cs_encaps_sig_handle - encapsulated signals handle structure
3489  * @refcount: refcount used to protect removing this id when several
3490  *            wait cs are used to wait of the reserved encaps signals.
3491  * @hdev: pointer to habanalabs device structure.
3492  * @hw_sob: pointer to  H/W SOB used in the reservation.
3493  * @ctx: pointer to the user's context data structure
3494  * @cs_seq: staged cs sequence which contains encapsulated signals
3495  * @id: idr handler id to be used to fetch the handler info
3496  * @q_idx: stream queue index
3497  * @pre_sob_val: current SOB value before reservation
3498  * @count: signals number
3499  */
3500 struct hl_cs_encaps_sig_handle {
3501 	struct kref refcount;
3502 	struct hl_device *hdev;
3503 	struct hl_hw_sob *hw_sob;
3504 	struct hl_ctx *ctx;
3505 	u64  cs_seq;
3506 	u32  id;
3507 	u32  q_idx;
3508 	u32  pre_sob_val;
3509 	u32  count;
3510 };
3511 
3512 /**
3513  * struct hl_info_fw_err_info - firmware error information structure
3514  * @err_type: The type of error detected (or reported).
3515  * @event_mask: Pointer to the event mask to be modified with the detected error flag
3516  *              (can be NULL)
3517  * @event_id: The id of the event that reported the error
3518  *            (applicable when err_type is HL_INFO_FW_REPORTED_ERR).
3519  */
3520 struct hl_info_fw_err_info {
3521 	enum hl_info_fw_err_type err_type;
3522 	u64 *event_mask;
3523 	u16 event_id;
3524 };
3525 
3526 /*
3527  * IOCTLs
3528  */
3529 
3530 /**
3531  * typedef hl_ioctl_t - typedef for ioctl function in the driver
3532  * @hpriv: pointer to the FD's private data, which contains state of
3533  *		user process
3534  * @data: pointer to the input/output arguments structure of the IOCTL
3535  *
3536  * Return: 0 for success, negative value for error
3537  */
3538 typedef int hl_ioctl_t(struct hl_fpriv *hpriv, void *data);
3539 
3540 /**
3541  * struct hl_ioctl_desc - describes an IOCTL entry of the driver.
3542  * @cmd: the IOCTL code as created by the kernel macros.
3543  * @func: pointer to the driver's function that should be called for this IOCTL.
3544  */
3545 struct hl_ioctl_desc {
3546 	unsigned int cmd;
3547 	hl_ioctl_t *func;
3548 };
3549 
3550 static inline bool hl_is_fw_ver_below_1_9(struct hl_device *hdev)
3551 {
3552 	return (hdev->fw_major_version < 42);
3553 }
3554 
3555 /*
3556  * Kernel module functions that can be accessed by entire module
3557  */
3558 
3559 /**
3560  * hl_get_sg_info() - get number of pages and the DMA address from SG list.
3561  * @sg: the SG list.
3562  * @dma_addr: pointer to DMA address to return.
3563  *
3564  * Calculate the number of consecutive pages described by the SG list. Take the
3565  * offset of the address in the first page, add to it the length and round it up
3566  * to the number of needed pages.
3567  */
3568 static inline u32 hl_get_sg_info(struct scatterlist *sg, dma_addr_t *dma_addr)
3569 {
3570 	*dma_addr = sg_dma_address(sg);
3571 
3572 	return ((((*dma_addr) & (PAGE_SIZE - 1)) + sg_dma_len(sg)) +
3573 			(PAGE_SIZE - 1)) >> PAGE_SHIFT;
3574 }
3575 
3576 /**
3577  * hl_mem_area_inside_range() - Checks whether address+size are inside a range.
3578  * @address: The start address of the area we want to validate.
3579  * @size: The size in bytes of the area we want to validate.
3580  * @range_start_address: The start address of the valid range.
3581  * @range_end_address: The end address of the valid range.
3582  *
3583  * Return: true if the area is inside the valid range, false otherwise.
3584  */
3585 static inline bool hl_mem_area_inside_range(u64 address, u64 size,
3586 				u64 range_start_address, u64 range_end_address)
3587 {
3588 	u64 end_address = address + size;
3589 
3590 	if ((address >= range_start_address) &&
3591 			(end_address <= range_end_address) &&
3592 			(end_address > address))
3593 		return true;
3594 
3595 	return false;
3596 }
3597 
3598 /**
3599  * hl_mem_area_crosses_range() - Checks whether address+size crossing a range.
3600  * @address: The start address of the area we want to validate.
3601  * @size: The size in bytes of the area we want to validate.
3602  * @range_start_address: The start address of the valid range.
3603  * @range_end_address: The end address of the valid range.
3604  *
3605  * Return: true if the area overlaps part or all of the valid range,
3606  *		false otherwise.
3607  */
3608 static inline bool hl_mem_area_crosses_range(u64 address, u32 size,
3609 				u64 range_start_address, u64 range_end_address)
3610 {
3611 	u64 end_address = address + size - 1;
3612 
3613 	return ((address <= range_end_address) && (range_start_address <= end_address));
3614 }
3615 
3616 uint64_t hl_set_dram_bar_default(struct hl_device *hdev, u64 addr);
3617 void *hl_cpu_accessible_dma_pool_alloc(struct hl_device *hdev, size_t size, dma_addr_t *dma_handle);
3618 void hl_cpu_accessible_dma_pool_free(struct hl_device *hdev, size_t size, void *vaddr);
3619 void *hl_asic_dma_alloc_coherent_caller(struct hl_device *hdev, size_t size, dma_addr_t *dma_handle,
3620 					gfp_t flag, const char *caller);
3621 void hl_asic_dma_free_coherent_caller(struct hl_device *hdev, size_t size, void *cpu_addr,
3622 					dma_addr_t dma_handle, const char *caller);
3623 void *hl_asic_dma_pool_zalloc_caller(struct hl_device *hdev, size_t size, gfp_t mem_flags,
3624 					dma_addr_t *dma_handle, const char *caller);
3625 void hl_asic_dma_pool_free_caller(struct hl_device *hdev, void *vaddr, dma_addr_t dma_addr,
3626 					const char *caller);
3627 int hl_dma_map_sgtable(struct hl_device *hdev, struct sg_table *sgt, enum dma_data_direction dir);
3628 void hl_dma_unmap_sgtable(struct hl_device *hdev, struct sg_table *sgt,
3629 				enum dma_data_direction dir);
3630 int hl_access_sram_dram_region(struct hl_device *hdev, u64 addr, u64 *val,
3631 	enum debugfs_access_type acc_type, enum pci_region region_type, bool set_dram_bar);
3632 int hl_access_cfg_region(struct hl_device *hdev, u64 addr, u64 *val,
3633 	enum debugfs_access_type acc_type);
3634 int hl_access_dev_mem(struct hl_device *hdev, enum pci_region region_type,
3635 			u64 addr, u64 *val, enum debugfs_access_type acc_type);
3636 int hl_device_open(struct inode *inode, struct file *filp);
3637 int hl_device_open_ctrl(struct inode *inode, struct file *filp);
3638 bool hl_device_operational(struct hl_device *hdev,
3639 		enum hl_device_status *status);
3640 bool hl_ctrl_device_operational(struct hl_device *hdev,
3641 		enum hl_device_status *status);
3642 enum hl_device_status hl_device_status(struct hl_device *hdev);
3643 int hl_device_set_debug_mode(struct hl_device *hdev, struct hl_ctx *ctx, bool enable);
3644 int hl_hw_queues_create(struct hl_device *hdev);
3645 void hl_hw_queues_destroy(struct hl_device *hdev);
3646 int hl_hw_queue_send_cb_no_cmpl(struct hl_device *hdev, u32 hw_queue_id,
3647 		u32 cb_size, u64 cb_ptr);
3648 void hl_hw_queue_submit_bd(struct hl_device *hdev, struct hl_hw_queue *q,
3649 		u32 ctl, u32 len, u64 ptr);
3650 int hl_hw_queue_schedule_cs(struct hl_cs *cs);
3651 u32 hl_hw_queue_add_ptr(u32 ptr, u16 val);
3652 void hl_hw_queue_inc_ci_kernel(struct hl_device *hdev, u32 hw_queue_id);
3653 void hl_hw_queue_update_ci(struct hl_cs *cs);
3654 void hl_hw_queue_reset(struct hl_device *hdev, bool hard_reset);
3655 
3656 #define hl_queue_inc_ptr(p)		hl_hw_queue_add_ptr(p, 1)
3657 #define hl_pi_2_offset(pi)		((pi) & (HL_QUEUE_LENGTH - 1))
3658 
3659 int hl_cq_init(struct hl_device *hdev, struct hl_cq *q, u32 hw_queue_id);
3660 void hl_cq_fini(struct hl_device *hdev, struct hl_cq *q);
3661 int hl_eq_init(struct hl_device *hdev, struct hl_eq *q);
3662 void hl_eq_fini(struct hl_device *hdev, struct hl_eq *q);
3663 void hl_cq_reset(struct hl_device *hdev, struct hl_cq *q);
3664 void hl_eq_reset(struct hl_device *hdev, struct hl_eq *q);
3665 irqreturn_t hl_irq_handler_cq(int irq, void *arg);
3666 irqreturn_t hl_irq_handler_eq(int irq, void *arg);
3667 irqreturn_t hl_irq_handler_dec_abnrm(int irq, void *arg);
3668 irqreturn_t hl_irq_handler_user_interrupt(int irq, void *arg);
3669 irqreturn_t hl_irq_user_interrupt_thread_handler(int irq, void *arg);
3670 u32 hl_cq_inc_ptr(u32 ptr);
3671 
3672 int hl_asid_init(struct hl_device *hdev);
3673 void hl_asid_fini(struct hl_device *hdev);
3674 unsigned long hl_asid_alloc(struct hl_device *hdev);
3675 void hl_asid_free(struct hl_device *hdev, unsigned long asid);
3676 
3677 int hl_ctx_create(struct hl_device *hdev, struct hl_fpriv *hpriv);
3678 void hl_ctx_free(struct hl_device *hdev, struct hl_ctx *ctx);
3679 int hl_ctx_init(struct hl_device *hdev, struct hl_ctx *ctx, bool is_kernel_ctx);
3680 void hl_ctx_do_release(struct kref *ref);
3681 void hl_ctx_get(struct hl_ctx *ctx);
3682 int hl_ctx_put(struct hl_ctx *ctx);
3683 struct hl_ctx *hl_get_compute_ctx(struct hl_device *hdev);
3684 struct hl_fence *hl_ctx_get_fence(struct hl_ctx *ctx, u64 seq);
3685 int hl_ctx_get_fences(struct hl_ctx *ctx, u64 *seq_arr,
3686 				struct hl_fence **fence, u32 arr_len);
3687 void hl_ctx_mgr_init(struct hl_ctx_mgr *mgr);
3688 void hl_ctx_mgr_fini(struct hl_device *hdev, struct hl_ctx_mgr *mgr);
3689 
3690 int hl_device_init(struct hl_device *hdev);
3691 void hl_device_fini(struct hl_device *hdev);
3692 int hl_device_suspend(struct hl_device *hdev);
3693 int hl_device_resume(struct hl_device *hdev);
3694 int hl_device_reset(struct hl_device *hdev, u32 flags);
3695 int hl_device_cond_reset(struct hl_device *hdev, u32 flags, u64 event_mask);
3696 void hl_hpriv_get(struct hl_fpriv *hpriv);
3697 int hl_hpriv_put(struct hl_fpriv *hpriv);
3698 int hl_device_utilization(struct hl_device *hdev, u32 *utilization);
3699 
3700 int hl_build_hwmon_channel_info(struct hl_device *hdev,
3701 		struct cpucp_sensor *sensors_arr);
3702 
3703 void hl_notifier_event_send_all(struct hl_device *hdev, u64 event_mask);
3704 
3705 int hl_sysfs_init(struct hl_device *hdev);
3706 void hl_sysfs_fini(struct hl_device *hdev);
3707 
3708 int hl_hwmon_init(struct hl_device *hdev);
3709 void hl_hwmon_fini(struct hl_device *hdev);
3710 void hl_hwmon_release_resources(struct hl_device *hdev);
3711 
3712 int hl_cb_create(struct hl_device *hdev, struct hl_mem_mgr *mmg,
3713 			struct hl_ctx *ctx, u32 cb_size, bool internal_cb,
3714 			bool map_cb, u64 *handle);
3715 int hl_cb_destroy(struct hl_mem_mgr *mmg, u64 cb_handle);
3716 int hl_hw_block_mmap(struct hl_fpriv *hpriv, struct vm_area_struct *vma);
3717 struct hl_cb *hl_cb_get(struct hl_mem_mgr *mmg, u64 handle);
3718 void hl_cb_put(struct hl_cb *cb);
3719 struct hl_cb *hl_cb_kernel_create(struct hl_device *hdev, u32 cb_size,
3720 					bool internal_cb);
3721 int hl_cb_pool_init(struct hl_device *hdev);
3722 int hl_cb_pool_fini(struct hl_device *hdev);
3723 int hl_cb_va_pool_init(struct hl_ctx *ctx);
3724 void hl_cb_va_pool_fini(struct hl_ctx *ctx);
3725 
3726 void hl_cs_rollback_all(struct hl_device *hdev, bool skip_wq_flush);
3727 struct hl_cs_job *hl_cs_allocate_job(struct hl_device *hdev,
3728 		enum hl_queue_type queue_type, bool is_kernel_allocated_cb);
3729 void hl_sob_reset_error(struct kref *ref);
3730 int hl_gen_sob_mask(u16 sob_base, u8 sob_mask, u8 *mask);
3731 void hl_fence_put(struct hl_fence *fence);
3732 void hl_fences_put(struct hl_fence **fence, int len);
3733 void hl_fence_get(struct hl_fence *fence);
3734 void cs_get(struct hl_cs *cs);
3735 bool cs_needs_completion(struct hl_cs *cs);
3736 bool cs_needs_timeout(struct hl_cs *cs);
3737 bool is_staged_cs_last_exists(struct hl_device *hdev, struct hl_cs *cs);
3738 struct hl_cs *hl_staged_cs_find_first(struct hl_device *hdev, u64 cs_seq);
3739 void hl_multi_cs_completion_init(struct hl_device *hdev);
3740 u32 hl_get_active_cs_num(struct hl_device *hdev);
3741 
3742 void goya_set_asic_funcs(struct hl_device *hdev);
3743 void gaudi_set_asic_funcs(struct hl_device *hdev);
3744 void gaudi2_set_asic_funcs(struct hl_device *hdev);
3745 
3746 int hl_vm_ctx_init(struct hl_ctx *ctx);
3747 void hl_vm_ctx_fini(struct hl_ctx *ctx);
3748 
3749 int hl_vm_init(struct hl_device *hdev);
3750 void hl_vm_fini(struct hl_device *hdev);
3751 
3752 void hl_hw_block_mem_init(struct hl_ctx *ctx);
3753 void hl_hw_block_mem_fini(struct hl_ctx *ctx);
3754 
3755 u64 hl_reserve_va_block(struct hl_device *hdev, struct hl_ctx *ctx,
3756 		enum hl_va_range_type type, u64 size, u32 alignment);
3757 int hl_unreserve_va_block(struct hl_device *hdev, struct hl_ctx *ctx,
3758 		u64 start_addr, u64 size);
3759 int hl_pin_host_memory(struct hl_device *hdev, u64 addr, u64 size,
3760 			struct hl_userptr *userptr);
3761 void hl_unpin_host_memory(struct hl_device *hdev, struct hl_userptr *userptr);
3762 void hl_userptr_delete_list(struct hl_device *hdev,
3763 				struct list_head *userptr_list);
3764 bool hl_userptr_is_pinned(struct hl_device *hdev, u64 addr, u32 size,
3765 				struct list_head *userptr_list,
3766 				struct hl_userptr **userptr);
3767 
3768 int hl_mmu_init(struct hl_device *hdev);
3769 void hl_mmu_fini(struct hl_device *hdev);
3770 int hl_mmu_ctx_init(struct hl_ctx *ctx);
3771 void hl_mmu_ctx_fini(struct hl_ctx *ctx);
3772 int hl_mmu_map_page(struct hl_ctx *ctx, u64 virt_addr, u64 phys_addr,
3773 		u32 page_size, bool flush_pte);
3774 int hl_mmu_get_real_page_size(struct hl_device *hdev, struct hl_mmu_properties *mmu_prop,
3775 				u32 page_size, u32 *real_page_size, bool is_dram_addr);
3776 int hl_mmu_unmap_page(struct hl_ctx *ctx, u64 virt_addr, u32 page_size,
3777 		bool flush_pte);
3778 int hl_mmu_map_contiguous(struct hl_ctx *ctx, u64 virt_addr,
3779 					u64 phys_addr, u32 size);
3780 int hl_mmu_unmap_contiguous(struct hl_ctx *ctx, u64 virt_addr, u32 size);
3781 int hl_mmu_invalidate_cache(struct hl_device *hdev, bool is_hard, u32 flags);
3782 int hl_mmu_invalidate_cache_range(struct hl_device *hdev, bool is_hard,
3783 					u32 flags, u32 asid, u64 va, u64 size);
3784 int hl_mmu_prefetch_cache_range(struct hl_ctx *ctx, u32 flags, u32 asid, u64 va, u64 size);
3785 u64 hl_mmu_get_next_hop_addr(struct hl_ctx *ctx, u64 curr_pte);
3786 u64 hl_mmu_get_hop_pte_phys_addr(struct hl_ctx *ctx, struct hl_mmu_properties *mmu_prop,
3787 					u8 hop_idx, u64 hop_addr, u64 virt_addr);
3788 void hl_mmu_hr_flush(struct hl_ctx *ctx);
3789 int hl_mmu_hr_init(struct hl_device *hdev, struct hl_mmu_hr_priv *hr_priv, u32 hop_table_size,
3790 			u64 pgt_size);
3791 void hl_mmu_hr_fini(struct hl_device *hdev, struct hl_mmu_hr_priv *hr_priv, u32 hop_table_size);
3792 void hl_mmu_hr_free_hop_remove_pgt(struct pgt_info *pgt_info, struct hl_mmu_hr_priv *hr_priv,
3793 				u32 hop_table_size);
3794 u64 hl_mmu_hr_pte_phys_to_virt(struct hl_ctx *ctx, struct pgt_info *pgt, u64 phys_pte_addr,
3795 							u32 hop_table_size);
3796 void hl_mmu_hr_write_pte(struct hl_ctx *ctx, struct pgt_info *pgt_info, u64 phys_pte_addr,
3797 							u64 val, u32 hop_table_size);
3798 void hl_mmu_hr_clear_pte(struct hl_ctx *ctx, struct pgt_info *pgt_info, u64 phys_pte_addr,
3799 							u32 hop_table_size);
3800 int hl_mmu_hr_put_pte(struct hl_ctx *ctx, struct pgt_info *pgt_info, struct hl_mmu_hr_priv *hr_priv,
3801 							u32 hop_table_size);
3802 void hl_mmu_hr_get_pte(struct hl_ctx *ctx, struct hl_hr_mmu_funcs *hr_func, u64 phys_hop_addr);
3803 struct pgt_info *hl_mmu_hr_get_next_hop_pgt_info(struct hl_ctx *ctx,
3804 							struct hl_hr_mmu_funcs *hr_func,
3805 							u64 curr_pte);
3806 struct pgt_info *hl_mmu_hr_alloc_hop(struct hl_ctx *ctx, struct hl_mmu_hr_priv *hr_priv,
3807 							struct hl_hr_mmu_funcs *hr_func,
3808 							struct hl_mmu_properties *mmu_prop);
3809 struct pgt_info *hl_mmu_hr_get_alloc_next_hop(struct hl_ctx *ctx,
3810 							struct hl_mmu_hr_priv *hr_priv,
3811 							struct hl_hr_mmu_funcs *hr_func,
3812 							struct hl_mmu_properties *mmu_prop,
3813 							u64 curr_pte, bool *is_new_hop);
3814 int hl_mmu_hr_get_tlb_info(struct hl_ctx *ctx, u64 virt_addr, struct hl_mmu_hop_info *hops,
3815 							struct hl_hr_mmu_funcs *hr_func);
3816 void hl_mmu_swap_out(struct hl_ctx *ctx);
3817 void hl_mmu_swap_in(struct hl_ctx *ctx);
3818 int hl_mmu_if_set_funcs(struct hl_device *hdev);
3819 void hl_mmu_v1_set_funcs(struct hl_device *hdev, struct hl_mmu_funcs *mmu);
3820 void hl_mmu_v2_hr_set_funcs(struct hl_device *hdev, struct hl_mmu_funcs *mmu);
3821 int hl_mmu_va_to_pa(struct hl_ctx *ctx, u64 virt_addr, u64 *phys_addr);
3822 int hl_mmu_get_tlb_info(struct hl_ctx *ctx, u64 virt_addr,
3823 			struct hl_mmu_hop_info *hops);
3824 u64 hl_mmu_scramble_addr(struct hl_device *hdev, u64 addr);
3825 u64 hl_mmu_descramble_addr(struct hl_device *hdev, u64 addr);
3826 bool hl_is_dram_va(struct hl_device *hdev, u64 virt_addr);
3827 
3828 int hl_fw_load_fw_to_device(struct hl_device *hdev, const char *fw_name,
3829 				void __iomem *dst, u32 src_offset, u32 size);
3830 int hl_fw_send_pci_access_msg(struct hl_device *hdev, u32 opcode, u64 value);
3831 int hl_fw_send_cpu_message(struct hl_device *hdev, u32 hw_queue_id, u32 *msg,
3832 				u16 len, u32 timeout, u64 *result);
3833 int hl_fw_unmask_irq(struct hl_device *hdev, u16 event_type);
3834 int hl_fw_unmask_irq_arr(struct hl_device *hdev, const u32 *irq_arr,
3835 		size_t irq_arr_size);
3836 int hl_fw_test_cpu_queue(struct hl_device *hdev);
3837 void *hl_fw_cpu_accessible_dma_pool_alloc(struct hl_device *hdev, size_t size,
3838 						dma_addr_t *dma_handle);
3839 void hl_fw_cpu_accessible_dma_pool_free(struct hl_device *hdev, size_t size,
3840 					void *vaddr);
3841 int hl_fw_send_heartbeat(struct hl_device *hdev);
3842 int hl_fw_cpucp_info_get(struct hl_device *hdev,
3843 				u32 sts_boot_dev_sts0_reg,
3844 				u32 sts_boot_dev_sts1_reg, u32 boot_err0_reg,
3845 				u32 boot_err1_reg);
3846 int hl_fw_cpucp_handshake(struct hl_device *hdev,
3847 				u32 sts_boot_dev_sts0_reg,
3848 				u32 sts_boot_dev_sts1_reg, u32 boot_err0_reg,
3849 				u32 boot_err1_reg);
3850 int hl_fw_get_eeprom_data(struct hl_device *hdev, void *data, size_t max_size);
3851 int hl_fw_get_monitor_dump(struct hl_device *hdev, void *data);
3852 int hl_fw_cpucp_pci_counters_get(struct hl_device *hdev,
3853 		struct hl_info_pci_counters *counters);
3854 int hl_fw_cpucp_total_energy_get(struct hl_device *hdev,
3855 			u64 *total_energy);
3856 int get_used_pll_index(struct hl_device *hdev, u32 input_pll_index,
3857 						enum pll_index *pll_index);
3858 int hl_fw_cpucp_pll_info_get(struct hl_device *hdev, u32 pll_index,
3859 		u16 *pll_freq_arr);
3860 int hl_fw_cpucp_power_get(struct hl_device *hdev, u64 *power);
3861 void hl_fw_ask_hard_reset_without_linux(struct hl_device *hdev);
3862 void hl_fw_ask_halt_machine_without_linux(struct hl_device *hdev);
3863 int hl_fw_init_cpu(struct hl_device *hdev);
3864 int hl_fw_wait_preboot_ready(struct hl_device *hdev);
3865 int hl_fw_read_preboot_status(struct hl_device *hdev);
3866 int hl_fw_dynamic_send_protocol_cmd(struct hl_device *hdev,
3867 				struct fw_load_mgr *fw_loader,
3868 				enum comms_cmd cmd, unsigned int size,
3869 				bool wait_ok, u32 timeout);
3870 int hl_fw_dram_replaced_row_get(struct hl_device *hdev,
3871 				struct cpucp_hbm_row_info *info);
3872 int hl_fw_dram_pending_row_get(struct hl_device *hdev, u32 *pend_rows_num);
3873 int hl_fw_cpucp_engine_core_asid_set(struct hl_device *hdev, u32 asid);
3874 int hl_fw_send_device_activity(struct hl_device *hdev, bool open);
3875 int hl_pci_bars_map(struct hl_device *hdev, const char * const name[3],
3876 			bool is_wc[3]);
3877 int hl_pci_elbi_read(struct hl_device *hdev, u64 addr, u32 *data);
3878 int hl_pci_iatu_write(struct hl_device *hdev, u32 addr, u32 data);
3879 int hl_pci_set_inbound_region(struct hl_device *hdev, u8 region,
3880 		struct hl_inbound_pci_region *pci_region);
3881 int hl_pci_set_outbound_region(struct hl_device *hdev,
3882 		struct hl_outbound_pci_region *pci_region);
3883 enum pci_region hl_get_pci_memory_region(struct hl_device *hdev, u64 addr);
3884 int hl_pci_init(struct hl_device *hdev);
3885 void hl_pci_fini(struct hl_device *hdev);
3886 
3887 long hl_fw_get_frequency(struct hl_device *hdev, u32 pll_index, bool curr);
3888 void hl_fw_set_frequency(struct hl_device *hdev, u32 pll_index, u64 freq);
3889 int hl_get_temperature(struct hl_device *hdev, int sensor_index, u32 attr, long *value);
3890 int hl_set_temperature(struct hl_device *hdev, int sensor_index, u32 attr, long value);
3891 int hl_get_voltage(struct hl_device *hdev, int sensor_index, u32 attr, long *value);
3892 int hl_get_current(struct hl_device *hdev, int sensor_index, u32 attr, long *value);
3893 int hl_get_fan_speed(struct hl_device *hdev, int sensor_index, u32 attr, long *value);
3894 int hl_get_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr, long *value);
3895 void hl_set_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr, long value);
3896 long hl_fw_get_max_power(struct hl_device *hdev);
3897 void hl_fw_set_max_power(struct hl_device *hdev);
3898 int hl_fw_get_sec_attest_info(struct hl_device *hdev, struct cpucp_sec_attest_info *sec_attest_info,
3899 				u32 nonce);
3900 int hl_set_voltage(struct hl_device *hdev, int sensor_index, u32 attr, long value);
3901 int hl_set_current(struct hl_device *hdev, int sensor_index, u32 attr, long value);
3902 int hl_set_power(struct hl_device *hdev, int sensor_index, u32 attr, long value);
3903 int hl_get_power(struct hl_device *hdev, int sensor_index, u32 attr, long *value);
3904 int hl_fw_get_clk_rate(struct hl_device *hdev, u32 *cur_clk, u32 *max_clk);
3905 void hl_fw_set_pll_profile(struct hl_device *hdev);
3906 void hl_sysfs_add_dev_clk_attr(struct hl_device *hdev, struct attribute_group *dev_clk_attr_grp);
3907 void hl_sysfs_add_dev_vrm_attr(struct hl_device *hdev, struct attribute_group *dev_vrm_attr_grp);
3908 int hl_fw_send_generic_request(struct hl_device *hdev, enum hl_passthrough_type sub_opcode,
3909 						dma_addr_t buff, u32 *size);
3910 
3911 void hw_sob_get(struct hl_hw_sob *hw_sob);
3912 void hw_sob_put(struct hl_hw_sob *hw_sob);
3913 void hl_encaps_release_handle_and_put_ctx(struct kref *ref);
3914 void hl_encaps_release_handle_and_put_sob_ctx(struct kref *ref);
3915 void hl_hw_queue_encaps_sig_set_sob_info(struct hl_device *hdev,
3916 			struct hl_cs *cs, struct hl_cs_job *job,
3917 			struct hl_cs_compl *cs_cmpl);
3918 
3919 int hl_dec_init(struct hl_device *hdev);
3920 void hl_dec_fini(struct hl_device *hdev);
3921 void hl_dec_ctx_fini(struct hl_ctx *ctx);
3922 
3923 void hl_release_pending_user_interrupts(struct hl_device *hdev);
3924 void hl_abort_waitings_for_completion(struct hl_device *hdev);
3925 int hl_cs_signal_sob_wraparound_handler(struct hl_device *hdev, u32 q_idx,
3926 			struct hl_hw_sob **hw_sob, u32 count, bool encaps_sig);
3927 
3928 int hl_state_dump(struct hl_device *hdev);
3929 const char *hl_state_dump_get_sync_name(struct hl_device *hdev, u32 sync_id);
3930 const char *hl_state_dump_get_monitor_name(struct hl_device *hdev,
3931 					struct hl_mon_state_dump *mon);
3932 void hl_state_dump_free_sync_to_engine_map(struct hl_sync_to_engine_map *map);
3933 __printf(4, 5) int hl_snprintf_resize(char **buf, size_t *size, size_t *offset,
3934 					const char *format, ...);
3935 char *hl_format_as_binary(char *buf, size_t buf_len, u32 n);
3936 const char *hl_sync_engine_to_string(enum hl_sync_engine_type engine_type);
3937 
3938 void hl_mem_mgr_init(struct device *dev, struct hl_mem_mgr *mmg);
3939 void hl_mem_mgr_fini(struct hl_mem_mgr *mmg);
3940 void hl_mem_mgr_idr_destroy(struct hl_mem_mgr *mmg);
3941 int hl_mem_mgr_mmap(struct hl_mem_mgr *mmg, struct vm_area_struct *vma,
3942 		    void *args);
3943 struct hl_mmap_mem_buf *hl_mmap_mem_buf_get(struct hl_mem_mgr *mmg,
3944 						   u64 handle);
3945 int hl_mmap_mem_buf_put_handle(struct hl_mem_mgr *mmg, u64 handle);
3946 int hl_mmap_mem_buf_put(struct hl_mmap_mem_buf *buf);
3947 struct hl_mmap_mem_buf *
3948 hl_mmap_mem_buf_alloc(struct hl_mem_mgr *mmg,
3949 		      struct hl_mmap_mem_buf_behavior *behavior, gfp_t gfp,
3950 		      void *args);
3951 __printf(2, 3) void hl_engine_data_sprintf(struct engines_data *e, const char *fmt, ...);
3952 void hl_capture_razwi(struct hl_device *hdev, u64 addr, u16 *engine_id, u16 num_of_engines,
3953 			u8 flags);
3954 void hl_handle_razwi(struct hl_device *hdev, u64 addr, u16 *engine_id, u16 num_of_engines,
3955 			u8 flags, u64 *event_mask);
3956 void hl_capture_page_fault(struct hl_device *hdev, u64 addr, u16 eng_id, bool is_pmmu);
3957 void hl_handle_page_fault(struct hl_device *hdev, u64 addr, u16 eng_id, bool is_pmmu,
3958 				u64 *event_mask);
3959 void hl_handle_critical_hw_err(struct hl_device *hdev, u16 event_id, u64 *event_mask);
3960 void hl_handle_fw_err(struct hl_device *hdev, struct hl_info_fw_err_info *info);
3961 
3962 #ifdef CONFIG_DEBUG_FS
3963 
3964 void hl_debugfs_init(void);
3965 void hl_debugfs_fini(void);
3966 void hl_debugfs_add_device(struct hl_device *hdev);
3967 void hl_debugfs_remove_device(struct hl_device *hdev);
3968 void hl_debugfs_add_file(struct hl_fpriv *hpriv);
3969 void hl_debugfs_remove_file(struct hl_fpriv *hpriv);
3970 void hl_debugfs_add_cb(struct hl_cb *cb);
3971 void hl_debugfs_remove_cb(struct hl_cb *cb);
3972 void hl_debugfs_add_cs(struct hl_cs *cs);
3973 void hl_debugfs_remove_cs(struct hl_cs *cs);
3974 void hl_debugfs_add_job(struct hl_device *hdev, struct hl_cs_job *job);
3975 void hl_debugfs_remove_job(struct hl_device *hdev, struct hl_cs_job *job);
3976 void hl_debugfs_add_userptr(struct hl_device *hdev, struct hl_userptr *userptr);
3977 void hl_debugfs_remove_userptr(struct hl_device *hdev,
3978 				struct hl_userptr *userptr);
3979 void hl_debugfs_add_ctx_mem_hash(struct hl_device *hdev, struct hl_ctx *ctx);
3980 void hl_debugfs_remove_ctx_mem_hash(struct hl_device *hdev, struct hl_ctx *ctx);
3981 void hl_debugfs_set_state_dump(struct hl_device *hdev, char *data,
3982 					unsigned long length);
3983 
3984 #else
3985 
3986 static inline void __init hl_debugfs_init(void)
3987 {
3988 }
3989 
3990 static inline void hl_debugfs_fini(void)
3991 {
3992 }
3993 
3994 static inline void hl_debugfs_add_device(struct hl_device *hdev)
3995 {
3996 }
3997 
3998 static inline void hl_debugfs_remove_device(struct hl_device *hdev)
3999 {
4000 }
4001 
4002 static inline void hl_debugfs_add_file(struct hl_fpriv *hpriv)
4003 {
4004 }
4005 
4006 static inline void hl_debugfs_remove_file(struct hl_fpriv *hpriv)
4007 {
4008 }
4009 
4010 static inline void hl_debugfs_add_cb(struct hl_cb *cb)
4011 {
4012 }
4013 
4014 static inline void hl_debugfs_remove_cb(struct hl_cb *cb)
4015 {
4016 }
4017 
4018 static inline void hl_debugfs_add_cs(struct hl_cs *cs)
4019 {
4020 }
4021 
4022 static inline void hl_debugfs_remove_cs(struct hl_cs *cs)
4023 {
4024 }
4025 
4026 static inline void hl_debugfs_add_job(struct hl_device *hdev,
4027 					struct hl_cs_job *job)
4028 {
4029 }
4030 
4031 static inline void hl_debugfs_remove_job(struct hl_device *hdev,
4032 					struct hl_cs_job *job)
4033 {
4034 }
4035 
4036 static inline void hl_debugfs_add_userptr(struct hl_device *hdev,
4037 					struct hl_userptr *userptr)
4038 {
4039 }
4040 
4041 static inline void hl_debugfs_remove_userptr(struct hl_device *hdev,
4042 					struct hl_userptr *userptr)
4043 {
4044 }
4045 
4046 static inline void hl_debugfs_add_ctx_mem_hash(struct hl_device *hdev,
4047 					struct hl_ctx *ctx)
4048 {
4049 }
4050 
4051 static inline void hl_debugfs_remove_ctx_mem_hash(struct hl_device *hdev,
4052 					struct hl_ctx *ctx)
4053 {
4054 }
4055 
4056 static inline void hl_debugfs_set_state_dump(struct hl_device *hdev,
4057 					char *data, unsigned long length)
4058 {
4059 }
4060 
4061 #endif
4062 
4063 /* Security */
4064 int hl_unsecure_register(struct hl_device *hdev, u32 mm_reg_addr, int offset,
4065 		const u32 pb_blocks[], struct hl_block_glbl_sec sgs_array[],
4066 		int array_size);
4067 int hl_unsecure_registers(struct hl_device *hdev, const u32 mm_reg_array[],
4068 		int mm_array_size, int offset, const u32 pb_blocks[],
4069 		struct hl_block_glbl_sec sgs_array[], int blocks_array_size);
4070 void hl_config_glbl_sec(struct hl_device *hdev, const u32 pb_blocks[],
4071 		struct hl_block_glbl_sec sgs_array[], u32 block_offset,
4072 		int array_size);
4073 void hl_secure_block(struct hl_device *hdev,
4074 		struct hl_block_glbl_sec sgs_array[], int array_size);
4075 int hl_init_pb_with_mask(struct hl_device *hdev, u32 num_dcores,
4076 		u32 dcore_offset, u32 num_instances, u32 instance_offset,
4077 		const u32 pb_blocks[], u32 blocks_array_size,
4078 		const u32 *regs_array, u32 regs_array_size, u64 mask);
4079 int hl_init_pb(struct hl_device *hdev, u32 num_dcores, u32 dcore_offset,
4080 		u32 num_instances, u32 instance_offset,
4081 		const u32 pb_blocks[], u32 blocks_array_size,
4082 		const u32 *regs_array, u32 regs_array_size);
4083 int hl_init_pb_ranges_with_mask(struct hl_device *hdev, u32 num_dcores,
4084 		u32 dcore_offset, u32 num_instances, u32 instance_offset,
4085 		const u32 pb_blocks[], u32 blocks_array_size,
4086 		const struct range *regs_range_array, u32 regs_range_array_size,
4087 		u64 mask);
4088 int hl_init_pb_ranges(struct hl_device *hdev, u32 num_dcores,
4089 		u32 dcore_offset, u32 num_instances, u32 instance_offset,
4090 		const u32 pb_blocks[], u32 blocks_array_size,
4091 		const struct range *regs_range_array,
4092 		u32 regs_range_array_size);
4093 int hl_init_pb_single_dcore(struct hl_device *hdev, u32 dcore_offset,
4094 		u32 num_instances, u32 instance_offset,
4095 		const u32 pb_blocks[], u32 blocks_array_size,
4096 		const u32 *regs_array, u32 regs_array_size);
4097 int hl_init_pb_ranges_single_dcore(struct hl_device *hdev, u32 dcore_offset,
4098 		u32 num_instances, u32 instance_offset,
4099 		const u32 pb_blocks[], u32 blocks_array_size,
4100 		const struct range *regs_range_array,
4101 		u32 regs_range_array_size);
4102 void hl_ack_pb(struct hl_device *hdev, u32 num_dcores, u32 dcore_offset,
4103 		u32 num_instances, u32 instance_offset,
4104 		const u32 pb_blocks[], u32 blocks_array_size);
4105 void hl_ack_pb_with_mask(struct hl_device *hdev, u32 num_dcores,
4106 		u32 dcore_offset, u32 num_instances, u32 instance_offset,
4107 		const u32 pb_blocks[], u32 blocks_array_size, u64 mask);
4108 void hl_ack_pb_single_dcore(struct hl_device *hdev, u32 dcore_offset,
4109 		u32 num_instances, u32 instance_offset,
4110 		const u32 pb_blocks[], u32 blocks_array_size);
4111 
4112 /* IOCTLs */
4113 long hl_ioctl(struct file *filep, unsigned int cmd, unsigned long arg);
4114 long hl_ioctl_control(struct file *filep, unsigned int cmd, unsigned long arg);
4115 int hl_cb_ioctl(struct hl_fpriv *hpriv, void *data);
4116 int hl_cs_ioctl(struct hl_fpriv *hpriv, void *data);
4117 int hl_wait_ioctl(struct hl_fpriv *hpriv, void *data);
4118 int hl_mem_ioctl(struct hl_fpriv *hpriv, void *data);
4119 
4120 #endif /* HABANALABSP_H_ */
4121