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