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