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