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