1 /* SPDX-License-Identifier: GPL-2.0
2  *
3  * Copyright 2016-2019 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/bitfield.h>
25 #include <linux/genalloc.h>
26 #include <linux/sched/signal.h>
27 #include <linux/io-64-nonatomic-lo-hi.h>
28 #include <linux/coresight.h>
29 
30 #define HL_NAME				"habanalabs"
31 
32 /* Use upper bits of mmap offset to store habana driver specific information.
33  * bits[63:61] - Encode mmap type
34  * bits[45:0]  - mmap offset value
35  *
36  * NOTE: struct vm_area_struct.vm_pgoff uses offset in pages. Hence, these
37  *  defines are w.r.t to PAGE_SIZE
38  */
39 #define HL_MMAP_TYPE_SHIFT		(61 - PAGE_SHIFT)
40 #define HL_MMAP_TYPE_MASK		(0x7ull << HL_MMAP_TYPE_SHIFT)
41 #define HL_MMAP_TYPE_BLOCK		(0x4ull << HL_MMAP_TYPE_SHIFT)
42 #define HL_MMAP_TYPE_CB			(0x2ull << HL_MMAP_TYPE_SHIFT)
43 
44 #define HL_MMAP_OFFSET_VALUE_MASK	(0x1FFFFFFFFFFFull >> PAGE_SHIFT)
45 #define HL_MMAP_OFFSET_VALUE_GET(off)	(off & HL_MMAP_OFFSET_VALUE_MASK)
46 
47 #define HL_PENDING_RESET_PER_SEC	10
48 #define HL_PENDING_RESET_MAX_TRIALS	60 /* 10 minutes */
49 #define HL_PENDING_RESET_LONG_SEC	60
50 
51 #define HL_HARD_RESET_MAX_TIMEOUT	120
52 #define HL_PLDM_HARD_RESET_MAX_TIMEOUT	(HL_HARD_RESET_MAX_TIMEOUT * 3)
53 
54 #define HL_DEVICE_TIMEOUT_USEC		1000000 /* 1 s */
55 
56 #define HL_HEARTBEAT_PER_USEC		5000000 /* 5 s */
57 
58 #define HL_PLL_LOW_JOB_FREQ_USEC	5000000 /* 5 s */
59 
60 #define HL_CPUCP_INFO_TIMEOUT_USEC	10000000 /* 10s */
61 #define HL_CPUCP_EEPROM_TIMEOUT_USEC	10000000 /* 10s */
62 
63 #define HL_PCI_ELBI_TIMEOUT_MSEC	10 /* 10ms */
64 
65 #define HL_SIM_MAX_TIMEOUT_US		10000000 /* 10s */
66 
67 #define HL_COMMON_USER_INTERRUPT_ID	0xFFF
68 
69 #define HL_STATE_DUMP_HIST_LEN		5
70 
71 #define OBJ_NAMES_HASH_TABLE_BITS	7 /* 1 << 7 buckets */
72 #define SYNC_TO_ENGINE_HASH_TABLE_BITS	7 /* 1 << 7 buckets */
73 
74 /* Memory */
75 #define MEM_HASH_TABLE_BITS		7 /* 1 << 7 buckets */
76 
77 /* MMU */
78 #define MMU_HASH_TABLE_BITS		7 /* 1 << 7 buckets */
79 
80 /**
81  * enum hl_mmu_page_table_locaion - mmu page table location
82  * @MMU_DR_PGT: page-table is located on device DRAM.
83  * @MMU_HR_PGT: page-table is located on host memory.
84  * @MMU_NUM_PGT_LOCATIONS: number of page-table locations currently supported.
85  */
86 enum hl_mmu_page_table_location {
87 	MMU_DR_PGT = 0,		/* device-dram-resident MMU PGT */
88 	MMU_HR_PGT,		/* host resident MMU PGT */
89 	MMU_NUM_PGT_LOCATIONS	/* num of PGT locations */
90 };
91 
92 /*
93  * HL_RSVD_SOBS 'sync stream' reserved sync objects per QMAN stream
94  * HL_RSVD_MONS 'sync stream' reserved monitors per QMAN stream
95  */
96 #define HL_RSVD_SOBS			2
97 #define HL_RSVD_MONS			1
98 
99 /*
100  * HL_COLLECTIVE_RSVD_MSTR_MONS 'collective' reserved monitors per QMAN stream
101  */
102 #define HL_COLLECTIVE_RSVD_MSTR_MONS	2
103 
104 #define HL_MAX_SOB_VAL			(1 << 15)
105 
106 #define IS_POWER_OF_2(n)		(n != 0 && ((n & (n - 1)) == 0))
107 #define IS_MAX_PENDING_CS_VALID(n)	(IS_POWER_OF_2(n) && (n > 1))
108 
109 #define HL_PCI_NUM_BARS			6
110 
111 #define HL_MAX_DCORES			4
112 
113 /*
114  * Reset Flags
115  *
116  * - HL_RESET_HARD
117  *       If set do hard reset to all engines. If not set reset just
118  *       compute/DMA engines.
119  *
120  * - HL_RESET_FROM_RESET_THREAD
121  *       Set if the caller is the hard-reset thread
122  *
123  * - HL_RESET_HEARTBEAT
124  *       Set if reset is due to heartbeat
125  *
126  * - HL_RESET_TDR
127  *       Set if reset is due to TDR
128  *
129  * - HL_RESET_DEVICE_RELEASE
130  *       Set if reset is due to device release
131  *
132  * - HL_RESET_FW
133  *       F/W will perform the reset. No need to ask it to reset the device. This is relevant
134  *       only when running with secured f/w
135  */
136 #define HL_RESET_HARD			(1 << 0)
137 #define HL_RESET_FROM_RESET_THREAD	(1 << 1)
138 #define HL_RESET_HEARTBEAT		(1 << 2)
139 #define HL_RESET_TDR			(1 << 3)
140 #define HL_RESET_DEVICE_RELEASE		(1 << 4)
141 #define HL_RESET_FW			(1 << 5)
142 
143 #define HL_MAX_SOBS_PER_MONITOR	8
144 
145 /**
146  * struct hl_gen_wait_properties - properties for generating a wait CB
147  * @data: command buffer
148  * @q_idx: queue id is used to extract fence register address
149  * @size: offset in command buffer
150  * @sob_base: SOB base to use in this wait CB
151  * @sob_val: SOB value to wait for
152  * @mon_id: monitor to use in this wait CB
153  * @sob_mask: each bit represents a SOB offset from sob_base to be used
154  */
155 struct hl_gen_wait_properties {
156 	void	*data;
157 	u32	q_idx;
158 	u32	size;
159 	u16	sob_base;
160 	u16	sob_val;
161 	u16	mon_id;
162 	u8	sob_mask;
163 };
164 
165 /**
166  * struct pgt_info - MMU hop page info.
167  * @node: hash linked-list node for the pgts shadow hash of pgts.
168  * @phys_addr: physical address of the pgt.
169  * @shadow_addr: shadow hop in the host.
170  * @ctx: pointer to the owner ctx.
171  * @num_of_ptes: indicates how many ptes are used in the pgt.
172  *
173  * The MMU page tables hierarchy is placed on the DRAM. When a new level (hop)
174  * is needed during mapping, a new page is allocated and this structure holds
175  * its essential information. During unmapping, if no valid PTEs remained in the
176  * page, it is freed with its pgt_info structure.
177  */
178 struct pgt_info {
179 	struct hlist_node	node;
180 	u64			phys_addr;
181 	u64			shadow_addr;
182 	struct hl_ctx		*ctx;
183 	int			num_of_ptes;
184 };
185 
186 struct hl_device;
187 struct hl_fpriv;
188 
189 /**
190  * enum hl_pci_match_mode - pci match mode per region
191  * @PCI_ADDRESS_MATCH_MODE: address match mode
192  * @PCI_BAR_MATCH_MODE: bar match mode
193  */
194 enum hl_pci_match_mode {
195 	PCI_ADDRESS_MATCH_MODE,
196 	PCI_BAR_MATCH_MODE
197 };
198 
199 /**
200  * enum hl_fw_component - F/W components to read version through registers.
201  * @FW_COMP_BOOT_FIT: boot fit.
202  * @FW_COMP_PREBOOT: preboot.
203  * @FW_COMP_LINUX: linux.
204  */
205 enum hl_fw_component {
206 	FW_COMP_BOOT_FIT,
207 	FW_COMP_PREBOOT,
208 	FW_COMP_LINUX,
209 };
210 
211 /**
212  * enum hl_fw_types - F/W types present in the system
213  * @FW_TYPE_LINUX: Linux image for device CPU
214  * @FW_TYPE_BOOT_CPU: Boot image for device CPU
215  * @FW_TYPE_PREBOOT_CPU: Indicates pre-loaded CPUs are present in the system
216  *                       (preboot, ppboot etc...)
217  * @FW_TYPE_ALL_TYPES: Mask for all types
218  */
219 enum hl_fw_types {
220 	FW_TYPE_LINUX = 0x1,
221 	FW_TYPE_BOOT_CPU = 0x2,
222 	FW_TYPE_PREBOOT_CPU = 0x4,
223 	FW_TYPE_ALL_TYPES =
224 		(FW_TYPE_LINUX | FW_TYPE_BOOT_CPU | FW_TYPE_PREBOOT_CPU)
225 };
226 
227 /**
228  * enum hl_queue_type - Supported QUEUE types.
229  * @QUEUE_TYPE_NA: queue is not available.
230  * @QUEUE_TYPE_EXT: external queue which is a DMA channel that may access the
231  *                  host.
232  * @QUEUE_TYPE_INT: internal queue that performs DMA inside the device's
233  *			memories and/or operates the compute engines.
234  * @QUEUE_TYPE_CPU: S/W queue for communication with the device's CPU.
235  * @QUEUE_TYPE_HW: queue of DMA and compute engines jobs, for which completion
236  *                 notifications are sent by H/W.
237  */
238 enum hl_queue_type {
239 	QUEUE_TYPE_NA,
240 	QUEUE_TYPE_EXT,
241 	QUEUE_TYPE_INT,
242 	QUEUE_TYPE_CPU,
243 	QUEUE_TYPE_HW
244 };
245 
246 enum hl_cs_type {
247 	CS_TYPE_DEFAULT,
248 	CS_TYPE_SIGNAL,
249 	CS_TYPE_WAIT,
250 	CS_TYPE_COLLECTIVE_WAIT,
251 	CS_RESERVE_SIGNALS,
252 	CS_UNRESERVE_SIGNALS
253 };
254 
255 /*
256  * struct hl_inbound_pci_region - inbound region descriptor
257  * @mode: pci match mode for this region
258  * @addr: region target address
259  * @size: region size in bytes
260  * @offset_in_bar: offset within bar (address match mode)
261  * @bar: bar id
262  */
263 struct hl_inbound_pci_region {
264 	enum hl_pci_match_mode	mode;
265 	u64			addr;
266 	u64			size;
267 	u64			offset_in_bar;
268 	u8			bar;
269 };
270 
271 /*
272  * struct hl_outbound_pci_region - outbound region descriptor
273  * @addr: region target address
274  * @size: region size in bytes
275  */
276 struct hl_outbound_pci_region {
277 	u64	addr;
278 	u64	size;
279 };
280 
281 /*
282  * enum queue_cb_alloc_flags - Indicates queue support for CBs that
283  * allocated by Kernel or by User
284  * @CB_ALLOC_KERNEL: support only CBs that allocated by Kernel
285  * @CB_ALLOC_USER: support only CBs that allocated by User
286  */
287 enum queue_cb_alloc_flags {
288 	CB_ALLOC_KERNEL = 0x1,
289 	CB_ALLOC_USER   = 0x2
290 };
291 
292 /*
293  * struct hl_hw_sob - H/W SOB info.
294  * @hdev: habanalabs device structure.
295  * @kref: refcount of this SOB. The SOB will reset once the refcount is zero.
296  * @sob_id: id of this SOB.
297  * @sob_addr: the sob offset from the base address.
298  * @q_idx: the H/W queue that uses this SOB.
299  * @need_reset: reset indication set when switching to the other sob.
300  */
301 struct hl_hw_sob {
302 	struct hl_device	*hdev;
303 	struct kref		kref;
304 	u32			sob_id;
305 	u32			sob_addr;
306 	u32			q_idx;
307 	bool			need_reset;
308 };
309 
310 enum hl_collective_mode {
311 	HL_COLLECTIVE_NOT_SUPPORTED = 0x0,
312 	HL_COLLECTIVE_MASTER = 0x1,
313 	HL_COLLECTIVE_SLAVE = 0x2
314 };
315 
316 /**
317  * struct hw_queue_properties - queue information.
318  * @type: queue type.
319  * @queue_cb_alloc_flags: bitmap which indicates if the hw queue supports CB
320  *                        that allocated by the Kernel driver and therefore,
321  *                        a CB handle can be provided for jobs on this queue.
322  *                        Otherwise, a CB address must be provided.
323  * @collective_mode: collective mode of current queue
324  * @driver_only: true if only the driver is allowed to send a job to this queue,
325  *               false otherwise.
326  * @supports_sync_stream: True if queue supports sync stream
327  */
328 struct hw_queue_properties {
329 	enum hl_queue_type	type;
330 	enum queue_cb_alloc_flags cb_alloc_flags;
331 	enum hl_collective_mode	collective_mode;
332 	u8			driver_only;
333 	u8			supports_sync_stream;
334 };
335 
336 /**
337  * enum vm_type - virtual memory mapping request information.
338  * @VM_TYPE_USERPTR: mapping of user memory to device virtual address.
339  * @VM_TYPE_PHYS_PACK: mapping of DRAM memory to device virtual address.
340  */
341 enum vm_type {
342 	VM_TYPE_USERPTR = 0x1,
343 	VM_TYPE_PHYS_PACK = 0x2
344 };
345 
346 /**
347  * enum hl_device_hw_state - H/W device state. use this to understand whether
348  *                           to do reset before hw_init or not
349  * @HL_DEVICE_HW_STATE_CLEAN: H/W state is clean. i.e. after hard reset
350  * @HL_DEVICE_HW_STATE_DIRTY: H/W state is dirty. i.e. we started to execute
351  *                            hw_init
352  */
353 enum hl_device_hw_state {
354 	HL_DEVICE_HW_STATE_CLEAN = 0,
355 	HL_DEVICE_HW_STATE_DIRTY
356 };
357 
358 #define HL_MMU_VA_ALIGNMENT_NOT_NEEDED 0
359 
360 /**
361  * struct hl_mmu_properties - ASIC specific MMU address translation properties.
362  * @start_addr: virtual start address of the memory region.
363  * @end_addr: virtual end address of the memory region.
364  * @hop0_shift: shift of hop 0 mask.
365  * @hop1_shift: shift of hop 1 mask.
366  * @hop2_shift: shift of hop 2 mask.
367  * @hop3_shift: shift of hop 3 mask.
368  * @hop4_shift: shift of hop 4 mask.
369  * @hop5_shift: shift of hop 5 mask.
370  * @hop0_mask: mask to get the PTE address in hop 0.
371  * @hop1_mask: mask to get the PTE address in hop 1.
372  * @hop2_mask: mask to get the PTE address in hop 2.
373  * @hop3_mask: mask to get the PTE address in hop 3.
374  * @hop4_mask: mask to get the PTE address in hop 4.
375  * @hop5_mask: mask to get the PTE address in hop 5.
376  * @page_size: default page size used to allocate memory.
377  * @num_hops: The amount of hops supported by the translation table.
378  * @host_resident: Should the MMU page table reside in host memory or in the
379  *                 device DRAM.
380  */
381 struct hl_mmu_properties {
382 	u64	start_addr;
383 	u64	end_addr;
384 	u64	hop0_shift;
385 	u64	hop1_shift;
386 	u64	hop2_shift;
387 	u64	hop3_shift;
388 	u64	hop4_shift;
389 	u64	hop5_shift;
390 	u64	hop0_mask;
391 	u64	hop1_mask;
392 	u64	hop2_mask;
393 	u64	hop3_mask;
394 	u64	hop4_mask;
395 	u64	hop5_mask;
396 	u32	page_size;
397 	u32	num_hops;
398 	u8	host_resident;
399 };
400 
401 /**
402  * struct hl_hints_range - hint addresses reserved va range.
403  * @start_addr: start address of the va range.
404  * @end_addr: end address of the va range.
405  */
406 struct hl_hints_range {
407 	u64 start_addr;
408 	u64 end_addr;
409 };
410 
411 /**
412  * struct asic_fixed_properties - ASIC specific immutable properties.
413  * @hw_queues_props: H/W queues properties.
414  * @cpucp_info: received various information from CPU-CP regarding the H/W, e.g.
415  *		available sensors.
416  * @uboot_ver: F/W U-boot version.
417  * @preboot_ver: F/W Preboot version.
418  * @dmmu: DRAM MMU address translation properties.
419  * @pmmu: PCI (host) MMU address translation properties.
420  * @pmmu_huge: PCI (host) MMU address translation properties for memory
421  *              allocated with huge pages.
422  * @hints_dram_reserved_va_range: dram hint addresses reserved range.
423  * @hints_host_reserved_va_range: host hint addresses reserved range.
424  * @hints_host_hpage_reserved_va_range: host huge page hint addresses reserved
425  *                                      range.
426  * @sram_base_address: SRAM physical start address.
427  * @sram_end_address: SRAM physical end address.
428  * @sram_user_base_address - SRAM physical start address for user access.
429  * @dram_base_address: DRAM physical start address.
430  * @dram_end_address: DRAM physical end address.
431  * @dram_user_base_address: DRAM physical start address for user access.
432  * @dram_size: DRAM total size.
433  * @dram_pci_bar_size: size of PCI bar towards DRAM.
434  * @max_power_default: max power of the device after reset
435  * @dc_power_default: power consumed by the device in mode idle.
436  * @dram_size_for_default_page_mapping: DRAM size needed to map to avoid page
437  *                                      fault.
438  * @pcie_dbi_base_address: Base address of the PCIE_DBI block.
439  * @pcie_aux_dbi_reg_addr: Address of the PCIE_AUX DBI register.
440  * @mmu_pgt_addr: base physical address in DRAM of MMU page tables.
441  * @mmu_dram_default_page_addr: DRAM default page physical address.
442  * @cb_va_start_addr: virtual start address of command buffers which are mapped
443  *                    to the device's MMU.
444  * @cb_va_end_addr: virtual end address of command buffers which are mapped to
445  *                  the device's MMU.
446  * @dram_hints_align_mask: dram va hint addresses alignment mask which is used
447  *                  for hints validity check.
448  * device_dma_offset_for_host_access: the offset to add to host DMA addresses
449  *                                    to enable the device to access them.
450  * @mmu_pgt_size: MMU page tables total size.
451  * @mmu_pte_size: PTE size in MMU page tables.
452  * @mmu_hop_table_size: MMU hop table size.
453  * @mmu_hop0_tables_total_size: total size of MMU hop0 tables.
454  * @dram_page_size: page size for MMU DRAM allocation.
455  * @cfg_size: configuration space size on SRAM.
456  * @sram_size: total size of SRAM.
457  * @max_asid: maximum number of open contexts (ASIDs).
458  * @num_of_events: number of possible internal H/W IRQs.
459  * @psoc_pci_pll_nr: PCI PLL NR value.
460  * @psoc_pci_pll_nf: PCI PLL NF value.
461  * @psoc_pci_pll_od: PCI PLL OD value.
462  * @psoc_pci_pll_div_factor: PCI PLL DIV FACTOR 1 value.
463  * @psoc_timestamp_frequency: frequency of the psoc timestamp clock.
464  * @high_pll: high PLL frequency used by the device.
465  * @cb_pool_cb_cnt: number of CBs in the CB pool.
466  * @cb_pool_cb_size: size of each CB in the CB pool.
467  * @max_pending_cs: maximum of concurrent pending command submissions
468  * @max_queues: maximum amount of queues in the system
469  * @fw_preboot_cpu_boot_dev_sts0: bitmap representation of preboot cpu
470  *                                capabilities reported by FW, bit description
471  *                                can be found in CPU_BOOT_DEV_STS0
472  * @fw_preboot_cpu_boot_dev_sts1: bitmap representation of preboot cpu
473  *                                capabilities reported by FW, bit description
474  *                                can be found in CPU_BOOT_DEV_STS1
475  * @fw_bootfit_cpu_boot_dev_sts0: bitmap representation of boot cpu security
476  *                                status reported by FW, bit description can be
477  *                                found in CPU_BOOT_DEV_STS0
478  * @fw_bootfit_cpu_boot_dev_sts1: bitmap representation of boot cpu security
479  *                                status reported by FW, bit description can be
480  *                                found in CPU_BOOT_DEV_STS1
481  * @fw_app_cpu_boot_dev_sts0: bitmap representation of application security
482  *                            status reported by FW, bit description can be
483  *                            found in CPU_BOOT_DEV_STS0
484  * @fw_app_cpu_boot_dev_sts1: bitmap representation of application security
485  *                            status reported by FW, bit description can be
486  *                            found in CPU_BOOT_DEV_STS1
487  * @collective_first_sob: first sync object available for collective use
488  * @collective_first_mon: first monitor available for collective use
489  * @sync_stream_first_sob: first sync object available for sync stream use
490  * @sync_stream_first_mon: first monitor available for sync stream use
491  * @first_available_user_sob: first sob available for the user
492  * @first_available_user_mon: first monitor available for the user
493  * @first_available_user_msix_interrupt: first available msix interrupt
494  *                                       reserved for the user
495  * @first_available_cq: first available CQ for the user.
496  * @user_interrupt_count: number of user interrupts.
497  * @server_type: Server type that the ASIC is currently installed in.
498  *               The value is according to enum hl_server_type in uapi file.
499  * @tpc_enabled_mask: which TPCs are enabled.
500  * @completion_queues_count: number of completion queues.
501  * @fw_security_enabled: true if security measures are enabled in firmware,
502  *                       false otherwise
503  * @fw_cpu_boot_dev_sts0_valid: status bits are valid and can be fetched from
504  *                              BOOT_DEV_STS0
505  * @fw_cpu_boot_dev_sts1_valid: status bits are valid and can be fetched from
506  *                              BOOT_DEV_STS1
507  * @dram_supports_virtual_memory: is there an MMU towards the DRAM
508  * @hard_reset_done_by_fw: true if firmware is handling hard reset flow
509  * @num_functional_hbms: number of functional HBMs in each DCORE.
510  * @hints_range_reservation: device support hint addresses range reservation.
511  * @iatu_done_by_fw: true if iATU configuration is being done by FW.
512  * @dynamic_fw_load: is dynamic FW load is supported.
513  * @gic_interrupts_enable: true if FW is not blocking GIC controller,
514  *                         false otherwise.
515  */
516 struct asic_fixed_properties {
517 	struct hw_queue_properties	*hw_queues_props;
518 	struct cpucp_info		cpucp_info;
519 	char				uboot_ver[VERSION_MAX_LEN];
520 	char				preboot_ver[VERSION_MAX_LEN];
521 	struct hl_mmu_properties	dmmu;
522 	struct hl_mmu_properties	pmmu;
523 	struct hl_mmu_properties	pmmu_huge;
524 	struct hl_hints_range		hints_dram_reserved_va_range;
525 	struct hl_hints_range		hints_host_reserved_va_range;
526 	struct hl_hints_range		hints_host_hpage_reserved_va_range;
527 	u64				sram_base_address;
528 	u64				sram_end_address;
529 	u64				sram_user_base_address;
530 	u64				dram_base_address;
531 	u64				dram_end_address;
532 	u64				dram_user_base_address;
533 	u64				dram_size;
534 	u64				dram_pci_bar_size;
535 	u64				max_power_default;
536 	u64				dc_power_default;
537 	u64				dram_size_for_default_page_mapping;
538 	u64				pcie_dbi_base_address;
539 	u64				pcie_aux_dbi_reg_addr;
540 	u64				mmu_pgt_addr;
541 	u64				mmu_dram_default_page_addr;
542 	u64				cb_va_start_addr;
543 	u64				cb_va_end_addr;
544 	u64				dram_hints_align_mask;
545 	u64				device_dma_offset_for_host_access;
546 	u32				mmu_pgt_size;
547 	u32				mmu_pte_size;
548 	u32				mmu_hop_table_size;
549 	u32				mmu_hop0_tables_total_size;
550 	u32				dram_page_size;
551 	u32				cfg_size;
552 	u32				sram_size;
553 	u32				max_asid;
554 	u32				num_of_events;
555 	u32				psoc_pci_pll_nr;
556 	u32				psoc_pci_pll_nf;
557 	u32				psoc_pci_pll_od;
558 	u32				psoc_pci_pll_div_factor;
559 	u32				psoc_timestamp_frequency;
560 	u32				high_pll;
561 	u32				cb_pool_cb_cnt;
562 	u32				cb_pool_cb_size;
563 	u32				max_pending_cs;
564 	u32				max_queues;
565 	u32				fw_preboot_cpu_boot_dev_sts0;
566 	u32				fw_preboot_cpu_boot_dev_sts1;
567 	u32				fw_bootfit_cpu_boot_dev_sts0;
568 	u32				fw_bootfit_cpu_boot_dev_sts1;
569 	u32				fw_app_cpu_boot_dev_sts0;
570 	u32				fw_app_cpu_boot_dev_sts1;
571 	u16				collective_first_sob;
572 	u16				collective_first_mon;
573 	u16				sync_stream_first_sob;
574 	u16				sync_stream_first_mon;
575 	u16				first_available_user_sob[HL_MAX_DCORES];
576 	u16				first_available_user_mon[HL_MAX_DCORES];
577 	u16				first_available_user_msix_interrupt;
578 	u16				first_available_cq[HL_MAX_DCORES];
579 	u16				user_interrupt_count;
580 	u16				server_type;
581 	u8				tpc_enabled_mask;
582 	u8				completion_queues_count;
583 	u8				fw_security_enabled;
584 	u8				fw_cpu_boot_dev_sts0_valid;
585 	u8				fw_cpu_boot_dev_sts1_valid;
586 	u8				dram_supports_virtual_memory;
587 	u8				hard_reset_done_by_fw;
588 	u8				num_functional_hbms;
589 	u8				hints_range_reservation;
590 	u8				iatu_done_by_fw;
591 	u8				dynamic_fw_load;
592 	u8				gic_interrupts_enable;
593 };
594 
595 /**
596  * struct hl_fence - software synchronization primitive
597  * @completion: fence is implemented using completion
598  * @refcount: refcount for this fence
599  * @cs_sequence: sequence of the corresponding command submission
600  * @stream_master_qid_map: streams masters QID bitmap to represent all streams
601  *                         masters QIDs that multi cs is waiting on
602  * @error: mark this fence with error
603  * @timestamp: timestamp upon completion
604  */
605 struct hl_fence {
606 	struct completion	completion;
607 	struct kref		refcount;
608 	u64			cs_sequence;
609 	u32			stream_master_qid_map;
610 	int			error;
611 	ktime_t			timestamp;
612 };
613 
614 /**
615  * struct hl_cs_compl - command submission completion object.
616  * @base_fence: hl fence object.
617  * @lock: spinlock to protect fence.
618  * @hdev: habanalabs device structure.
619  * @hw_sob: the H/W SOB used in this signal/wait CS.
620  * @encaps_sig_hdl: encaps signals hanlder.
621  * @cs_seq: command submission sequence number.
622  * @type: type of the CS - signal/wait.
623  * @sob_val: the SOB value that is used in this signal/wait CS.
624  * @sob_group: the SOB group that is used in this collective wait CS.
625  * @encaps_signals: indication whether it's a completion object of cs with
626  * encaps signals or not.
627  */
628 struct hl_cs_compl {
629 	struct hl_fence		base_fence;
630 	spinlock_t		lock;
631 	struct hl_device	*hdev;
632 	struct hl_hw_sob	*hw_sob;
633 	struct hl_cs_encaps_sig_handle *encaps_sig_hdl;
634 	u64			cs_seq;
635 	enum hl_cs_type		type;
636 	u16			sob_val;
637 	u16			sob_group;
638 	bool			encaps_signals;
639 };
640 
641 /*
642  * Command Buffers
643  */
644 
645 /**
646  * struct hl_cb_mgr - describes a Command Buffer Manager.
647  * @cb_lock: protects cb_handles.
648  * @cb_handles: an idr to hold all command buffer handles.
649  */
650 struct hl_cb_mgr {
651 	spinlock_t		cb_lock;
652 	struct idr		cb_handles; /* protected by cb_lock */
653 };
654 
655 /**
656  * struct hl_cb - describes a Command Buffer.
657  * @refcount: reference counter for usage of the CB.
658  * @hdev: pointer to device this CB belongs to.
659  * @ctx: pointer to the CB owner's context.
660  * @lock: spinlock to protect mmap flows.
661  * @debugfs_list: node in debugfs list of command buffers.
662  * @pool_list: node in pool list of command buffers.
663  * @va_block_list: list of virtual addresses blocks of the CB if it is mapped to
664  *                 the device's MMU.
665  * @id: the CB's ID.
666  * @kernel_address: Holds the CB's kernel virtual address.
667  * @bus_address: Holds the CB's DMA address.
668  * @mmap_size: Holds the CB's size that was mmaped.
669  * @size: holds the CB's size.
670  * @cs_cnt: holds number of CS that this CB participates in.
671  * @mmap: true if the CB is currently mmaped to user.
672  * @is_pool: true if CB was acquired from the pool, false otherwise.
673  * @is_internal: internaly allocated
674  * @is_mmu_mapped: true if the CB is mapped to the device's MMU.
675  */
676 struct hl_cb {
677 	struct kref		refcount;
678 	struct hl_device	*hdev;
679 	struct hl_ctx		*ctx;
680 	spinlock_t		lock;
681 	struct list_head	debugfs_list;
682 	struct list_head	pool_list;
683 	struct list_head	va_block_list;
684 	u64			id;
685 	void			*kernel_address;
686 	dma_addr_t		bus_address;
687 	u32			mmap_size;
688 	u32			size;
689 	atomic_t		cs_cnt;
690 	u8			mmap;
691 	u8			is_pool;
692 	u8			is_internal;
693 	u8			is_mmu_mapped;
694 };
695 
696 
697 /*
698  * QUEUES
699  */
700 
701 struct hl_cs;
702 struct hl_cs_job;
703 
704 /* Queue length of external and HW queues */
705 #define HL_QUEUE_LENGTH			4096
706 #define HL_QUEUE_SIZE_IN_BYTES		(HL_QUEUE_LENGTH * HL_BD_SIZE)
707 
708 #if (HL_MAX_JOBS_PER_CS > HL_QUEUE_LENGTH)
709 #error "HL_QUEUE_LENGTH must be greater than HL_MAX_JOBS_PER_CS"
710 #endif
711 
712 /* HL_CQ_LENGTH is in units of struct hl_cq_entry */
713 #define HL_CQ_LENGTH			HL_QUEUE_LENGTH
714 #define HL_CQ_SIZE_IN_BYTES		(HL_CQ_LENGTH * HL_CQ_ENTRY_SIZE)
715 
716 /* Must be power of 2 */
717 #define HL_EQ_LENGTH			64
718 #define HL_EQ_SIZE_IN_BYTES		(HL_EQ_LENGTH * HL_EQ_ENTRY_SIZE)
719 
720 /* Host <-> CPU-CP shared memory size */
721 #define HL_CPU_ACCESSIBLE_MEM_SIZE	SZ_2M
722 
723 /**
724  * struct hl_sync_stream_properties -
725  *     describes a H/W queue sync stream properties
726  * @hw_sob: array of the used H/W SOBs by this H/W queue.
727  * @next_sob_val: the next value to use for the currently used SOB.
728  * @base_sob_id: the base SOB id of the SOBs used by this queue.
729  * @base_mon_id: the base MON id of the MONs used by this queue.
730  * @collective_mstr_mon_id: the MON ids of the MONs used by this master queue
731  *                          in order to sync with all slave queues.
732  * @collective_slave_mon_id: the MON id used by this slave queue in order to
733  *                           sync with its master queue.
734  * @collective_sob_id: current SOB id used by this collective slave queue
735  *                     to signal its collective master queue upon completion.
736  * @curr_sob_offset: the id offset to the currently used SOB from the
737  *                   HL_RSVD_SOBS that are being used by this queue.
738  */
739 struct hl_sync_stream_properties {
740 	struct hl_hw_sob hw_sob[HL_RSVD_SOBS];
741 	u16		next_sob_val;
742 	u16		base_sob_id;
743 	u16		base_mon_id;
744 	u16		collective_mstr_mon_id[HL_COLLECTIVE_RSVD_MSTR_MONS];
745 	u16		collective_slave_mon_id;
746 	u16		collective_sob_id;
747 	u8		curr_sob_offset;
748 };
749 
750 /**
751  * struct hl_encaps_signals_mgr - describes sync stream encapsulated signals
752  * handlers manager
753  * @lock: protects handles.
754  * @handles: an idr to hold all encapsulated signals handles.
755  */
756 struct hl_encaps_signals_mgr {
757 	spinlock_t		lock;
758 	struct idr		handles;
759 };
760 
761 /**
762  * struct hl_hw_queue - describes a H/W transport queue.
763  * @shadow_queue: pointer to a shadow queue that holds pointers to jobs.
764  * @sync_stream_prop: sync stream queue properties
765  * @queue_type: type of queue.
766  * @collective_mode: collective mode of current queue
767  * @kernel_address: holds the queue's kernel virtual address.
768  * @bus_address: holds the queue's DMA address.
769  * @pi: holds the queue's pi value.
770  * @ci: holds the queue's ci value, AS CALCULATED BY THE DRIVER (not real ci).
771  * @hw_queue_id: the id of the H/W queue.
772  * @cq_id: the id for the corresponding CQ for this H/W queue.
773  * @msi_vec: the IRQ number of the H/W queue.
774  * @int_queue_len: length of internal queue (number of entries).
775  * @valid: is the queue valid (we have array of 32 queues, not all of them
776  *         exist).
777  * @supports_sync_stream: True if queue supports sync stream
778  */
779 struct hl_hw_queue {
780 	struct hl_cs_job			**shadow_queue;
781 	struct hl_sync_stream_properties	sync_stream_prop;
782 	enum hl_queue_type			queue_type;
783 	enum hl_collective_mode			collective_mode;
784 	void					*kernel_address;
785 	dma_addr_t				bus_address;
786 	u32					pi;
787 	atomic_t				ci;
788 	u32					hw_queue_id;
789 	u32					cq_id;
790 	u32					msi_vec;
791 	u16					int_queue_len;
792 	u8					valid;
793 	u8					supports_sync_stream;
794 };
795 
796 /**
797  * struct hl_cq - describes a completion queue
798  * @hdev: pointer to the device structure
799  * @kernel_address: holds the queue's kernel virtual address
800  * @bus_address: holds the queue's DMA address
801  * @cq_idx: completion queue index in array
802  * @hw_queue_id: the id of the matching H/W queue
803  * @ci: ci inside the queue
804  * @pi: pi inside the queue
805  * @free_slots_cnt: counter of free slots in queue
806  */
807 struct hl_cq {
808 	struct hl_device	*hdev;
809 	void			*kernel_address;
810 	dma_addr_t		bus_address;
811 	u32			cq_idx;
812 	u32			hw_queue_id;
813 	u32			ci;
814 	u32			pi;
815 	atomic_t		free_slots_cnt;
816 };
817 
818 /**
819  * struct hl_user_interrupt - holds user interrupt information
820  * @hdev: pointer to the device structure
821  * @wait_list_head: head to the list of user threads pending on this interrupt
822  * @wait_list_lock: protects wait_list_head
823  * @interrupt_id: msix interrupt id
824  */
825 struct hl_user_interrupt {
826 	struct hl_device	*hdev;
827 	struct list_head	wait_list_head;
828 	spinlock_t		wait_list_lock;
829 	u32			interrupt_id;
830 };
831 
832 /**
833  * struct hl_user_pending_interrupt - holds a context to a user thread
834  *                                    pending on an interrupt
835  * @wait_list_node: node in the list of user threads pending on an interrupt
836  * @fence: hl fence object for interrupt completion
837  */
838 struct hl_user_pending_interrupt {
839 	struct list_head	wait_list_node;
840 	struct hl_fence		fence;
841 };
842 
843 /**
844  * struct hl_eq - describes the event queue (single one per device)
845  * @hdev: pointer to the device structure
846  * @kernel_address: holds the queue's kernel virtual address
847  * @bus_address: holds the queue's DMA address
848  * @ci: ci inside the queue
849  * @prev_eqe_index: the index of the previous event queue entry. The index of
850  *                  the current entry's index must be +1 of the previous one.
851  * @check_eqe_index: do we need to check the index of the current entry vs. the
852  *                   previous one. This is for backward compatibility with older
853  *                   firmwares
854  */
855 struct hl_eq {
856 	struct hl_device	*hdev;
857 	void			*kernel_address;
858 	dma_addr_t		bus_address;
859 	u32			ci;
860 	u32			prev_eqe_index;
861 	bool			check_eqe_index;
862 };
863 
864 
865 /*
866  * ASICs
867  */
868 
869 /**
870  * enum hl_asic_type - supported ASIC types.
871  * @ASIC_INVALID: Invalid ASIC type.
872  * @ASIC_GOYA: Goya device.
873  * @ASIC_GAUDI: Gaudi device.
874  * @ASIC_GAUDI_SEC: Gaudi secured device (HL-2000).
875  */
876 enum hl_asic_type {
877 	ASIC_INVALID,
878 	ASIC_GOYA,
879 	ASIC_GAUDI,
880 	ASIC_GAUDI_SEC
881 };
882 
883 struct hl_cs_parser;
884 
885 /**
886  * enum hl_pm_mng_profile - power management profile.
887  * @PM_AUTO: internal clock is set by the Linux driver.
888  * @PM_MANUAL: internal clock is set by the user.
889  * @PM_LAST: last power management type.
890  */
891 enum hl_pm_mng_profile {
892 	PM_AUTO = 1,
893 	PM_MANUAL,
894 	PM_LAST
895 };
896 
897 /**
898  * enum hl_pll_frequency - PLL frequency.
899  * @PLL_HIGH: high frequency.
900  * @PLL_LOW: low frequency.
901  * @PLL_LAST: last frequency values that were configured by the user.
902  */
903 enum hl_pll_frequency {
904 	PLL_HIGH = 1,
905 	PLL_LOW,
906 	PLL_LAST
907 };
908 
909 #define PLL_REF_CLK 50
910 
911 enum div_select_defs {
912 	DIV_SEL_REF_CLK = 0,
913 	DIV_SEL_PLL_CLK = 1,
914 	DIV_SEL_DIVIDED_REF = 2,
915 	DIV_SEL_DIVIDED_PLL = 3,
916 };
917 
918 enum pci_region {
919 	PCI_REGION_CFG,
920 	PCI_REGION_SRAM,
921 	PCI_REGION_DRAM,
922 	PCI_REGION_SP_SRAM,
923 	PCI_REGION_NUMBER,
924 };
925 
926 /**
927  * struct pci_mem_region - describe memory region in a PCI bar
928  * @region_base: region base address
929  * @region_size: region size
930  * @bar_size: size of the BAR
931  * @offset_in_bar: region offset into the bar
932  * @bar_id: bar ID of the region
933  * @used: if used 1, otherwise 0
934  */
935 struct pci_mem_region {
936 	u64 region_base;
937 	u64 region_size;
938 	u64 bar_size;
939 	u64 offset_in_bar;
940 	u8 bar_id;
941 	u8 used;
942 };
943 
944 /**
945  * struct static_fw_load_mgr - static FW load manager
946  * @preboot_version_max_off: max offset to preboot version
947  * @boot_fit_version_max_off: max offset to boot fit version
948  * @kmd_msg_to_cpu_reg: register address for KDM->CPU messages
949  * @cpu_cmd_status_to_host_reg: register address for CPU command status response
950  * @cpu_boot_status_reg: boot status register
951  * @cpu_boot_dev_status0_reg: boot device status register 0
952  * @cpu_boot_dev_status1_reg: boot device status register 1
953  * @boot_err0_reg: boot error register 0
954  * @boot_err1_reg: boot error register 1
955  * @preboot_version_offset_reg: SRAM offset to preboot version register
956  * @boot_fit_version_offset_reg: SRAM offset to boot fit version register
957  * @sram_offset_mask: mask for getting offset into the SRAM
958  * @cpu_reset_wait_msec: used when setting WFE via kmd_msg_to_cpu_reg
959  */
960 struct static_fw_load_mgr {
961 	u64 preboot_version_max_off;
962 	u64 boot_fit_version_max_off;
963 	u32 kmd_msg_to_cpu_reg;
964 	u32 cpu_cmd_status_to_host_reg;
965 	u32 cpu_boot_status_reg;
966 	u32 cpu_boot_dev_status0_reg;
967 	u32 cpu_boot_dev_status1_reg;
968 	u32 boot_err0_reg;
969 	u32 boot_err1_reg;
970 	u32 preboot_version_offset_reg;
971 	u32 boot_fit_version_offset_reg;
972 	u32 sram_offset_mask;
973 	u32 cpu_reset_wait_msec;
974 };
975 
976 /**
977  * struct fw_response - FW response to LKD command
978  * @ram_offset: descriptor offset into the RAM
979  * @ram_type: RAM type containing the descriptor (SRAM/DRAM)
980  * @status: command status
981  */
982 struct fw_response {
983 	u32 ram_offset;
984 	u8 ram_type;
985 	u8 status;
986 };
987 
988 /**
989  * struct dynamic_fw_load_mgr - dynamic FW load manager
990  * @response: FW to LKD response
991  * @comm_desc: the communication descriptor with FW
992  * @image_region: region to copy the FW image to
993  * @fw_image_size: size of FW image to load
994  * @wait_for_bl_timeout: timeout for waiting for boot loader to respond
995  */
996 struct dynamic_fw_load_mgr {
997 	struct fw_response response;
998 	struct lkd_fw_comms_desc comm_desc;
999 	struct pci_mem_region *image_region;
1000 	size_t fw_image_size;
1001 	u32 wait_for_bl_timeout;
1002 };
1003 
1004 /**
1005  * struct fw_image_props - properties of FW image
1006  * @image_name: name of the image
1007  * @src_off: offset in src FW to copy from
1008  * @copy_size: amount of bytes to copy (0 to copy the whole binary)
1009  */
1010 struct fw_image_props {
1011 	char *image_name;
1012 	u32 src_off;
1013 	u32 copy_size;
1014 };
1015 
1016 /**
1017  * struct fw_load_mgr - manager FW loading process
1018  * @dynamic_loader: specific structure for dynamic load
1019  * @static_loader: specific structure for static load
1020  * @boot_fit_img: boot fit image properties
1021  * @linux_img: linux image properties
1022  * @cpu_timeout: CPU response timeout in usec
1023  * @boot_fit_timeout: Boot fit load timeout in usec
1024  * @skip_bmc: should BMC be skipped
1025  * @sram_bar_id: SRAM bar ID
1026  * @dram_bar_id: DRAM bar ID
1027  * @linux_loaded: true if linux was loaded so far
1028  */
1029 struct fw_load_mgr {
1030 	union {
1031 		struct dynamic_fw_load_mgr dynamic_loader;
1032 		struct static_fw_load_mgr static_loader;
1033 	};
1034 	struct fw_image_props boot_fit_img;
1035 	struct fw_image_props linux_img;
1036 	u32 cpu_timeout;
1037 	u32 boot_fit_timeout;
1038 	u8 skip_bmc;
1039 	u8 sram_bar_id;
1040 	u8 dram_bar_id;
1041 	u8 linux_loaded;
1042 };
1043 
1044 /**
1045  * struct hl_asic_funcs - ASIC specific functions that are can be called from
1046  *                        common code.
1047  * @early_init: sets up early driver state (pre sw_init), doesn't configure H/W.
1048  * @early_fini: tears down what was done in early_init.
1049  * @late_init: sets up late driver/hw state (post hw_init) - Optional.
1050  * @late_fini: tears down what was done in late_init (pre hw_fini) - Optional.
1051  * @sw_init: sets up driver state, does not configure H/W.
1052  * @sw_fini: tears down driver state, does not configure H/W.
1053  * @hw_init: sets up the H/W state.
1054  * @hw_fini: tears down the H/W state.
1055  * @halt_engines: halt engines, needed for reset sequence. This also disables
1056  *                interrupts from the device. Should be called before
1057  *                hw_fini and before CS rollback.
1058  * @suspend: handles IP specific H/W or SW changes for suspend.
1059  * @resume: handles IP specific H/W or SW changes for resume.
1060  * @mmap: maps a memory.
1061  * @ring_doorbell: increment PI on a given QMAN.
1062  * @pqe_write: Write the PQ entry to the PQ. This is ASIC-specific
1063  *             function because the PQs are located in different memory areas
1064  *             per ASIC (SRAM, DRAM, Host memory) and therefore, the method of
1065  *             writing the PQE must match the destination memory area
1066  *             properties.
1067  * @asic_dma_alloc_coherent: Allocate coherent DMA memory by calling
1068  *                           dma_alloc_coherent(). This is ASIC function because
1069  *                           its implementation is not trivial when the driver
1070  *                           is loaded in simulation mode (not upstreamed).
1071  * @asic_dma_free_coherent:  Free coherent DMA memory by calling
1072  *                           dma_free_coherent(). This is ASIC function because
1073  *                           its implementation is not trivial when the driver
1074  *                           is loaded in simulation mode (not upstreamed).
1075  * @scrub_device_mem: Scrub device memory given an address and size
1076  * @get_int_queue_base: get the internal queue base address.
1077  * @test_queues: run simple test on all queues for sanity check.
1078  * @asic_dma_pool_zalloc: small DMA allocation of coherent memory from DMA pool.
1079  *                        size of allocation is HL_DMA_POOL_BLK_SIZE.
1080  * @asic_dma_pool_free: free small DMA allocation from pool.
1081  * @cpu_accessible_dma_pool_alloc: allocate CPU PQ packet from DMA pool.
1082  * @cpu_accessible_dma_pool_free: free CPU PQ packet from DMA pool.
1083  * @hl_dma_unmap_sg: DMA unmap scatter-gather list.
1084  * @cs_parser: parse Command Submission.
1085  * @asic_dma_map_sg: DMA map scatter-gather list.
1086  * @get_dma_desc_list_size: get number of LIN_DMA packets required for CB.
1087  * @add_end_of_cb_packets: Add packets to the end of CB, if device requires it.
1088  * @update_eq_ci: update event queue CI.
1089  * @context_switch: called upon ASID context switch.
1090  * @restore_phase_topology: clear all SOBs amd MONs.
1091  * @debugfs_read32: debug interface for reading u32 from DRAM/SRAM/Host memory.
1092  * @debugfs_write32: debug interface for writing u32 to DRAM/SRAM/Host memory.
1093  * @debugfs_read64: debug interface for reading u64 from DRAM/SRAM/Host memory.
1094  * @debugfs_write64: debug interface for writing u64 to DRAM/SRAM/Host memory.
1095  * @debugfs_read_dma: debug interface for reading up to 2MB from the device's
1096  *                    internal memory via DMA engine.
1097  * @add_device_attr: add ASIC specific device attributes.
1098  * @handle_eqe: handle event queue entry (IRQ) from CPU-CP.
1099  * @set_pll_profile: change PLL profile (manual/automatic).
1100  * @get_events_stat: retrieve event queue entries histogram.
1101  * @read_pte: read MMU page table entry from DRAM.
1102  * @write_pte: write MMU page table entry to DRAM.
1103  * @mmu_invalidate_cache: flush MMU STLB host/DRAM cache, either with soft
1104  *                        (L1 only) or hard (L0 & L1) flush.
1105  * @mmu_invalidate_cache_range: flush specific MMU STLB cache lines with
1106  *                              ASID-VA-size mask.
1107  * @send_heartbeat: send is-alive packet to CPU-CP and verify response.
1108  * @set_clock_gating: enable/disable clock gating per engine according to
1109  *                    clock gating mask in hdev
1110  * @disable_clock_gating: disable clock gating completely
1111  * @debug_coresight: perform certain actions on Coresight for debugging.
1112  * @is_device_idle: return true if device is idle, false otherwise.
1113  * @soft_reset_late_init: perform certain actions needed after soft reset.
1114  * @hw_queues_lock: acquire H/W queues lock.
1115  * @hw_queues_unlock: release H/W queues lock.
1116  * @get_pci_id: retrieve PCI ID.
1117  * @get_eeprom_data: retrieve EEPROM data from F/W.
1118  * @send_cpu_message: send message to F/W. If the message is timedout, the
1119  *                    driver will eventually reset the device. The timeout can
1120  *                    be determined by the calling function or it can be 0 and
1121  *                    then the timeout is the default timeout for the specific
1122  *                    ASIC
1123  * @get_hw_state: retrieve the H/W state
1124  * @pci_bars_map: Map PCI BARs.
1125  * @init_iatu: Initialize the iATU unit inside the PCI controller.
1126  * @rreg: Read a register. Needed for simulator support.
1127  * @wreg: Write a register. Needed for simulator support.
1128  * @halt_coresight: stop the ETF and ETR traces.
1129  * @ctx_init: context dependent initialization.
1130  * @ctx_fini: context dependent cleanup.
1131  * @get_clk_rate: Retrieve the ASIC current and maximum clock rate in MHz
1132  * @get_queue_id_for_cq: Get the H/W queue id related to the given CQ index.
1133  * @load_firmware_to_device: load the firmware to the device's memory
1134  * @load_boot_fit_to_device: load boot fit to device's memory
1135  * @get_signal_cb_size: Get signal CB size.
1136  * @get_wait_cb_size: Get wait CB size.
1137  * @gen_signal_cb: Generate a signal CB.
1138  * @gen_wait_cb: Generate a wait CB.
1139  * @reset_sob: Reset a SOB.
1140  * @reset_sob_group: Reset SOB group
1141  * @set_dma_mask_from_fw: set the DMA mask in the driver according to the
1142  *                        firmware configuration
1143  * @get_device_time: Get the device time.
1144  * @collective_wait_init_cs: Generate collective master/slave packets
1145  *                           and place them in the relevant cs jobs
1146  * @collective_wait_create_jobs: allocate collective wait cs jobs
1147  * @scramble_addr: Routine to scramble the address prior of mapping it
1148  *                 in the MMU.
1149  * @descramble_addr: Routine to de-scramble the address prior of
1150  *                   showing it to users.
1151  * @ack_protection_bits_errors: ack and dump all security violations
1152  * @get_hw_block_id: retrieve a HW block id to be used by the user to mmap it.
1153  *                   also returns the size of the block if caller supplies
1154  *                   a valid pointer for it
1155  * @hw_block_mmap: mmap a HW block with a given id.
1156  * @enable_events_from_fw: send interrupt to firmware to notify them the
1157  *                         driver is ready to receive asynchronous events. This
1158  *                         function should be called during the first init and
1159  *                         after every hard-reset of the device
1160  * @get_msi_info: Retrieve asic-specific MSI ID of the f/w async event
1161  * @map_pll_idx_to_fw_idx: convert driver specific per asic PLL index to
1162  *                         generic f/w compatible PLL Indexes
1163  * @init_firmware_loader: initialize data for FW loader.
1164  * @init_cpu_scrambler_dram: Enable CPU specific DRAM scrambling
1165  * @state_dump_init: initialize constants required for state dump
1166  * @get_sob_addr: get SOB base address offset.
1167  * @set_pci_memory_regions: setting properties of PCI memory regions
1168  * @get_stream_master_qid_arr: get pointer to stream masters QID array
1169  */
1170 struct hl_asic_funcs {
1171 	int (*early_init)(struct hl_device *hdev);
1172 	int (*early_fini)(struct hl_device *hdev);
1173 	int (*late_init)(struct hl_device *hdev);
1174 	void (*late_fini)(struct hl_device *hdev);
1175 	int (*sw_init)(struct hl_device *hdev);
1176 	int (*sw_fini)(struct hl_device *hdev);
1177 	int (*hw_init)(struct hl_device *hdev);
1178 	void (*hw_fini)(struct hl_device *hdev, bool hard_reset, bool fw_reset);
1179 	void (*halt_engines)(struct hl_device *hdev, bool hard_reset, bool fw_reset);
1180 	int (*suspend)(struct hl_device *hdev);
1181 	int (*resume)(struct hl_device *hdev);
1182 	int (*mmap)(struct hl_device *hdev, struct vm_area_struct *vma,
1183 			void *cpu_addr, dma_addr_t dma_addr, size_t size);
1184 	void (*ring_doorbell)(struct hl_device *hdev, u32 hw_queue_id, u32 pi);
1185 	void (*pqe_write)(struct hl_device *hdev, __le64 *pqe,
1186 			struct hl_bd *bd);
1187 	void* (*asic_dma_alloc_coherent)(struct hl_device *hdev, size_t size,
1188 					dma_addr_t *dma_handle, gfp_t flag);
1189 	void (*asic_dma_free_coherent)(struct hl_device *hdev, size_t size,
1190 					void *cpu_addr, dma_addr_t dma_handle);
1191 	int (*scrub_device_mem)(struct hl_device *hdev, u64 addr, u64 size);
1192 	void* (*get_int_queue_base)(struct hl_device *hdev, u32 queue_id,
1193 				dma_addr_t *dma_handle, u16 *queue_len);
1194 	int (*test_queues)(struct hl_device *hdev);
1195 	void* (*asic_dma_pool_zalloc)(struct hl_device *hdev, size_t size,
1196 				gfp_t mem_flags, dma_addr_t *dma_handle);
1197 	void (*asic_dma_pool_free)(struct hl_device *hdev, void *vaddr,
1198 				dma_addr_t dma_addr);
1199 	void* (*cpu_accessible_dma_pool_alloc)(struct hl_device *hdev,
1200 				size_t size, dma_addr_t *dma_handle);
1201 	void (*cpu_accessible_dma_pool_free)(struct hl_device *hdev,
1202 				size_t size, void *vaddr);
1203 	void (*hl_dma_unmap_sg)(struct hl_device *hdev,
1204 				struct scatterlist *sgl, int nents,
1205 				enum dma_data_direction dir);
1206 	int (*cs_parser)(struct hl_device *hdev, struct hl_cs_parser *parser);
1207 	int (*asic_dma_map_sg)(struct hl_device *hdev,
1208 				struct scatterlist *sgl, int nents,
1209 				enum dma_data_direction dir);
1210 	u32 (*get_dma_desc_list_size)(struct hl_device *hdev,
1211 					struct sg_table *sgt);
1212 	void (*add_end_of_cb_packets)(struct hl_device *hdev,
1213 					void *kernel_address, u32 len,
1214 					u64 cq_addr, u32 cq_val, u32 msix_num,
1215 					bool eb);
1216 	void (*update_eq_ci)(struct hl_device *hdev, u32 val);
1217 	int (*context_switch)(struct hl_device *hdev, u32 asid);
1218 	void (*restore_phase_topology)(struct hl_device *hdev);
1219 	int (*debugfs_read32)(struct hl_device *hdev, u64 addr,
1220 				bool user_address, u32 *val);
1221 	int (*debugfs_write32)(struct hl_device *hdev, u64 addr,
1222 				bool user_address, u32 val);
1223 	int (*debugfs_read64)(struct hl_device *hdev, u64 addr,
1224 				bool user_address, u64 *val);
1225 	int (*debugfs_write64)(struct hl_device *hdev, u64 addr,
1226 				bool user_address, u64 val);
1227 	int (*debugfs_read_dma)(struct hl_device *hdev, u64 addr, u32 size,
1228 				void *blob_addr);
1229 	void (*add_device_attr)(struct hl_device *hdev,
1230 				struct attribute_group *dev_attr_grp);
1231 	void (*handle_eqe)(struct hl_device *hdev,
1232 				struct hl_eq_entry *eq_entry);
1233 	void (*set_pll_profile)(struct hl_device *hdev,
1234 			enum hl_pll_frequency freq);
1235 	void* (*get_events_stat)(struct hl_device *hdev, bool aggregate,
1236 				u32 *size);
1237 	u64 (*read_pte)(struct hl_device *hdev, u64 addr);
1238 	void (*write_pte)(struct hl_device *hdev, u64 addr, u64 val);
1239 	int (*mmu_invalidate_cache)(struct hl_device *hdev, bool is_hard,
1240 					u32 flags);
1241 	int (*mmu_invalidate_cache_range)(struct hl_device *hdev, bool is_hard,
1242 				u32 flags, u32 asid, u64 va, u64 size);
1243 	int (*send_heartbeat)(struct hl_device *hdev);
1244 	void (*set_clock_gating)(struct hl_device *hdev);
1245 	void (*disable_clock_gating)(struct hl_device *hdev);
1246 	int (*debug_coresight)(struct hl_device *hdev, void *data);
1247 	bool (*is_device_idle)(struct hl_device *hdev, u64 *mask_arr,
1248 					u8 mask_len, struct seq_file *s);
1249 	int (*soft_reset_late_init)(struct hl_device *hdev);
1250 	void (*hw_queues_lock)(struct hl_device *hdev);
1251 	void (*hw_queues_unlock)(struct hl_device *hdev);
1252 	u32 (*get_pci_id)(struct hl_device *hdev);
1253 	int (*get_eeprom_data)(struct hl_device *hdev, void *data,
1254 				size_t max_size);
1255 	int (*send_cpu_message)(struct hl_device *hdev, u32 *msg,
1256 				u16 len, u32 timeout, u64 *result);
1257 	int (*pci_bars_map)(struct hl_device *hdev);
1258 	int (*init_iatu)(struct hl_device *hdev);
1259 	u32 (*rreg)(struct hl_device *hdev, u32 reg);
1260 	void (*wreg)(struct hl_device *hdev, u32 reg, u32 val);
1261 	void (*halt_coresight)(struct hl_device *hdev);
1262 	int (*ctx_init)(struct hl_ctx *ctx);
1263 	void (*ctx_fini)(struct hl_ctx *ctx);
1264 	int (*get_clk_rate)(struct hl_device *hdev, u32 *cur_clk, u32 *max_clk);
1265 	u32 (*get_queue_id_for_cq)(struct hl_device *hdev, u32 cq_idx);
1266 	int (*load_firmware_to_device)(struct hl_device *hdev);
1267 	int (*load_boot_fit_to_device)(struct hl_device *hdev);
1268 	u32 (*get_signal_cb_size)(struct hl_device *hdev);
1269 	u32 (*get_wait_cb_size)(struct hl_device *hdev);
1270 	u32 (*gen_signal_cb)(struct hl_device *hdev, void *data, u16 sob_id,
1271 			u32 size, bool eb);
1272 	u32 (*gen_wait_cb)(struct hl_device *hdev,
1273 			struct hl_gen_wait_properties *prop);
1274 	void (*reset_sob)(struct hl_device *hdev, void *data);
1275 	void (*reset_sob_group)(struct hl_device *hdev, u16 sob_group);
1276 	void (*set_dma_mask_from_fw)(struct hl_device *hdev);
1277 	u64 (*get_device_time)(struct hl_device *hdev);
1278 	int (*collective_wait_init_cs)(struct hl_cs *cs);
1279 	int (*collective_wait_create_jobs)(struct hl_device *hdev,
1280 			struct hl_ctx *ctx, struct hl_cs *cs,
1281 			u32 wait_queue_id, u32 collective_engine_id,
1282 			u32 encaps_signal_offset);
1283 	u64 (*scramble_addr)(struct hl_device *hdev, u64 addr);
1284 	u64 (*descramble_addr)(struct hl_device *hdev, u64 addr);
1285 	void (*ack_protection_bits_errors)(struct hl_device *hdev);
1286 	int (*get_hw_block_id)(struct hl_device *hdev, u64 block_addr,
1287 				u32 *block_size, u32 *block_id);
1288 	int (*hw_block_mmap)(struct hl_device *hdev, struct vm_area_struct *vma,
1289 			u32 block_id, u32 block_size);
1290 	void (*enable_events_from_fw)(struct hl_device *hdev);
1291 	void (*get_msi_info)(__le32 *table);
1292 	int (*map_pll_idx_to_fw_idx)(u32 pll_idx);
1293 	void (*init_firmware_loader)(struct hl_device *hdev);
1294 	void (*init_cpu_scrambler_dram)(struct hl_device *hdev);
1295 	void (*state_dump_init)(struct hl_device *hdev);
1296 	u32 (*get_sob_addr)(struct hl_device *hdev, u32 sob_id);
1297 	void (*set_pci_memory_regions)(struct hl_device *hdev);
1298 	u32* (*get_stream_master_qid_arr)(void);
1299 };
1300 
1301 
1302 /*
1303  * CONTEXTS
1304  */
1305 
1306 #define HL_KERNEL_ASID_ID	0
1307 
1308 /**
1309  * enum hl_va_range_type - virtual address range type.
1310  * @HL_VA_RANGE_TYPE_HOST: range type of host pages
1311  * @HL_VA_RANGE_TYPE_HOST_HUGE: range type of host huge pages
1312  * @HL_VA_RANGE_TYPE_DRAM: range type of dram pages
1313  */
1314 enum hl_va_range_type {
1315 	HL_VA_RANGE_TYPE_HOST,
1316 	HL_VA_RANGE_TYPE_HOST_HUGE,
1317 	HL_VA_RANGE_TYPE_DRAM,
1318 	HL_VA_RANGE_TYPE_MAX
1319 };
1320 
1321 /**
1322  * struct hl_va_range - virtual addresses range.
1323  * @lock: protects the virtual addresses list.
1324  * @list: list of virtual addresses blocks available for mappings.
1325  * @start_addr: range start address.
1326  * @end_addr: range end address.
1327  * @page_size: page size of this va range.
1328  */
1329 struct hl_va_range {
1330 	struct mutex		lock;
1331 	struct list_head	list;
1332 	u64			start_addr;
1333 	u64			end_addr;
1334 	u32			page_size;
1335 };
1336 
1337 /**
1338  * struct hl_cs_counters_atomic - command submission counters
1339  * @out_of_mem_drop_cnt: dropped due to memory allocation issue
1340  * @parsing_drop_cnt: dropped due to error in packet parsing
1341  * @queue_full_drop_cnt: dropped due to queue full
1342  * @device_in_reset_drop_cnt: dropped due to device in reset
1343  * @max_cs_in_flight_drop_cnt: dropped due to maximum CS in-flight
1344  * @validation_drop_cnt: dropped due to error in validation
1345  */
1346 struct hl_cs_counters_atomic {
1347 	atomic64_t out_of_mem_drop_cnt;
1348 	atomic64_t parsing_drop_cnt;
1349 	atomic64_t queue_full_drop_cnt;
1350 	atomic64_t device_in_reset_drop_cnt;
1351 	atomic64_t max_cs_in_flight_drop_cnt;
1352 	atomic64_t validation_drop_cnt;
1353 };
1354 
1355 /**
1356  * struct hl_ctx - user/kernel context.
1357  * @mem_hash: holds mapping from virtual address to virtual memory area
1358  *		descriptor (hl_vm_phys_pg_list or hl_userptr).
1359  * @mmu_shadow_hash: holds a mapping from shadow address to pgt_info structure.
1360  * @hpriv: pointer to the private (Kernel Driver) data of the process (fd).
1361  * @hdev: pointer to the device structure.
1362  * @refcount: reference counter for the context. Context is released only when
1363  *		this hits 0l. It is incremented on CS and CS_WAIT.
1364  * @cs_pending: array of hl fence objects representing pending CS.
1365  * @va_range: holds available virtual addresses for host and dram mappings.
1366  * @mem_hash_lock: protects the mem_hash.
1367  * @mmu_lock: protects the MMU page tables. Any change to the PGT, modifying the
1368  *            MMU hash or walking the PGT requires talking this lock.
1369  * @hw_block_list_lock: protects the HW block memory list.
1370  * @debugfs_list: node in debugfs list of contexts.
1371  * @hw_block_mem_list: list of HW block virtual mapped addresses.
1372  * @cs_counters: context command submission counters.
1373  * @cb_va_pool: device VA pool for command buffers which are mapped to the
1374  *              device's MMU.
1375  * @sig_mgr: encaps signals handle manager.
1376  * @cs_sequence: sequence number for CS. Value is assigned to a CS and passed
1377  *			to user so user could inquire about CS. It is used as
1378  *			index to cs_pending array.
1379  * @dram_default_hops: array that holds all hops addresses needed for default
1380  *                     DRAM mapping.
1381  * @cs_lock: spinlock to protect cs_sequence.
1382  * @dram_phys_mem: amount of used physical DRAM memory by this context.
1383  * @thread_ctx_switch_token: token to prevent multiple threads of the same
1384  *				context	from running the context switch phase.
1385  *				Only a single thread should run it.
1386  * @thread_ctx_switch_wait_token: token to prevent the threads that didn't run
1387  *				the context switch phase from moving to their
1388  *				execution phase before the context switch phase
1389  *				has finished.
1390  * @asid: context's unique address space ID in the device's MMU.
1391  * @handle: context's opaque handle for user
1392  */
1393 struct hl_ctx {
1394 	DECLARE_HASHTABLE(mem_hash, MEM_HASH_TABLE_BITS);
1395 	DECLARE_HASHTABLE(mmu_shadow_hash, MMU_HASH_TABLE_BITS);
1396 	struct hl_fpriv			*hpriv;
1397 	struct hl_device		*hdev;
1398 	struct kref			refcount;
1399 	struct hl_fence			**cs_pending;
1400 	struct hl_va_range		*va_range[HL_VA_RANGE_TYPE_MAX];
1401 	struct mutex			mem_hash_lock;
1402 	struct mutex			mmu_lock;
1403 	struct mutex			hw_block_list_lock;
1404 	struct list_head		debugfs_list;
1405 	struct list_head		hw_block_mem_list;
1406 	struct hl_cs_counters_atomic	cs_counters;
1407 	struct gen_pool			*cb_va_pool;
1408 	struct hl_encaps_signals_mgr	sig_mgr;
1409 	u64				cs_sequence;
1410 	u64				*dram_default_hops;
1411 	spinlock_t			cs_lock;
1412 	atomic64_t			dram_phys_mem;
1413 	atomic_t			thread_ctx_switch_token;
1414 	u32				thread_ctx_switch_wait_token;
1415 	u32				asid;
1416 	u32				handle;
1417 };
1418 
1419 /**
1420  * struct hl_ctx_mgr - for handling multiple contexts.
1421  * @ctx_lock: protects ctx_handles.
1422  * @ctx_handles: idr to hold all ctx handles.
1423  */
1424 struct hl_ctx_mgr {
1425 	struct mutex		ctx_lock;
1426 	struct idr		ctx_handles;
1427 };
1428 
1429 
1430 
1431 /*
1432  * COMMAND SUBMISSIONS
1433  */
1434 
1435 /**
1436  * struct hl_userptr - memory mapping chunk information
1437  * @vm_type: type of the VM.
1438  * @job_node: linked-list node for hanging the object on the Job's list.
1439  * @pages: pointer to struct page array
1440  * @npages: size of @pages array
1441  * @sgt: pointer to the scatter-gather table that holds the pages.
1442  * @dir: for DMA unmapping, the direction must be supplied, so save it.
1443  * @debugfs_list: node in debugfs list of command submissions.
1444  * @pid: the pid of the user process owning the memory
1445  * @addr: user-space virtual address of the start of the memory area.
1446  * @size: size of the memory area to pin & map.
1447  * @dma_mapped: true if the SG was mapped to DMA addresses, false otherwise.
1448  */
1449 struct hl_userptr {
1450 	enum vm_type		vm_type; /* must be first */
1451 	struct list_head	job_node;
1452 	struct page		**pages;
1453 	unsigned int		npages;
1454 	struct sg_table		*sgt;
1455 	enum dma_data_direction dir;
1456 	struct list_head	debugfs_list;
1457 	pid_t			pid;
1458 	u64			addr;
1459 	u64			size;
1460 	u8			dma_mapped;
1461 };
1462 
1463 /**
1464  * struct hl_cs - command submission.
1465  * @jobs_in_queue_cnt: per each queue, maintain counter of submitted jobs.
1466  * @ctx: the context this CS belongs to.
1467  * @job_list: list of the CS's jobs in the various queues.
1468  * @job_lock: spinlock for the CS's jobs list. Needed for free_job.
1469  * @refcount: reference counter for usage of the CS.
1470  * @fence: pointer to the fence object of this CS.
1471  * @signal_fence: pointer to the fence object of the signal CS (used by wait
1472  *                CS only).
1473  * @finish_work: workqueue object to run when CS is completed by H/W.
1474  * @work_tdr: delayed work node for TDR.
1475  * @mirror_node : node in device mirror list of command submissions.
1476  * @staged_cs_node: node in the staged cs list.
1477  * @debugfs_list: node in debugfs list of command submissions.
1478  * @encaps_sig_hdl: holds the encaps signals handle.
1479  * @sequence: the sequence number of this CS.
1480  * @staged_sequence: the sequence of the staged submission this CS is part of,
1481  *                   relevant only if staged_cs is set.
1482  * @timeout_jiffies: cs timeout in jiffies.
1483  * @submission_time_jiffies: submission time of the cs
1484  * @type: CS_TYPE_*.
1485  * @encaps_sig_hdl_id: encaps signals handle id, set for the first staged cs.
1486  * @submitted: true if CS was submitted to H/W.
1487  * @completed: true if CS was completed by device.
1488  * @timedout : true if CS was timedout.
1489  * @tdr_active: true if TDR was activated for this CS (to prevent
1490  *		double TDR activation).
1491  * @aborted: true if CS was aborted due to some device error.
1492  * @timestamp: true if a timestmap must be captured upon completion.
1493  * @staged_last: true if this is the last staged CS and needs completion.
1494  * @staged_first: true if this is the first staged CS and we need to receive
1495  *                timeout for this CS.
1496  * @staged_cs: true if this CS is part of a staged submission.
1497  * @skip_reset_on_timeout: true if we shall not reset the device in case
1498  *                         timeout occurs (debug scenario).
1499  * @encaps_signals: true if this CS has encaps reserved signals.
1500  */
1501 struct hl_cs {
1502 	u16			*jobs_in_queue_cnt;
1503 	struct hl_ctx		*ctx;
1504 	struct list_head	job_list;
1505 	spinlock_t		job_lock;
1506 	struct kref		refcount;
1507 	struct hl_fence		*fence;
1508 	struct hl_fence		*signal_fence;
1509 	struct work_struct	finish_work;
1510 	struct delayed_work	work_tdr;
1511 	struct list_head	mirror_node;
1512 	struct list_head	staged_cs_node;
1513 	struct list_head	debugfs_list;
1514 	struct hl_cs_encaps_sig_handle *encaps_sig_hdl;
1515 	u64			sequence;
1516 	u64			staged_sequence;
1517 	u64			timeout_jiffies;
1518 	u64			submission_time_jiffies;
1519 	enum hl_cs_type		type;
1520 	u32			encaps_sig_hdl_id;
1521 	u8			submitted;
1522 	u8			completed;
1523 	u8			timedout;
1524 	u8			tdr_active;
1525 	u8			aborted;
1526 	u8			timestamp;
1527 	u8			staged_last;
1528 	u8			staged_first;
1529 	u8			staged_cs;
1530 	u8			skip_reset_on_timeout;
1531 	u8			encaps_signals;
1532 };
1533 
1534 /**
1535  * struct hl_cs_job - command submission job.
1536  * @cs_node: the node to hang on the CS jobs list.
1537  * @cs: the CS this job belongs to.
1538  * @user_cb: the CB we got from the user.
1539  * @patched_cb: in case of patching, this is internal CB which is submitted on
1540  *		the queue instead of the CB we got from the IOCTL.
1541  * @finish_work: workqueue object to run when job is completed.
1542  * @userptr_list: linked-list of userptr mappings that belong to this job and
1543  *			wait for completion.
1544  * @debugfs_list: node in debugfs list of command submission jobs.
1545  * @refcount: reference counter for usage of the CS job.
1546  * @queue_type: the type of the H/W queue this job is submitted to.
1547  * @id: the id of this job inside a CS.
1548  * @hw_queue_id: the id of the H/W queue this job is submitted to.
1549  * @user_cb_size: the actual size of the CB we got from the user.
1550  * @job_cb_size: the actual size of the CB that we put on the queue.
1551  * @encaps_sig_wait_offset: encapsulated signals offset, which allow user
1552  *                          to wait on part of the reserved signals.
1553  * @is_kernel_allocated_cb: true if the CB handle we got from the user holds a
1554  *                          handle to a kernel-allocated CB object, false
1555  *                          otherwise (SRAM/DRAM/host address).
1556  * @contains_dma_pkt: whether the JOB contains at least one DMA packet. This
1557  *                    info is needed later, when adding the 2xMSG_PROT at the
1558  *                    end of the JOB, to know which barriers to put in the
1559  *                    MSG_PROT packets. Relevant only for GAUDI as GOYA doesn't
1560  *                    have streams so the engine can't be busy by another
1561  *                    stream.
1562  */
1563 struct hl_cs_job {
1564 	struct list_head	cs_node;
1565 	struct hl_cs		*cs;
1566 	struct hl_cb		*user_cb;
1567 	struct hl_cb		*patched_cb;
1568 	struct work_struct	finish_work;
1569 	struct list_head	userptr_list;
1570 	struct list_head	debugfs_list;
1571 	struct kref		refcount;
1572 	enum hl_queue_type	queue_type;
1573 	u32			id;
1574 	u32			hw_queue_id;
1575 	u32			user_cb_size;
1576 	u32			job_cb_size;
1577 	u32			encaps_sig_wait_offset;
1578 	u8			is_kernel_allocated_cb;
1579 	u8			contains_dma_pkt;
1580 };
1581 
1582 /**
1583  * struct hl_cs_parser - command submission parser properties.
1584  * @user_cb: the CB we got from the user.
1585  * @patched_cb: in case of patching, this is internal CB which is submitted on
1586  *		the queue instead of the CB we got from the IOCTL.
1587  * @job_userptr_list: linked-list of userptr mappings that belong to the related
1588  *			job and wait for completion.
1589  * @cs_sequence: the sequence number of the related CS.
1590  * @queue_type: the type of the H/W queue this job is submitted to.
1591  * @ctx_id: the ID of the context the related CS belongs to.
1592  * @hw_queue_id: the id of the H/W queue this job is submitted to.
1593  * @user_cb_size: the actual size of the CB we got from the user.
1594  * @patched_cb_size: the size of the CB after parsing.
1595  * @job_id: the id of the related job inside the related CS.
1596  * @is_kernel_allocated_cb: true if the CB handle we got from the user holds a
1597  *                          handle to a kernel-allocated CB object, false
1598  *                          otherwise (SRAM/DRAM/host address).
1599  * @contains_dma_pkt: whether the JOB contains at least one DMA packet. This
1600  *                    info is needed later, when adding the 2xMSG_PROT at the
1601  *                    end of the JOB, to know which barriers to put in the
1602  *                    MSG_PROT packets. Relevant only for GAUDI as GOYA doesn't
1603  *                    have streams so the engine can't be busy by another
1604  *                    stream.
1605  * @completion: true if we need completion for this CS.
1606  */
1607 struct hl_cs_parser {
1608 	struct hl_cb		*user_cb;
1609 	struct hl_cb		*patched_cb;
1610 	struct list_head	*job_userptr_list;
1611 	u64			cs_sequence;
1612 	enum hl_queue_type	queue_type;
1613 	u32			ctx_id;
1614 	u32			hw_queue_id;
1615 	u32			user_cb_size;
1616 	u32			patched_cb_size;
1617 	u8			job_id;
1618 	u8			is_kernel_allocated_cb;
1619 	u8			contains_dma_pkt;
1620 	u8			completion;
1621 };
1622 
1623 /*
1624  * MEMORY STRUCTURE
1625  */
1626 
1627 /**
1628  * struct hl_vm_hash_node - hash element from virtual address to virtual
1629  *				memory area descriptor (hl_vm_phys_pg_list or
1630  *				hl_userptr).
1631  * @node: node to hang on the hash table in context object.
1632  * @vaddr: key virtual address.
1633  * @ptr: value pointer (hl_vm_phys_pg_list or hl_userptr).
1634  */
1635 struct hl_vm_hash_node {
1636 	struct hlist_node	node;
1637 	u64			vaddr;
1638 	void			*ptr;
1639 };
1640 
1641 /**
1642  * struct hl_vm_hw_block_list_node - list element from user virtual address to
1643  *				HW block id.
1644  * @node: node to hang on the list in context object.
1645  * @ctx: the context this node belongs to.
1646  * @vaddr: virtual address of the HW block.
1647  * @size: size of the block.
1648  * @id: HW block id (handle).
1649  */
1650 struct hl_vm_hw_block_list_node {
1651 	struct list_head	node;
1652 	struct hl_ctx		*ctx;
1653 	unsigned long		vaddr;
1654 	u32			size;
1655 	u32			id;
1656 };
1657 
1658 /**
1659  * struct hl_vm_phys_pg_pack - physical page pack.
1660  * @vm_type: describes the type of the virtual area descriptor.
1661  * @pages: the physical page array.
1662  * @npages: num physical pages in the pack.
1663  * @total_size: total size of all the pages in this list.
1664  * @mapping_cnt: number of shared mappings.
1665  * @asid: the context related to this list.
1666  * @page_size: size of each page in the pack.
1667  * @flags: HL_MEM_* flags related to this list.
1668  * @handle: the provided handle related to this list.
1669  * @offset: offset from the first page.
1670  * @contiguous: is contiguous physical memory.
1671  * @created_from_userptr: is product of host virtual address.
1672  */
1673 struct hl_vm_phys_pg_pack {
1674 	enum vm_type		vm_type; /* must be first */
1675 	u64			*pages;
1676 	u64			npages;
1677 	u64			total_size;
1678 	atomic_t		mapping_cnt;
1679 	u32			asid;
1680 	u32			page_size;
1681 	u32			flags;
1682 	u32			handle;
1683 	u32			offset;
1684 	u8			contiguous;
1685 	u8			created_from_userptr;
1686 };
1687 
1688 /**
1689  * struct hl_vm_va_block - virtual range block information.
1690  * @node: node to hang on the virtual range list in context object.
1691  * @start: virtual range start address.
1692  * @end: virtual range end address.
1693  * @size: virtual range size.
1694  */
1695 struct hl_vm_va_block {
1696 	struct list_head	node;
1697 	u64			start;
1698 	u64			end;
1699 	u64			size;
1700 };
1701 
1702 /**
1703  * struct hl_vm - virtual memory manager for MMU.
1704  * @dram_pg_pool: pool for DRAM physical pages of 2MB.
1705  * @dram_pg_pool_refcount: reference counter for the pool usage.
1706  * @idr_lock: protects the phys_pg_list_handles.
1707  * @phys_pg_pack_handles: idr to hold all device allocations handles.
1708  * @init_done: whether initialization was done. We need this because VM
1709  *		initialization might be skipped during device initialization.
1710  */
1711 struct hl_vm {
1712 	struct gen_pool		*dram_pg_pool;
1713 	struct kref		dram_pg_pool_refcount;
1714 	spinlock_t		idr_lock;
1715 	struct idr		phys_pg_pack_handles;
1716 	u8			init_done;
1717 };
1718 
1719 
1720 /*
1721  * DEBUG, PROFILING STRUCTURE
1722  */
1723 
1724 /**
1725  * struct hl_debug_params - Coresight debug parameters.
1726  * @input: pointer to component specific input parameters.
1727  * @output: pointer to component specific output parameters.
1728  * @output_size: size of output buffer.
1729  * @reg_idx: relevant register ID.
1730  * @op: component operation to execute.
1731  * @enable: true if to enable component debugging, false otherwise.
1732  */
1733 struct hl_debug_params {
1734 	void *input;
1735 	void *output;
1736 	u32 output_size;
1737 	u32 reg_idx;
1738 	u32 op;
1739 	bool enable;
1740 };
1741 
1742 /*
1743  * FILE PRIVATE STRUCTURE
1744  */
1745 
1746 /**
1747  * struct hl_fpriv - process information stored in FD private data.
1748  * @hdev: habanalabs device structure.
1749  * @filp: pointer to the given file structure.
1750  * @taskpid: current process ID.
1751  * @ctx: current executing context. TODO: remove for multiple ctx per process
1752  * @ctx_mgr: context manager to handle multiple context for this FD.
1753  * @cb_mgr: command buffer manager to handle multiple buffers for this FD.
1754  * @debugfs_list: list of relevant ASIC debugfs.
1755  * @dev_node: node in the device list of file private data
1756  * @refcount: number of related contexts.
1757  * @restore_phase_mutex: lock for context switch and restore phase.
1758  * @is_control: true for control device, false otherwise
1759  */
1760 struct hl_fpriv {
1761 	struct hl_device	*hdev;
1762 	struct file		*filp;
1763 	struct pid		*taskpid;
1764 	struct hl_ctx		*ctx;
1765 	struct hl_ctx_mgr	ctx_mgr;
1766 	struct hl_cb_mgr	cb_mgr;
1767 	struct list_head	debugfs_list;
1768 	struct list_head	dev_node;
1769 	struct kref		refcount;
1770 	struct mutex		restore_phase_mutex;
1771 	u8			is_control;
1772 };
1773 
1774 
1775 /*
1776  * DebugFS
1777  */
1778 
1779 /**
1780  * struct hl_info_list - debugfs file ops.
1781  * @name: file name.
1782  * @show: function to output information.
1783  * @write: function to write to the file.
1784  */
1785 struct hl_info_list {
1786 	const char	*name;
1787 	int		(*show)(struct seq_file *s, void *data);
1788 	ssize_t		(*write)(struct file *file, const char __user *buf,
1789 				size_t count, loff_t *f_pos);
1790 };
1791 
1792 /**
1793  * struct hl_debugfs_entry - debugfs dentry wrapper.
1794  * @info_ent: dentry realted ops.
1795  * @dev_entry: ASIC specific debugfs manager.
1796  */
1797 struct hl_debugfs_entry {
1798 	const struct hl_info_list	*info_ent;
1799 	struct hl_dbg_device_entry	*dev_entry;
1800 };
1801 
1802 /**
1803  * struct hl_dbg_device_entry - ASIC specific debugfs manager.
1804  * @root: root dentry.
1805  * @hdev: habanalabs device structure.
1806  * @entry_arr: array of available hl_debugfs_entry.
1807  * @file_list: list of available debugfs files.
1808  * @file_mutex: protects file_list.
1809  * @cb_list: list of available CBs.
1810  * @cb_spinlock: protects cb_list.
1811  * @cs_list: list of available CSs.
1812  * @cs_spinlock: protects cs_list.
1813  * @cs_job_list: list of available CB jobs.
1814  * @cs_job_spinlock: protects cs_job_list.
1815  * @userptr_list: list of available userptrs (virtual memory chunk descriptor).
1816  * @userptr_spinlock: protects userptr_list.
1817  * @ctx_mem_hash_list: list of available contexts with MMU mappings.
1818  * @ctx_mem_hash_spinlock: protects cb_list.
1819  * @blob_desc: descriptor of blob
1820  * @state_dump: data of the system states in case of a bad cs.
1821  * @state_dump_sem: protects state_dump.
1822  * @addr: next address to read/write from/to in read/write32.
1823  * @mmu_addr: next virtual address to translate to physical address in mmu_show.
1824  * @userptr_lookup: the target user ptr to look up for on demand.
1825  * @mmu_asid: ASID to use while translating in mmu_show.
1826  * @state_dump_head: index of the latest state dump
1827  * @i2c_bus: generic u8 debugfs file for bus value to use in i2c_data_read.
1828  * @i2c_addr: generic u8 debugfs file for address value to use in i2c_data_read.
1829  * @i2c_reg: generic u8 debugfs file for register value to use in i2c_data_read.
1830  */
1831 struct hl_dbg_device_entry {
1832 	struct dentry			*root;
1833 	struct hl_device		*hdev;
1834 	struct hl_debugfs_entry		*entry_arr;
1835 	struct list_head		file_list;
1836 	struct mutex			file_mutex;
1837 	struct list_head		cb_list;
1838 	spinlock_t			cb_spinlock;
1839 	struct list_head		cs_list;
1840 	spinlock_t			cs_spinlock;
1841 	struct list_head		cs_job_list;
1842 	spinlock_t			cs_job_spinlock;
1843 	struct list_head		userptr_list;
1844 	spinlock_t			userptr_spinlock;
1845 	struct list_head		ctx_mem_hash_list;
1846 	spinlock_t			ctx_mem_hash_spinlock;
1847 	struct debugfs_blob_wrapper	blob_desc;
1848 	char				*state_dump[HL_STATE_DUMP_HIST_LEN];
1849 	struct rw_semaphore		state_dump_sem;
1850 	u64				addr;
1851 	u64				mmu_addr;
1852 	u64				userptr_lookup;
1853 	u32				mmu_asid;
1854 	u32				state_dump_head;
1855 	u8				i2c_bus;
1856 	u8				i2c_addr;
1857 	u8				i2c_reg;
1858 };
1859 
1860 /**
1861  * struct hl_hw_obj_name_entry - single hw object name, member of
1862  * hl_state_dump_specs
1863  * @node: link to the containing hash table
1864  * @name: hw object name
1865  * @id: object identifier
1866  */
1867 struct hl_hw_obj_name_entry {
1868 	struct hlist_node	node;
1869 	const char		*name;
1870 	u32			id;
1871 };
1872 
1873 enum hl_state_dump_specs_props {
1874 	SP_SYNC_OBJ_BASE_ADDR,
1875 	SP_NEXT_SYNC_OBJ_ADDR,
1876 	SP_SYNC_OBJ_AMOUNT,
1877 	SP_MON_OBJ_WR_ADDR_LOW,
1878 	SP_MON_OBJ_WR_ADDR_HIGH,
1879 	SP_MON_OBJ_WR_DATA,
1880 	SP_MON_OBJ_ARM_DATA,
1881 	SP_MON_OBJ_STATUS,
1882 	SP_MONITORS_AMOUNT,
1883 	SP_TPC0_CMDQ,
1884 	SP_TPC0_CFG_SO,
1885 	SP_NEXT_TPC,
1886 	SP_MME_CMDQ,
1887 	SP_MME_CFG_SO,
1888 	SP_NEXT_MME,
1889 	SP_DMA_CMDQ,
1890 	SP_DMA_CFG_SO,
1891 	SP_DMA_QUEUES_OFFSET,
1892 	SP_NUM_OF_MME_ENGINES,
1893 	SP_SUB_MME_ENG_NUM,
1894 	SP_NUM_OF_DMA_ENGINES,
1895 	SP_NUM_OF_TPC_ENGINES,
1896 	SP_ENGINE_NUM_OF_QUEUES,
1897 	SP_ENGINE_NUM_OF_STREAMS,
1898 	SP_ENGINE_NUM_OF_FENCES,
1899 	SP_FENCE0_CNT_OFFSET,
1900 	SP_FENCE0_RDATA_OFFSET,
1901 	SP_CP_STS_OFFSET,
1902 	SP_NUM_CORES,
1903 
1904 	SP_MAX
1905 };
1906 
1907 enum hl_sync_engine_type {
1908 	ENGINE_TPC,
1909 	ENGINE_DMA,
1910 	ENGINE_MME,
1911 };
1912 
1913 /**
1914  * struct hl_mon_state_dump - represents a state dump of a single monitor
1915  * @id: monitor id
1916  * @wr_addr_low: address monitor will write to, low bits
1917  * @wr_addr_high: address monitor will write to, high bits
1918  * @wr_data: data monitor will write
1919  * @arm_data: register value containing monitor configuration
1920  * @status: monitor status
1921  */
1922 struct hl_mon_state_dump {
1923 	u32		id;
1924 	u32		wr_addr_low;
1925 	u32		wr_addr_high;
1926 	u32		wr_data;
1927 	u32		arm_data;
1928 	u32		status;
1929 };
1930 
1931 /**
1932  * struct hl_sync_to_engine_map_entry - sync object id to engine mapping entry
1933  * @engine_type: type of the engine
1934  * @engine_id: id of the engine
1935  * @sync_id: id of the sync object
1936  */
1937 struct hl_sync_to_engine_map_entry {
1938 	struct hlist_node		node;
1939 	enum hl_sync_engine_type	engine_type;
1940 	u32				engine_id;
1941 	u32				sync_id;
1942 };
1943 
1944 /**
1945  * struct hl_sync_to_engine_map - maps sync object id to associated engine id
1946  * @tb: hash table containing the mapping, each element is of type
1947  *      struct hl_sync_to_engine_map_entry
1948  */
1949 struct hl_sync_to_engine_map {
1950 	DECLARE_HASHTABLE(tb, SYNC_TO_ENGINE_HASH_TABLE_BITS);
1951 };
1952 
1953 /**
1954  * struct hl_state_dump_specs_funcs - virtual functions used by the state dump
1955  * @gen_sync_to_engine_map: generate a hash map from sync obj id to its engine
1956  * @print_single_monitor: format monitor data as string
1957  * @monitor_valid: return true if given monitor dump is valid
1958  * @print_fences_single_engine: format fences data as string
1959  */
1960 struct hl_state_dump_specs_funcs {
1961 	int (*gen_sync_to_engine_map)(struct hl_device *hdev,
1962 				struct hl_sync_to_engine_map *map);
1963 	int (*print_single_monitor)(char **buf, size_t *size, size_t *offset,
1964 				    struct hl_device *hdev,
1965 				    struct hl_mon_state_dump *mon);
1966 	int (*monitor_valid)(struct hl_mon_state_dump *mon);
1967 	int (*print_fences_single_engine)(struct hl_device *hdev,
1968 					u64 base_offset,
1969 					u64 status_base_offset,
1970 					enum hl_sync_engine_type engine_type,
1971 					u32 engine_id, char **buf,
1972 					size_t *size, size_t *offset);
1973 };
1974 
1975 /**
1976  * struct hl_state_dump_specs - defines ASIC known hw objects names
1977  * @so_id_to_str_tb: sync objects names index table
1978  * @monitor_id_to_str_tb: monitors names index table
1979  * @funcs: virtual functions used for state dump
1980  * @sync_namager_names: readable names for sync manager if available (ex: N_E)
1981  * @props: pointer to a per asic const props array required for state dump
1982  */
1983 struct hl_state_dump_specs {
1984 	DECLARE_HASHTABLE(so_id_to_str_tb, OBJ_NAMES_HASH_TABLE_BITS);
1985 	DECLARE_HASHTABLE(monitor_id_to_str_tb, OBJ_NAMES_HASH_TABLE_BITS);
1986 	struct hl_state_dump_specs_funcs	funcs;
1987 	const char * const			*sync_namager_names;
1988 	s64					*props;
1989 };
1990 
1991 
1992 /*
1993  * DEVICES
1994  */
1995 
1996 #define HL_STR_MAX	32
1997 
1998 #define HL_DEV_STS_MAX (HL_DEVICE_STATUS_LAST + 1)
1999 
2000 /* Theoretical limit only. A single host can only contain up to 4 or 8 PCIe
2001  * x16 cards. In extreme cases, there are hosts that can accommodate 16 cards.
2002  */
2003 #define HL_MAX_MINORS	256
2004 
2005 /*
2006  * Registers read & write functions.
2007  */
2008 
2009 u32 hl_rreg(struct hl_device *hdev, u32 reg);
2010 void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
2011 
2012 #define RREG32(reg) hdev->asic_funcs->rreg(hdev, (reg))
2013 #define WREG32(reg, v) hdev->asic_funcs->wreg(hdev, (reg), (v))
2014 #define DREG32(reg) pr_info("REGISTER: " #reg " : 0x%08X\n",	\
2015 			hdev->asic_funcs->rreg(hdev, (reg)))
2016 
2017 #define WREG32_P(reg, val, mask)				\
2018 	do {							\
2019 		u32 tmp_ = RREG32(reg);				\
2020 		tmp_ &= (mask);					\
2021 		tmp_ |= ((val) & ~(mask));			\
2022 		WREG32(reg, tmp_);				\
2023 	} while (0)
2024 #define WREG32_AND(reg, and) WREG32_P(reg, 0, and)
2025 #define WREG32_OR(reg, or) WREG32_P(reg, or, ~(or))
2026 
2027 #define RMWREG32(reg, val, mask)				\
2028 	do {							\
2029 		u32 tmp_ = RREG32(reg);				\
2030 		tmp_ &= ~(mask);				\
2031 		tmp_ |= ((val) << __ffs(mask));			\
2032 		WREG32(reg, tmp_);				\
2033 	} while (0)
2034 
2035 #define RREG32_MASK(reg, mask) ((RREG32(reg) & mask) >> __ffs(mask))
2036 
2037 #define REG_FIELD_SHIFT(reg, field) reg##_##field##_SHIFT
2038 #define REG_FIELD_MASK(reg, field) reg##_##field##_MASK
2039 #define WREG32_FIELD(reg, offset, field, val)	\
2040 	WREG32(mm##reg + offset, (RREG32(mm##reg + offset) & \
2041 				~REG_FIELD_MASK(reg, field)) | \
2042 				(val) << REG_FIELD_SHIFT(reg, field))
2043 
2044 /* Timeout should be longer when working with simulator but cap the
2045  * increased timeout to some maximum
2046  */
2047 #define hl_poll_timeout(hdev, addr, val, cond, sleep_us, timeout_us) \
2048 ({ \
2049 	ktime_t __timeout; \
2050 	if (hdev->pdev) \
2051 		__timeout = ktime_add_us(ktime_get(), timeout_us); \
2052 	else \
2053 		__timeout = ktime_add_us(ktime_get(),\
2054 				min((u64)(timeout_us * 10), \
2055 					(u64) HL_SIM_MAX_TIMEOUT_US)); \
2056 	might_sleep_if(sleep_us); \
2057 	for (;;) { \
2058 		(val) = RREG32(addr); \
2059 		if (cond) \
2060 			break; \
2061 		if (timeout_us && ktime_compare(ktime_get(), __timeout) > 0) { \
2062 			(val) = RREG32(addr); \
2063 			break; \
2064 		} \
2065 		if (sleep_us) \
2066 			usleep_range((sleep_us >> 2) + 1, sleep_us); \
2067 	} \
2068 	(cond) ? 0 : -ETIMEDOUT; \
2069 })
2070 
2071 /*
2072  * address in this macro points always to a memory location in the
2073  * host's (server's) memory. That location is updated asynchronously
2074  * either by the direct access of the device or by another core.
2075  *
2076  * To work both in LE and BE architectures, we need to distinguish between the
2077  * two states (device or another core updates the memory location). Therefore,
2078  * if mem_written_by_device is true, the host memory being polled will be
2079  * updated directly by the device. If false, the host memory being polled will
2080  * be updated by host CPU. Required so host knows whether or not the memory
2081  * might need to be byte-swapped before returning value to caller.
2082  */
2083 #define hl_poll_timeout_memory(hdev, addr, val, cond, sleep_us, timeout_us, \
2084 				mem_written_by_device) \
2085 ({ \
2086 	ktime_t __timeout; \
2087 	if (hdev->pdev) \
2088 		__timeout = ktime_add_us(ktime_get(), timeout_us); \
2089 	else \
2090 		__timeout = ktime_add_us(ktime_get(),\
2091 				min((u64)(timeout_us * 10), \
2092 					(u64) HL_SIM_MAX_TIMEOUT_US)); \
2093 	might_sleep_if(sleep_us); \
2094 	for (;;) { \
2095 		/* Verify we read updates done by other cores or by device */ \
2096 		mb(); \
2097 		(val) = *((u32 *)(addr)); \
2098 		if (mem_written_by_device) \
2099 			(val) = le32_to_cpu(*(__le32 *) &(val)); \
2100 		if (cond) \
2101 			break; \
2102 		if (timeout_us && ktime_compare(ktime_get(), __timeout) > 0) { \
2103 			(val) = *((u32 *)(addr)); \
2104 			if (mem_written_by_device) \
2105 				(val) = le32_to_cpu(*(__le32 *) &(val)); \
2106 			break; \
2107 		} \
2108 		if (sleep_us) \
2109 			usleep_range((sleep_us >> 2) + 1, sleep_us); \
2110 	} \
2111 	(cond) ? 0 : -ETIMEDOUT; \
2112 })
2113 
2114 #define hl_poll_timeout_device_memory(hdev, addr, val, cond, sleep_us, \
2115 					timeout_us) \
2116 ({ \
2117 	ktime_t __timeout; \
2118 	if (hdev->pdev) \
2119 		__timeout = ktime_add_us(ktime_get(), timeout_us); \
2120 	else \
2121 		__timeout = ktime_add_us(ktime_get(),\
2122 				min((u64)(timeout_us * 10), \
2123 					(u64) HL_SIM_MAX_TIMEOUT_US)); \
2124 	might_sleep_if(sleep_us); \
2125 	for (;;) { \
2126 		(val) = readl(addr); \
2127 		if (cond) \
2128 			break; \
2129 		if (timeout_us && ktime_compare(ktime_get(), __timeout) > 0) { \
2130 			(val) = readl(addr); \
2131 			break; \
2132 		} \
2133 		if (sleep_us) \
2134 			usleep_range((sleep_us >> 2) + 1, sleep_us); \
2135 	} \
2136 	(cond) ? 0 : -ETIMEDOUT; \
2137 })
2138 
2139 struct hwmon_chip_info;
2140 
2141 /**
2142  * struct hl_device_reset_work - reset workqueue task wrapper.
2143  * @wq: work queue for device reset procedure.
2144  * @reset_work: reset work to be done.
2145  * @hdev: habanalabs device structure.
2146  * @fw_reset: whether f/w will do the reset without us sending them a message to do it.
2147  */
2148 struct hl_device_reset_work {
2149 	struct workqueue_struct		*wq;
2150 	struct delayed_work		reset_work;
2151 	struct hl_device		*hdev;
2152 	bool				fw_reset;
2153 };
2154 
2155 /**
2156  * struct hr_mmu_hop_addrs - used for holding per-device host-resident mmu hop
2157  * information.
2158  * @virt_addr: the virtual address of the hop.
2159  * @phys-addr: the physical address of the hop (used by the device-mmu).
2160  * @shadow_addr: The shadow of the hop used by the driver for walking the hops.
2161  */
2162 struct hr_mmu_hop_addrs {
2163 	u64 virt_addr;
2164 	u64 phys_addr;
2165 	u64 shadow_addr;
2166 };
2167 
2168 /**
2169  * struct hl_mmu_hr_pgt_priv - used for holding per-device mmu host-resident
2170  * page-table internal information.
2171  * @mmu_pgt_pool: pool of page tables used by MMU for allocating hops.
2172  * @mmu_shadow_hop0: shadow array of hop0 tables.
2173  */
2174 struct hl_mmu_hr_priv {
2175 	struct gen_pool *mmu_pgt_pool;
2176 	struct hr_mmu_hop_addrs *mmu_shadow_hop0;
2177 };
2178 
2179 /**
2180  * struct hl_mmu_dr_pgt_priv - used for holding per-device mmu device-resident
2181  * page-table internal information.
2182  * @mmu_pgt_pool: pool of page tables used by MMU for allocating hops.
2183  * @mmu_shadow_hop0: shadow array of hop0 tables.
2184  */
2185 struct hl_mmu_dr_priv {
2186 	struct gen_pool *mmu_pgt_pool;
2187 	void *mmu_shadow_hop0;
2188 };
2189 
2190 /**
2191  * struct hl_mmu_priv - used for holding per-device mmu internal information.
2192  * @dr: information on the device-resident MMU, when exists.
2193  * @hr: information on the host-resident MMU, when exists.
2194  */
2195 struct hl_mmu_priv {
2196 	struct hl_mmu_dr_priv dr;
2197 	struct hl_mmu_hr_priv hr;
2198 };
2199 
2200 /**
2201  * struct hl_mmu_per_hop_info - A structure describing one TLB HOP and its entry
2202  *                that was created in order to translate a virtual address to a
2203  *                physical one.
2204  * @hop_addr: The address of the hop.
2205  * @hop_pte_addr: The address of the hop entry.
2206  * @hop_pte_val: The value in the hop entry.
2207  */
2208 struct hl_mmu_per_hop_info {
2209 	u64 hop_addr;
2210 	u64 hop_pte_addr;
2211 	u64 hop_pte_val;
2212 };
2213 
2214 /**
2215  * struct hl_mmu_hop_info - A structure describing the TLB hops and their
2216  * hop-entries that were created in order to translate a virtual address to a
2217  * physical one.
2218  * @scrambled_vaddr: The value of the virtual address after scrambling. This
2219  *                   address replaces the original virtual-address when mapped
2220  *                   in the MMU tables.
2221  * @unscrambled_paddr: The un-scrambled physical address.
2222  * @hop_info: Array holding the per-hop information used for the translation.
2223  * @used_hops: The number of hops used for the translation.
2224  * @range_type: virtual address range type.
2225  */
2226 struct hl_mmu_hop_info {
2227 	u64 scrambled_vaddr;
2228 	u64 unscrambled_paddr;
2229 	struct hl_mmu_per_hop_info hop_info[MMU_ARCH_5_HOPS];
2230 	u32 used_hops;
2231 	enum hl_va_range_type range_type;
2232 };
2233 
2234 /**
2235  * struct hl_mmu_funcs - Device related MMU functions.
2236  * @init: initialize the MMU module.
2237  * @fini: release the MMU module.
2238  * @ctx_init: Initialize a context for using the MMU module.
2239  * @ctx_fini: disable a ctx from using the mmu module.
2240  * @map: maps a virtual address to physical address for a context.
2241  * @unmap: unmap a virtual address of a context.
2242  * @flush: flush all writes from all cores to reach device MMU.
2243  * @swap_out: marks all mapping of the given context as swapped out.
2244  * @swap_in: marks all mapping of the given context as swapped in.
2245  * @get_tlb_info: returns the list of hops and hop-entries used that were
2246  *                created in order to translate the giver virtual address to a
2247  *                physical one.
2248  */
2249 struct hl_mmu_funcs {
2250 	int (*init)(struct hl_device *hdev);
2251 	void (*fini)(struct hl_device *hdev);
2252 	int (*ctx_init)(struct hl_ctx *ctx);
2253 	void (*ctx_fini)(struct hl_ctx *ctx);
2254 	int (*map)(struct hl_ctx *ctx,
2255 			u64 virt_addr, u64 phys_addr, u32 page_size,
2256 			bool is_dram_addr);
2257 	int (*unmap)(struct hl_ctx *ctx,
2258 			u64 virt_addr, bool is_dram_addr);
2259 	void (*flush)(struct hl_ctx *ctx);
2260 	void (*swap_out)(struct hl_ctx *ctx);
2261 	void (*swap_in)(struct hl_ctx *ctx);
2262 	int (*get_tlb_info)(struct hl_ctx *ctx,
2263 			u64 virt_addr, struct hl_mmu_hop_info *hops);
2264 };
2265 
2266 /**
2267  * number of user contexts allowed to call wait_for_multi_cs ioctl in
2268  * parallel
2269  */
2270 #define MULTI_CS_MAX_USER_CTX	2
2271 
2272 /**
2273  * struct multi_cs_completion - multi CS wait completion.
2274  * @completion: completion of any of the CS in the list
2275  * @lock: spinlock for the completion structure
2276  * @timestamp: timestamp for the multi-CS completion
2277  * @stream_master_qid_map: bitmap of all stream masters on which the multi-CS
2278  *                        is waiting
2279  * @used: 1 if in use, otherwise 0
2280  */
2281 struct multi_cs_completion {
2282 	struct completion	completion;
2283 	spinlock_t		lock;
2284 	s64			timestamp;
2285 	u32			stream_master_qid_map;
2286 	u8			used;
2287 };
2288 
2289 /**
2290  * struct multi_cs_data - internal data for multi CS call
2291  * @ctx: pointer to the context structure
2292  * @fence_arr: array of fences of all CSs
2293  * @seq_arr: array of CS sequence numbers
2294  * @timeout_us: timeout in usec for waiting for CS to complete
2295  * @timestamp: timestamp of first completed CS
2296  * @wait_status: wait for CS status
2297  * @completion_bitmap: bitmap of completed CSs (1- completed, otherwise 0)
2298  * @stream_master_qid_map: bitmap of all stream master QIDs on which the
2299  *                         multi-CS is waiting
2300  * @arr_len: fence_arr and seq_arr array length
2301  * @gone_cs: indication of gone CS (1- there was gone CS, otherwise 0)
2302  * @update_ts: update timestamp. 1- update the timestamp, otherwise 0.
2303  */
2304 struct multi_cs_data {
2305 	struct hl_ctx	*ctx;
2306 	struct hl_fence	**fence_arr;
2307 	u64		*seq_arr;
2308 	s64		timeout_us;
2309 	s64		timestamp;
2310 	long		wait_status;
2311 	u32		completion_bitmap;
2312 	u32		stream_master_qid_map;
2313 	u8		arr_len;
2314 	u8		gone_cs;
2315 	u8		update_ts;
2316 };
2317 
2318 /**
2319  * struct hl_device - habanalabs device structure.
2320  * @pdev: pointer to PCI device, can be NULL in case of simulator device.
2321  * @pcie_bar_phys: array of available PCIe bars physical addresses.
2322  *		   (required only for PCI address match mode)
2323  * @pcie_bar: array of available PCIe bars virtual addresses.
2324  * @rmmio: configuration area address on SRAM.
2325  * @cdev: related char device.
2326  * @cdev_ctrl: char device for control operations only (INFO IOCTL)
2327  * @dev: related kernel basic device structure.
2328  * @dev_ctrl: related kernel device structure for the control device
2329  * @work_freq: delayed work to lower device frequency if possible.
2330  * @work_heartbeat: delayed work for CPU-CP is-alive check.
2331  * @device_reset_work: delayed work which performs hard reset
2332  * @asic_name: ASIC specific name.
2333  * @asic_type: ASIC specific type.
2334  * @completion_queue: array of hl_cq.
2335  * @user_interrupt: array of hl_user_interrupt. upon the corresponding user
2336  *                  interrupt, driver will monitor the list of fences
2337  *                  registered to this interrupt.
2338  * @common_user_interrupt: common user interrupt for all user interrupts.
2339  *                         upon any user interrupt, driver will monitor the
2340  *                         list of fences registered to this common structure.
2341  * @cq_wq: work queues of completion queues for executing work in process
2342  *         context.
2343  * @eq_wq: work queue of event queue for executing work in process context.
2344  * @sob_reset_wq: work queue for sob reset executions.
2345  * @kernel_ctx: Kernel driver context structure.
2346  * @kernel_queues: array of hl_hw_queue.
2347  * @cs_mirror_list: CS mirror list for TDR.
2348  * @cs_mirror_lock: protects cs_mirror_list.
2349  * @kernel_cb_mgr: command buffer manager for creating/destroying/handling CBs.
2350  * @event_queue: event queue for IRQ from CPU-CP.
2351  * @dma_pool: DMA pool for small allocations.
2352  * @cpu_accessible_dma_mem: Host <-> CPU-CP shared memory CPU address.
2353  * @cpu_accessible_dma_address: Host <-> CPU-CP shared memory DMA address.
2354  * @cpu_accessible_dma_pool: Host <-> CPU-CP shared memory pool.
2355  * @asid_bitmap: holds used/available ASIDs.
2356  * @asid_mutex: protects asid_bitmap.
2357  * @send_cpu_message_lock: enforces only one message in Host <-> CPU-CP queue.
2358  * @debug_lock: protects critical section of setting debug mode for device
2359  * @asic_prop: ASIC specific immutable properties.
2360  * @asic_funcs: ASIC specific functions.
2361  * @asic_specific: ASIC specific information to use only from ASIC files.
2362  * @vm: virtual memory manager for MMU.
2363  * @hwmon_dev: H/W monitor device.
2364  * @pm_mng_profile: current power management profile.
2365  * @hl_chip_info: ASIC's sensors information.
2366  * @device_status_description: device status description.
2367  * @hl_debugfs: device's debugfs manager.
2368  * @cb_pool: list of preallocated CBs.
2369  * @cb_pool_lock: protects the CB pool.
2370  * @internal_cb_pool_virt_addr: internal command buffer pool virtual address.
2371  * @internal_cb_pool_dma_addr: internal command buffer pool dma address.
2372  * @internal_cb_pool: internal command buffer memory pool.
2373  * @internal_cb_va_base: internal cb pool mmu virtual address base
2374  * @fpriv_list: list of file private data structures. Each structure is created
2375  *              when a user opens the device
2376  * @fpriv_list_lock: protects the fpriv_list
2377  * @compute_ctx: current compute context executing.
2378  * @aggregated_cs_counters: aggregated cs counters among all contexts
2379  * @mmu_priv: device-specific MMU data.
2380  * @mmu_func: device-related MMU functions.
2381  * @fw_loader: FW loader manager.
2382  * @pci_mem_region: array of memory regions in the PCI
2383  * @state_dump_specs: constants and dictionaries needed to dump system state.
2384  * @multi_cs_completion: array of multi-CS completion.
2385  * @dram_used_mem: current DRAM memory consumption.
2386  * @timeout_jiffies: device CS timeout value.
2387  * @max_power: the max power of the device, as configured by the sysadmin. This
2388  *             value is saved so in case of hard-reset, the driver will restore
2389  *             this value and update the F/W after the re-initialization
2390  * @clock_gating_mask: is clock gating enabled. bitmask that represents the
2391  *                     different engines. See debugfs-driver-habanalabs for
2392  *                     details.
2393  * @boot_error_status_mask: contains a mask of the device boot error status.
2394  *                          Each bit represents a different error, according to
2395  *                          the defines in hl_boot_if.h. If the bit is cleared,
2396  *                          the error will be ignored by the driver during
2397  *                          device initialization. Mainly used to debug and
2398  *                          workaround firmware bugs
2399  * @last_successful_open_jif: timestamp (jiffies) of the last successful
2400  *                            device open.
2401  * @last_open_session_duration_jif: duration (jiffies) of the last device open
2402  *                                  session.
2403  * @open_counter: number of successful device open operations.
2404  * @in_reset: is device in reset flow.
2405  * @curr_pll_profile: current PLL profile.
2406  * @card_type: Various ASICs have several card types. This indicates the card
2407  *             type of the current device.
2408  * @major: habanalabs kernel driver major.
2409  * @high_pll: high PLL profile frequency.
2410  * @soft_reset_cnt: number of soft reset since the driver was loaded.
2411  * @hard_reset_cnt: number of hard reset since the driver was loaded.
2412  * @clk_throttling_reason: bitmask represents the current clk throttling reasons
2413  * @id: device minor.
2414  * @id_control: minor of the control device
2415  * @cpu_pci_msb_addr: 50-bit extension bits for the device CPU's 40-bit
2416  *                    addresses.
2417  * @disabled: is device disabled.
2418  * @late_init_done: is late init stage was done during initialization.
2419  * @hwmon_initialized: is H/W monitor sensors was initialized.
2420  * @hard_reset_pending: is there a hard reset work pending.
2421  * @heartbeat: is heartbeat sanity check towards CPU-CP enabled.
2422  * @reset_on_lockup: true if a reset should be done in case of stuck CS, false
2423  *                   otherwise.
2424  * @dram_default_page_mapping: is DRAM default page mapping enabled.
2425  * @memory_scrub: true to perform device memory scrub in various locations,
2426  *                such as context-switch, context close, page free, etc.
2427  * @pmmu_huge_range: is a different virtual addresses range used for PMMU with
2428  *                   huge pages.
2429  * @init_done: is the initialization of the device done.
2430  * @device_cpu_disabled: is the device CPU disabled (due to timeouts)
2431  * @dma_mask: the dma mask that was set for this device
2432  * @in_debug: is device under debug. This, together with fpriv_list, enforces
2433  *            that only a single user is configuring the debug infrastructure.
2434  * @power9_64bit_dma_enable: true to enable 64-bit DMA mask support. Relevant
2435  *                           only to POWER9 machines.
2436  * @cdev_sysfs_created: were char devices and sysfs nodes created.
2437  * @stop_on_err: true if engines should stop on error.
2438  * @supports_sync_stream: is sync stream supported.
2439  * @sync_stream_queue_idx: helper index for sync stream queues initialization.
2440  * @collective_mon_idx: helper index for collective initialization
2441  * @supports_coresight: is CoreSight supported.
2442  * @supports_soft_reset: is soft reset supported.
2443  * @allow_external_soft_reset: true if soft reset initiated by user or TDR is
2444  *                             allowed.
2445  * @supports_cb_mapping: is mapping a CB to the device's MMU supported.
2446  * @needs_reset: true if reset_on_lockup is false and device should be reset
2447  *               due to lockup.
2448  * @process_kill_trial_cnt: number of trials reset thread tried killing
2449  *                          user processes
2450  * @device_fini_pending: true if device_fini was called and might be
2451  *                       waiting for the reset thread to finish
2452  * @supports_staged_submission: true if staged submissions are supported
2453  * @curr_reset_cause: saves an enumerated reset cause when a hard reset is
2454  *                    triggered, and cleared after it is shared with preboot.
2455  * @skip_reset_on_timeout: Skip device reset if CS has timed out, wait for it to
2456  *                         complete instead.
2457  * @device_cpu_is_halted: Flag to indicate whether the device CPU was already
2458  *                        halted. We can't halt it again because the COMMS
2459  *                        protocol will throw an error. Relevant only for
2460  *                        cases where Linux was not loaded to device CPU
2461  * @supports_wait_for_multi_cs: true if wait for multi CS is supported
2462  */
2463 struct hl_device {
2464 	struct pci_dev			*pdev;
2465 	u64				pcie_bar_phys[HL_PCI_NUM_BARS];
2466 	void __iomem			*pcie_bar[HL_PCI_NUM_BARS];
2467 	void __iomem			*rmmio;
2468 	struct cdev			cdev;
2469 	struct cdev			cdev_ctrl;
2470 	struct device			*dev;
2471 	struct device			*dev_ctrl;
2472 	struct delayed_work		work_freq;
2473 	struct delayed_work		work_heartbeat;
2474 	struct hl_device_reset_work	device_reset_work;
2475 	char				asic_name[HL_STR_MAX];
2476 	char				status[HL_DEV_STS_MAX][HL_STR_MAX];
2477 	enum hl_asic_type		asic_type;
2478 	struct hl_cq			*completion_queue;
2479 	struct hl_user_interrupt	*user_interrupt;
2480 	struct hl_user_interrupt	common_user_interrupt;
2481 	struct workqueue_struct		**cq_wq;
2482 	struct workqueue_struct		*eq_wq;
2483 	struct workqueue_struct		*sob_reset_wq;
2484 	struct hl_ctx			*kernel_ctx;
2485 	struct hl_hw_queue		*kernel_queues;
2486 	struct list_head		cs_mirror_list;
2487 	spinlock_t			cs_mirror_lock;
2488 	struct hl_cb_mgr		kernel_cb_mgr;
2489 	struct hl_eq			event_queue;
2490 	struct dma_pool			*dma_pool;
2491 	void				*cpu_accessible_dma_mem;
2492 	dma_addr_t			cpu_accessible_dma_address;
2493 	struct gen_pool			*cpu_accessible_dma_pool;
2494 	unsigned long			*asid_bitmap;
2495 	struct mutex			asid_mutex;
2496 	struct mutex			send_cpu_message_lock;
2497 	struct mutex			debug_lock;
2498 	struct asic_fixed_properties	asic_prop;
2499 	const struct hl_asic_funcs	*asic_funcs;
2500 	void				*asic_specific;
2501 	struct hl_vm			vm;
2502 	struct device			*hwmon_dev;
2503 	enum hl_pm_mng_profile		pm_mng_profile;
2504 	struct hwmon_chip_info		*hl_chip_info;
2505 
2506 	struct hl_dbg_device_entry	hl_debugfs;
2507 
2508 	struct list_head		cb_pool;
2509 	spinlock_t			cb_pool_lock;
2510 
2511 	void				*internal_cb_pool_virt_addr;
2512 	dma_addr_t			internal_cb_pool_dma_addr;
2513 	struct gen_pool			*internal_cb_pool;
2514 	u64				internal_cb_va_base;
2515 
2516 	struct list_head		fpriv_list;
2517 	struct mutex			fpriv_list_lock;
2518 
2519 	struct hl_ctx			*compute_ctx;
2520 
2521 	struct hl_cs_counters_atomic	aggregated_cs_counters;
2522 
2523 	struct hl_mmu_priv		mmu_priv;
2524 	struct hl_mmu_funcs		mmu_func[MMU_NUM_PGT_LOCATIONS];
2525 
2526 	struct fw_load_mgr		fw_loader;
2527 
2528 	struct pci_mem_region		pci_mem_region[PCI_REGION_NUMBER];
2529 
2530 	struct hl_state_dump_specs	state_dump_specs;
2531 
2532 	struct multi_cs_completion	multi_cs_completion[
2533 							MULTI_CS_MAX_USER_CTX];
2534 	u32				*stream_master_qid_arr;
2535 	atomic64_t			dram_used_mem;
2536 	u64				timeout_jiffies;
2537 	u64				max_power;
2538 	u64				clock_gating_mask;
2539 	u64				boot_error_status_mask;
2540 	u64				last_successful_open_jif;
2541 	u64				last_open_session_duration_jif;
2542 	u64				open_counter;
2543 	atomic_t			in_reset;
2544 	enum hl_pll_frequency		curr_pll_profile;
2545 	enum cpucp_card_types		card_type;
2546 	u32				major;
2547 	u32				high_pll;
2548 	u32				soft_reset_cnt;
2549 	u32				hard_reset_cnt;
2550 	u32				clk_throttling_reason;
2551 	u16				id;
2552 	u16				id_control;
2553 	u16				cpu_pci_msb_addr;
2554 	u8				disabled;
2555 	u8				late_init_done;
2556 	u8				hwmon_initialized;
2557 	u8				hard_reset_pending;
2558 	u8				heartbeat;
2559 	u8				reset_on_lockup;
2560 	u8				dram_default_page_mapping;
2561 	u8				memory_scrub;
2562 	u8				pmmu_huge_range;
2563 	u8				init_done;
2564 	u8				device_cpu_disabled;
2565 	u8				dma_mask;
2566 	u8				in_debug;
2567 	u8				power9_64bit_dma_enable;
2568 	u8				cdev_sysfs_created;
2569 	u8				stop_on_err;
2570 	u8				supports_sync_stream;
2571 	u8				sync_stream_queue_idx;
2572 	u8				collective_mon_idx;
2573 	u8				supports_coresight;
2574 	u8				supports_soft_reset;
2575 	u8				allow_external_soft_reset;
2576 	u8				supports_cb_mapping;
2577 	u8				needs_reset;
2578 	u8				process_kill_trial_cnt;
2579 	u8				device_fini_pending;
2580 	u8				supports_staged_submission;
2581 	u8				curr_reset_cause;
2582 	u8				skip_reset_on_timeout;
2583 	u8				device_cpu_is_halted;
2584 	u8				supports_wait_for_multi_cs;
2585 	u8				stream_master_qid_arr_size;
2586 
2587 	/* Parameters for bring-up */
2588 	u64				nic_ports_mask;
2589 	u64				fw_components;
2590 	u8				mmu_enable;
2591 	u8				mmu_huge_page_opt;
2592 	u8				reset_pcilink;
2593 	u8				cpu_queues_enable;
2594 	u8				pldm;
2595 	u8				axi_drain;
2596 	u8				sram_scrambler_enable;
2597 	u8				dram_scrambler_enable;
2598 	u8				hard_reset_on_fw_events;
2599 	u8				bmc_enable;
2600 	u8				rl_enable;
2601 	u8				reset_on_preboot_fail;
2602 	u8				reset_upon_device_release;
2603 	u8				reset_if_device_not_idle;
2604 };
2605 
2606 
2607 /**
2608  * struct hl_cs_encaps_sig_handle - encapsulated signals handle structure
2609  * @refcount: refcount used to protect removing this id when several
2610  *            wait cs are used to wait of the reserved encaps signals.
2611  * @hdev: pointer to habanalabs device structure.
2612  * @hw_sob: pointer to  H/W SOB used in the reservation.
2613  * @cs_seq: staged cs sequence which contains encapsulated signals
2614  * @id: idr handler id to be used to fetch the handler info
2615  * @q_idx: stream queue index
2616  * @pre_sob_val: current SOB value before reservation
2617  * @count: signals number
2618  */
2619 struct hl_cs_encaps_sig_handle {
2620 	struct kref refcount;
2621 	struct hl_device *hdev;
2622 	struct hl_hw_sob *hw_sob;
2623 	u64  cs_seq;
2624 	u32  id;
2625 	u32  q_idx;
2626 	u32  pre_sob_val;
2627 	u32  count;
2628 };
2629 
2630 /*
2631  * IOCTLs
2632  */
2633 
2634 /**
2635  * typedef hl_ioctl_t - typedef for ioctl function in the driver
2636  * @hpriv: pointer to the FD's private data, which contains state of
2637  *		user process
2638  * @data: pointer to the input/output arguments structure of the IOCTL
2639  *
2640  * Return: 0 for success, negative value for error
2641  */
2642 typedef int hl_ioctl_t(struct hl_fpriv *hpriv, void *data);
2643 
2644 /**
2645  * struct hl_ioctl_desc - describes an IOCTL entry of the driver.
2646  * @cmd: the IOCTL code as created by the kernel macros.
2647  * @func: pointer to the driver's function that should be called for this IOCTL.
2648  */
2649 struct hl_ioctl_desc {
2650 	unsigned int cmd;
2651 	hl_ioctl_t *func;
2652 };
2653 
2654 
2655 /*
2656  * Kernel module functions that can be accessed by entire module
2657  */
2658 
2659 /**
2660  * hl_get_sg_info() - get number of pages and the DMA address from SG list.
2661  * @sg: the SG list.
2662  * @dma_addr: pointer to DMA address to return.
2663  *
2664  * Calculate the number of consecutive pages described by the SG list. Take the
2665  * offset of the address in the first page, add to it the length and round it up
2666  * to the number of needed pages.
2667  */
hl_get_sg_info(struct scatterlist * sg,dma_addr_t * dma_addr)2668 static inline u32 hl_get_sg_info(struct scatterlist *sg, dma_addr_t *dma_addr)
2669 {
2670 	*dma_addr = sg_dma_address(sg);
2671 
2672 	return ((((*dma_addr) & (PAGE_SIZE - 1)) + sg_dma_len(sg)) +
2673 			(PAGE_SIZE - 1)) >> PAGE_SHIFT;
2674 }
2675 
2676 /**
2677  * hl_mem_area_inside_range() - Checks whether address+size are inside a range.
2678  * @address: The start address of the area we want to validate.
2679  * @size: The size in bytes of the area we want to validate.
2680  * @range_start_address: The start address of the valid range.
2681  * @range_end_address: The end address of the valid range.
2682  *
2683  * Return: true if the area is inside the valid range, false otherwise.
2684  */
hl_mem_area_inside_range(u64 address,u64 size,u64 range_start_address,u64 range_end_address)2685 static inline bool hl_mem_area_inside_range(u64 address, u64 size,
2686 				u64 range_start_address, u64 range_end_address)
2687 {
2688 	u64 end_address = address + size;
2689 
2690 	if ((address >= range_start_address) &&
2691 			(end_address <= range_end_address) &&
2692 			(end_address > address))
2693 		return true;
2694 
2695 	return false;
2696 }
2697 
2698 /**
2699  * hl_mem_area_crosses_range() - Checks whether address+size crossing a range.
2700  * @address: The start address of the area we want to validate.
2701  * @size: The size in bytes of the area we want to validate.
2702  * @range_start_address: The start address of the valid range.
2703  * @range_end_address: The end address of the valid range.
2704  *
2705  * Return: true if the area overlaps part or all of the valid range,
2706  *		false otherwise.
2707  */
hl_mem_area_crosses_range(u64 address,u32 size,u64 range_start_address,u64 range_end_address)2708 static inline bool hl_mem_area_crosses_range(u64 address, u32 size,
2709 				u64 range_start_address, u64 range_end_address)
2710 {
2711 	u64 end_address = address + size;
2712 
2713 	if ((address >= range_start_address) &&
2714 			(address < range_end_address))
2715 		return true;
2716 
2717 	if ((end_address >= range_start_address) &&
2718 			(end_address < range_end_address))
2719 		return true;
2720 
2721 	if ((address < range_start_address) &&
2722 			(end_address >= range_end_address))
2723 		return true;
2724 
2725 	return false;
2726 }
2727 
2728 int hl_device_open(struct inode *inode, struct file *filp);
2729 int hl_device_open_ctrl(struct inode *inode, struct file *filp);
2730 bool hl_device_operational(struct hl_device *hdev,
2731 		enum hl_device_status *status);
2732 enum hl_device_status hl_device_status(struct hl_device *hdev);
2733 int hl_device_set_debug_mode(struct hl_device *hdev, bool enable);
2734 int create_hdev(struct hl_device **dev, struct pci_dev *pdev,
2735 		enum hl_asic_type asic_type, int minor);
2736 void destroy_hdev(struct hl_device *hdev);
2737 int hl_hw_queues_create(struct hl_device *hdev);
2738 void hl_hw_queues_destroy(struct hl_device *hdev);
2739 int hl_hw_queue_send_cb_no_cmpl(struct hl_device *hdev, u32 hw_queue_id,
2740 		u32 cb_size, u64 cb_ptr);
2741 void hl_hw_queue_submit_bd(struct hl_device *hdev, struct hl_hw_queue *q,
2742 		u32 ctl, u32 len, u64 ptr);
2743 int hl_hw_queue_schedule_cs(struct hl_cs *cs);
2744 u32 hl_hw_queue_add_ptr(u32 ptr, u16 val);
2745 void hl_hw_queue_inc_ci_kernel(struct hl_device *hdev, u32 hw_queue_id);
2746 void hl_hw_queue_update_ci(struct hl_cs *cs);
2747 void hl_hw_queue_reset(struct hl_device *hdev, bool hard_reset);
2748 
2749 #define hl_queue_inc_ptr(p)		hl_hw_queue_add_ptr(p, 1)
2750 #define hl_pi_2_offset(pi)		((pi) & (HL_QUEUE_LENGTH - 1))
2751 
2752 int hl_cq_init(struct hl_device *hdev, struct hl_cq *q, u32 hw_queue_id);
2753 void hl_cq_fini(struct hl_device *hdev, struct hl_cq *q);
2754 int hl_eq_init(struct hl_device *hdev, struct hl_eq *q);
2755 void hl_eq_fini(struct hl_device *hdev, struct hl_eq *q);
2756 void hl_cq_reset(struct hl_device *hdev, struct hl_cq *q);
2757 void hl_eq_reset(struct hl_device *hdev, struct hl_eq *q);
2758 irqreturn_t hl_irq_handler_cq(int irq, void *arg);
2759 irqreturn_t hl_irq_handler_eq(int irq, void *arg);
2760 irqreturn_t hl_irq_handler_user_cq(int irq, void *arg);
2761 irqreturn_t hl_irq_handler_default(int irq, void *arg);
2762 u32 hl_cq_inc_ptr(u32 ptr);
2763 
2764 int hl_asid_init(struct hl_device *hdev);
2765 void hl_asid_fini(struct hl_device *hdev);
2766 unsigned long hl_asid_alloc(struct hl_device *hdev);
2767 void hl_asid_free(struct hl_device *hdev, unsigned long asid);
2768 
2769 int hl_ctx_create(struct hl_device *hdev, struct hl_fpriv *hpriv);
2770 void hl_ctx_free(struct hl_device *hdev, struct hl_ctx *ctx);
2771 int hl_ctx_init(struct hl_device *hdev, struct hl_ctx *ctx, bool is_kernel_ctx);
2772 void hl_ctx_do_release(struct kref *ref);
2773 void hl_ctx_get(struct hl_device *hdev,	struct hl_ctx *ctx);
2774 int hl_ctx_put(struct hl_ctx *ctx);
2775 struct hl_fence *hl_ctx_get_fence(struct hl_ctx *ctx, u64 seq);
2776 int hl_ctx_get_fences(struct hl_ctx *ctx, u64 *seq_arr,
2777 				struct hl_fence **fence, u32 arr_len);
2778 void hl_ctx_mgr_init(struct hl_ctx_mgr *mgr);
2779 void hl_ctx_mgr_fini(struct hl_device *hdev, struct hl_ctx_mgr *mgr);
2780 
2781 int hl_device_init(struct hl_device *hdev, struct class *hclass);
2782 void hl_device_fini(struct hl_device *hdev);
2783 int hl_device_suspend(struct hl_device *hdev);
2784 int hl_device_resume(struct hl_device *hdev);
2785 int hl_device_reset(struct hl_device *hdev, u32 flags);
2786 void hl_hpriv_get(struct hl_fpriv *hpriv);
2787 int hl_hpriv_put(struct hl_fpriv *hpriv);
2788 int hl_device_set_frequency(struct hl_device *hdev, enum hl_pll_frequency freq);
2789 int hl_device_utilization(struct hl_device *hdev, u32 *utilization);
2790 
2791 int hl_build_hwmon_channel_info(struct hl_device *hdev,
2792 		struct cpucp_sensor *sensors_arr);
2793 
2794 int hl_sysfs_init(struct hl_device *hdev);
2795 void hl_sysfs_fini(struct hl_device *hdev);
2796 
2797 int hl_hwmon_init(struct hl_device *hdev);
2798 void hl_hwmon_fini(struct hl_device *hdev);
2799 
2800 int hl_cb_create(struct hl_device *hdev, struct hl_cb_mgr *mgr,
2801 			struct hl_ctx *ctx, u32 cb_size, bool internal_cb,
2802 			bool map_cb, u64 *handle);
2803 int hl_cb_destroy(struct hl_device *hdev, struct hl_cb_mgr *mgr, u64 cb_handle);
2804 int hl_cb_mmap(struct hl_fpriv *hpriv, struct vm_area_struct *vma);
2805 int hl_hw_block_mmap(struct hl_fpriv *hpriv, struct vm_area_struct *vma);
2806 struct hl_cb *hl_cb_get(struct hl_device *hdev,	struct hl_cb_mgr *mgr,
2807 			u32 handle);
2808 void hl_cb_put(struct hl_cb *cb);
2809 void hl_cb_mgr_init(struct hl_cb_mgr *mgr);
2810 void hl_cb_mgr_fini(struct hl_device *hdev, struct hl_cb_mgr *mgr);
2811 struct hl_cb *hl_cb_kernel_create(struct hl_device *hdev, u32 cb_size,
2812 					bool internal_cb);
2813 int hl_cb_pool_init(struct hl_device *hdev);
2814 int hl_cb_pool_fini(struct hl_device *hdev);
2815 int hl_cb_va_pool_init(struct hl_ctx *ctx);
2816 void hl_cb_va_pool_fini(struct hl_ctx *ctx);
2817 
2818 void hl_cs_rollback_all(struct hl_device *hdev);
2819 struct hl_cs_job *hl_cs_allocate_job(struct hl_device *hdev,
2820 		enum hl_queue_type queue_type, bool is_kernel_allocated_cb);
2821 void hl_sob_reset_error(struct kref *ref);
2822 int hl_gen_sob_mask(u16 sob_base, u8 sob_mask, u8 *mask);
2823 void hl_fence_put(struct hl_fence *fence);
2824 void hl_fences_put(struct hl_fence **fence, int len);
2825 void hl_fence_get(struct hl_fence *fence);
2826 void cs_get(struct hl_cs *cs);
2827 bool cs_needs_completion(struct hl_cs *cs);
2828 bool cs_needs_timeout(struct hl_cs *cs);
2829 bool is_staged_cs_last_exists(struct hl_device *hdev, struct hl_cs *cs);
2830 struct hl_cs *hl_staged_cs_find_first(struct hl_device *hdev, u64 cs_seq);
2831 void hl_multi_cs_completion_init(struct hl_device *hdev);
2832 
2833 void goya_set_asic_funcs(struct hl_device *hdev);
2834 void gaudi_set_asic_funcs(struct hl_device *hdev);
2835 
2836 int hl_vm_ctx_init(struct hl_ctx *ctx);
2837 void hl_vm_ctx_fini(struct hl_ctx *ctx);
2838 
2839 int hl_vm_init(struct hl_device *hdev);
2840 void hl_vm_fini(struct hl_device *hdev);
2841 
2842 void hl_hw_block_mem_init(struct hl_ctx *ctx);
2843 void hl_hw_block_mem_fini(struct hl_ctx *ctx);
2844 
2845 u64 hl_reserve_va_block(struct hl_device *hdev, struct hl_ctx *ctx,
2846 		enum hl_va_range_type type, u32 size, u32 alignment);
2847 int hl_unreserve_va_block(struct hl_device *hdev, struct hl_ctx *ctx,
2848 		u64 start_addr, u64 size);
2849 int hl_pin_host_memory(struct hl_device *hdev, u64 addr, u64 size,
2850 			struct hl_userptr *userptr);
2851 void hl_unpin_host_memory(struct hl_device *hdev, struct hl_userptr *userptr);
2852 void hl_userptr_delete_list(struct hl_device *hdev,
2853 				struct list_head *userptr_list);
2854 bool hl_userptr_is_pinned(struct hl_device *hdev, u64 addr, u32 size,
2855 				struct list_head *userptr_list,
2856 				struct hl_userptr **userptr);
2857 
2858 int hl_mmu_init(struct hl_device *hdev);
2859 void hl_mmu_fini(struct hl_device *hdev);
2860 int hl_mmu_ctx_init(struct hl_ctx *ctx);
2861 void hl_mmu_ctx_fini(struct hl_ctx *ctx);
2862 int hl_mmu_map_page(struct hl_ctx *ctx, u64 virt_addr, u64 phys_addr,
2863 		u32 page_size, bool flush_pte);
2864 int hl_mmu_unmap_page(struct hl_ctx *ctx, u64 virt_addr, u32 page_size,
2865 		bool flush_pte);
2866 int hl_mmu_map_contiguous(struct hl_ctx *ctx, u64 virt_addr,
2867 					u64 phys_addr, u32 size);
2868 int hl_mmu_unmap_contiguous(struct hl_ctx *ctx, u64 virt_addr, u32 size);
2869 void hl_mmu_swap_out(struct hl_ctx *ctx);
2870 void hl_mmu_swap_in(struct hl_ctx *ctx);
2871 int hl_mmu_if_set_funcs(struct hl_device *hdev);
2872 void hl_mmu_v1_set_funcs(struct hl_device *hdev, struct hl_mmu_funcs *mmu);
2873 int hl_mmu_va_to_pa(struct hl_ctx *ctx, u64 virt_addr, u64 *phys_addr);
2874 int hl_mmu_get_tlb_info(struct hl_ctx *ctx, u64 virt_addr,
2875 			struct hl_mmu_hop_info *hops);
2876 u64 hl_mmu_scramble_addr(struct hl_device *hdev, u64 addr);
2877 u64 hl_mmu_descramble_addr(struct hl_device *hdev, u64 addr);
2878 bool hl_is_dram_va(struct hl_device *hdev, u64 virt_addr);
2879 
2880 int hl_fw_load_fw_to_device(struct hl_device *hdev, const char *fw_name,
2881 				void __iomem *dst, u32 src_offset, u32 size);
2882 int hl_fw_send_pci_access_msg(struct hl_device *hdev, u32 opcode);
2883 int hl_fw_send_cpu_message(struct hl_device *hdev, u32 hw_queue_id, u32 *msg,
2884 				u16 len, u32 timeout, u64 *result);
2885 int hl_fw_unmask_irq(struct hl_device *hdev, u16 event_type);
2886 int hl_fw_unmask_irq_arr(struct hl_device *hdev, const u32 *irq_arr,
2887 		size_t irq_arr_size);
2888 int hl_fw_test_cpu_queue(struct hl_device *hdev);
2889 void *hl_fw_cpu_accessible_dma_pool_alloc(struct hl_device *hdev, size_t size,
2890 						dma_addr_t *dma_handle);
2891 void hl_fw_cpu_accessible_dma_pool_free(struct hl_device *hdev, size_t size,
2892 					void *vaddr);
2893 int hl_fw_send_heartbeat(struct hl_device *hdev);
2894 int hl_fw_cpucp_info_get(struct hl_device *hdev,
2895 				u32 sts_boot_dev_sts0_reg,
2896 				u32 sts_boot_dev_sts1_reg, u32 boot_err0_reg,
2897 				u32 boot_err1_reg);
2898 int hl_fw_cpucp_handshake(struct hl_device *hdev,
2899 				u32 sts_boot_dev_sts0_reg,
2900 				u32 sts_boot_dev_sts1_reg, u32 boot_err0_reg,
2901 				u32 boot_err1_reg);
2902 int hl_fw_get_eeprom_data(struct hl_device *hdev, void *data, size_t max_size);
2903 int hl_fw_cpucp_pci_counters_get(struct hl_device *hdev,
2904 		struct hl_info_pci_counters *counters);
2905 int hl_fw_cpucp_total_energy_get(struct hl_device *hdev,
2906 			u64 *total_energy);
2907 int get_used_pll_index(struct hl_device *hdev, u32 input_pll_index,
2908 						enum pll_index *pll_index);
2909 int hl_fw_cpucp_pll_info_get(struct hl_device *hdev, u32 pll_index,
2910 		u16 *pll_freq_arr);
2911 int hl_fw_cpucp_power_get(struct hl_device *hdev, u64 *power);
2912 void hl_fw_ask_hard_reset_without_linux(struct hl_device *hdev);
2913 void hl_fw_ask_halt_machine_without_linux(struct hl_device *hdev);
2914 int hl_fw_init_cpu(struct hl_device *hdev);
2915 int hl_fw_read_preboot_status(struct hl_device *hdev, u32 cpu_boot_status_reg,
2916 				u32 sts_boot_dev_sts0_reg,
2917 				u32 sts_boot_dev_sts1_reg, u32 boot_err0_reg,
2918 				u32 boot_err1_reg, u32 timeout);
2919 int hl_fw_dynamic_send_protocol_cmd(struct hl_device *hdev,
2920 				struct fw_load_mgr *fw_loader,
2921 				enum comms_cmd cmd, unsigned int size,
2922 				bool wait_ok, u32 timeout);
2923 int hl_pci_bars_map(struct hl_device *hdev, const char * const name[3],
2924 			bool is_wc[3]);
2925 int hl_pci_elbi_read(struct hl_device *hdev, u64 addr, u32 *data);
2926 int hl_pci_iatu_write(struct hl_device *hdev, u32 addr, u32 data);
2927 int hl_pci_set_inbound_region(struct hl_device *hdev, u8 region,
2928 		struct hl_inbound_pci_region *pci_region);
2929 int hl_pci_set_outbound_region(struct hl_device *hdev,
2930 		struct hl_outbound_pci_region *pci_region);
2931 enum pci_region hl_get_pci_memory_region(struct hl_device *hdev, u64 addr);
2932 int hl_pci_init(struct hl_device *hdev);
2933 void hl_pci_fini(struct hl_device *hdev);
2934 
2935 long hl_get_frequency(struct hl_device *hdev, u32 pll_index,
2936 								bool curr);
2937 void hl_set_frequency(struct hl_device *hdev, u32 pll_index,
2938 								u64 freq);
2939 int hl_get_temperature(struct hl_device *hdev,
2940 		       int sensor_index, u32 attr, long *value);
2941 int hl_set_temperature(struct hl_device *hdev,
2942 		       int sensor_index, u32 attr, long value);
2943 int hl_get_voltage(struct hl_device *hdev,
2944 		   int sensor_index, u32 attr, long *value);
2945 int hl_get_current(struct hl_device *hdev,
2946 		   int sensor_index, u32 attr, long *value);
2947 int hl_get_fan_speed(struct hl_device *hdev,
2948 		     int sensor_index, u32 attr, long *value);
2949 int hl_get_pwm_info(struct hl_device *hdev,
2950 		    int sensor_index, u32 attr, long *value);
2951 void hl_set_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr,
2952 			long value);
2953 u64 hl_get_max_power(struct hl_device *hdev);
2954 void hl_set_max_power(struct hl_device *hdev);
2955 int hl_set_voltage(struct hl_device *hdev,
2956 			int sensor_index, u32 attr, long value);
2957 int hl_set_current(struct hl_device *hdev,
2958 			int sensor_index, u32 attr, long value);
2959 void hw_sob_get(struct hl_hw_sob *hw_sob);
2960 void hw_sob_put(struct hl_hw_sob *hw_sob);
2961 void hl_encaps_handle_do_release(struct kref *ref);
2962 void hl_hw_queue_encaps_sig_set_sob_info(struct hl_device *hdev,
2963 			struct hl_cs *cs, struct hl_cs_job *job,
2964 			struct hl_cs_compl *cs_cmpl);
2965 void hl_release_pending_user_interrupts(struct hl_device *hdev);
2966 int hl_cs_signal_sob_wraparound_handler(struct hl_device *hdev, u32 q_idx,
2967 			struct hl_hw_sob **hw_sob, u32 count, bool encaps_sig);
2968 
2969 int hl_state_dump(struct hl_device *hdev);
2970 const char *hl_state_dump_get_sync_name(struct hl_device *hdev, u32 sync_id);
2971 const char *hl_state_dump_get_monitor_name(struct hl_device *hdev,
2972 					struct hl_mon_state_dump *mon);
2973 void hl_state_dump_free_sync_to_engine_map(struct hl_sync_to_engine_map *map);
2974 __printf(4, 5) int hl_snprintf_resize(char **buf, size_t *size, size_t *offset,
2975 					const char *format, ...);
2976 char *hl_format_as_binary(char *buf, size_t buf_len, u32 n);
2977 const char *hl_sync_engine_to_string(enum hl_sync_engine_type engine_type);
2978 
2979 #ifdef CONFIG_DEBUG_FS
2980 
2981 void hl_debugfs_init(void);
2982 void hl_debugfs_fini(void);
2983 void hl_debugfs_add_device(struct hl_device *hdev);
2984 void hl_debugfs_remove_device(struct hl_device *hdev);
2985 void hl_debugfs_add_file(struct hl_fpriv *hpriv);
2986 void hl_debugfs_remove_file(struct hl_fpriv *hpriv);
2987 void hl_debugfs_add_cb(struct hl_cb *cb);
2988 void hl_debugfs_remove_cb(struct hl_cb *cb);
2989 void hl_debugfs_add_cs(struct hl_cs *cs);
2990 void hl_debugfs_remove_cs(struct hl_cs *cs);
2991 void hl_debugfs_add_job(struct hl_device *hdev, struct hl_cs_job *job);
2992 void hl_debugfs_remove_job(struct hl_device *hdev, struct hl_cs_job *job);
2993 void hl_debugfs_add_userptr(struct hl_device *hdev, struct hl_userptr *userptr);
2994 void hl_debugfs_remove_userptr(struct hl_device *hdev,
2995 				struct hl_userptr *userptr);
2996 void hl_debugfs_add_ctx_mem_hash(struct hl_device *hdev, struct hl_ctx *ctx);
2997 void hl_debugfs_remove_ctx_mem_hash(struct hl_device *hdev, struct hl_ctx *ctx);
2998 void hl_debugfs_set_state_dump(struct hl_device *hdev, char *data,
2999 					unsigned long length);
3000 
3001 #else
3002 
hl_debugfs_init(void)3003 static inline void __init hl_debugfs_init(void)
3004 {
3005 }
3006 
hl_debugfs_fini(void)3007 static inline void hl_debugfs_fini(void)
3008 {
3009 }
3010 
hl_debugfs_add_device(struct hl_device * hdev)3011 static inline void hl_debugfs_add_device(struct hl_device *hdev)
3012 {
3013 }
3014 
hl_debugfs_remove_device(struct hl_device * hdev)3015 static inline void hl_debugfs_remove_device(struct hl_device *hdev)
3016 {
3017 }
3018 
hl_debugfs_add_file(struct hl_fpriv * hpriv)3019 static inline void hl_debugfs_add_file(struct hl_fpriv *hpriv)
3020 {
3021 }
3022 
hl_debugfs_remove_file(struct hl_fpriv * hpriv)3023 static inline void hl_debugfs_remove_file(struct hl_fpriv *hpriv)
3024 {
3025 }
3026 
hl_debugfs_add_cb(struct hl_cb * cb)3027 static inline void hl_debugfs_add_cb(struct hl_cb *cb)
3028 {
3029 }
3030 
hl_debugfs_remove_cb(struct hl_cb * cb)3031 static inline void hl_debugfs_remove_cb(struct hl_cb *cb)
3032 {
3033 }
3034 
hl_debugfs_add_cs(struct hl_cs * cs)3035 static inline void hl_debugfs_add_cs(struct hl_cs *cs)
3036 {
3037 }
3038 
hl_debugfs_remove_cs(struct hl_cs * cs)3039 static inline void hl_debugfs_remove_cs(struct hl_cs *cs)
3040 {
3041 }
3042 
hl_debugfs_add_job(struct hl_device * hdev,struct hl_cs_job * job)3043 static inline void hl_debugfs_add_job(struct hl_device *hdev,
3044 					struct hl_cs_job *job)
3045 {
3046 }
3047 
hl_debugfs_remove_job(struct hl_device * hdev,struct hl_cs_job * job)3048 static inline void hl_debugfs_remove_job(struct hl_device *hdev,
3049 					struct hl_cs_job *job)
3050 {
3051 }
3052 
hl_debugfs_add_userptr(struct hl_device * hdev,struct hl_userptr * userptr)3053 static inline void hl_debugfs_add_userptr(struct hl_device *hdev,
3054 					struct hl_userptr *userptr)
3055 {
3056 }
3057 
hl_debugfs_remove_userptr(struct hl_device * hdev,struct hl_userptr * userptr)3058 static inline void hl_debugfs_remove_userptr(struct hl_device *hdev,
3059 					struct hl_userptr *userptr)
3060 {
3061 }
3062 
hl_debugfs_add_ctx_mem_hash(struct hl_device * hdev,struct hl_ctx * ctx)3063 static inline void hl_debugfs_add_ctx_mem_hash(struct hl_device *hdev,
3064 					struct hl_ctx *ctx)
3065 {
3066 }
3067 
hl_debugfs_remove_ctx_mem_hash(struct hl_device * hdev,struct hl_ctx * ctx)3068 static inline void hl_debugfs_remove_ctx_mem_hash(struct hl_device *hdev,
3069 					struct hl_ctx *ctx)
3070 {
3071 }
3072 
hl_debugfs_set_state_dump(struct hl_device * hdev,char * data,unsigned long length)3073 static inline void hl_debugfs_set_state_dump(struct hl_device *hdev,
3074 					char *data, unsigned long length)
3075 {
3076 }
3077 
3078 #endif
3079 
3080 /* IOCTLs */
3081 long hl_ioctl(struct file *filep, unsigned int cmd, unsigned long arg);
3082 long hl_ioctl_control(struct file *filep, unsigned int cmd, unsigned long arg);
3083 int hl_cb_ioctl(struct hl_fpriv *hpriv, void *data);
3084 int hl_cs_ioctl(struct hl_fpriv *hpriv, void *data);
3085 int hl_wait_ioctl(struct hl_fpriv *hpriv, void *data);
3086 int hl_mem_ioctl(struct hl_fpriv *hpriv, void *data);
3087 
3088 #endif /* HABANALABSP_H_ */
3089