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