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