Back to home page

OSCL-LXR

 
 

    


0001 /* SPDX-License-Identifier: GPL-2.0
0002  *
0003  * Copyright 2016-2022 HabanaLabs, Ltd.
0004  * All Rights Reserved.
0005  *
0006  */
0007 
0008 #ifndef HABANALABSP_H_
0009 #define HABANALABSP_H_
0010 
0011 #include "../include/common/cpucp_if.h"
0012 #include "../include/common/qman_if.h"
0013 #include "../include/hw_ip/mmu/mmu_general.h"
0014 #include <uapi/misc/habanalabs.h>
0015 
0016 #include <linux/cdev.h>
0017 #include <linux/iopoll.h>
0018 #include <linux/irqreturn.h>
0019 #include <linux/dma-direction.h>
0020 #include <linux/scatterlist.h>
0021 #include <linux/hashtable.h>
0022 #include <linux/debugfs.h>
0023 #include <linux/rwsem.h>
0024 #include <linux/eventfd.h>
0025 #include <linux/bitfield.h>
0026 #include <linux/genalloc.h>
0027 #include <linux/sched/signal.h>
0028 #include <linux/io-64-nonatomic-lo-hi.h>
0029 #include <linux/coresight.h>
0030 #include <linux/dma-buf.h>
0031 
0032 #define HL_NAME             "habanalabs"
0033 
0034 struct hl_device;
0035 struct hl_fpriv;
0036 
0037 /* Use upper bits of mmap offset to store habana driver specific information.
0038  * bits[63:59] - Encode mmap type
0039  * bits[45:0]  - mmap offset value
0040  *
0041  * NOTE: struct vm_area_struct.vm_pgoff uses offset in pages. Hence, these
0042  *  defines are w.r.t to PAGE_SIZE
0043  */
0044 #define HL_MMAP_TYPE_SHIFT      (59 - PAGE_SHIFT)
0045 #define HL_MMAP_TYPE_MASK       (0x1full << HL_MMAP_TYPE_SHIFT)
0046 #define HL_MMAP_TYPE_TS_BUFF        (0x10ull << HL_MMAP_TYPE_SHIFT)
0047 #define HL_MMAP_TYPE_BLOCK      (0x4ull << HL_MMAP_TYPE_SHIFT)
0048 #define HL_MMAP_TYPE_CB         (0x2ull << HL_MMAP_TYPE_SHIFT)
0049 
0050 #define HL_MMAP_OFFSET_VALUE_MASK   (0x1FFFFFFFFFFFull >> PAGE_SHIFT)
0051 #define HL_MMAP_OFFSET_VALUE_GET(off)   (off & HL_MMAP_OFFSET_VALUE_MASK)
0052 
0053 #define HL_PENDING_RESET_PER_SEC    10
0054 #define HL_PENDING_RESET_MAX_TRIALS 60 /* 10 minutes */
0055 #define HL_PENDING_RESET_LONG_SEC   60
0056 
0057 #define HL_HARD_RESET_MAX_TIMEOUT   120
0058 #define HL_PLDM_HARD_RESET_MAX_TIMEOUT  (HL_HARD_RESET_MAX_TIMEOUT * 3)
0059 
0060 #define HL_DEVICE_TIMEOUT_USEC      1000000 /* 1 s */
0061 
0062 #define HL_HEARTBEAT_PER_USEC       5000000 /* 5 s */
0063 
0064 #define HL_PLL_LOW_JOB_FREQ_USEC    5000000 /* 5 s */
0065 
0066 #define HL_CPUCP_INFO_TIMEOUT_USEC  10000000 /* 10s */
0067 #define HL_CPUCP_EEPROM_TIMEOUT_USEC    10000000 /* 10s */
0068 #define HL_CPUCP_MON_DUMP_TIMEOUT_USEC  10000000 /* 10s */
0069 
0070 #define HL_FW_STATUS_POLL_INTERVAL_USEC     10000 /* 10ms */
0071 #define HL_FW_COMMS_STATUS_PLDM_POLL_INTERVAL_USEC  1000000 /* 1s */
0072 
0073 #define HL_PCI_ELBI_TIMEOUT_MSEC    10 /* 10ms */
0074 
0075 #define HL_SIM_MAX_TIMEOUT_US       100000000 /* 100s */
0076 
0077 #define HL_INVALID_QUEUE        UINT_MAX
0078 
0079 #define HL_COMMON_USER_CQ_INTERRUPT_ID  0xFFF
0080 #define HL_COMMON_DEC_INTERRUPT_ID  0xFFE
0081 
0082 #define HL_STATE_DUMP_HIST_LEN      5
0083 
0084 /* Default value for device reset trigger , an invalid value */
0085 #define HL_RESET_TRIGGER_DEFAULT    0xFF
0086 
0087 #define OBJ_NAMES_HASH_TABLE_BITS   7 /* 1 << 7 buckets */
0088 #define SYNC_TO_ENGINE_HASH_TABLE_BITS  7 /* 1 << 7 buckets */
0089 
0090 /* Memory */
0091 #define MEM_HASH_TABLE_BITS     7 /* 1 << 7 buckets */
0092 
0093 /* MMU */
0094 #define MMU_HASH_TABLE_BITS     7 /* 1 << 7 buckets */
0095 
0096 /**
0097  * enum hl_mmu_page_table_locaion - mmu page table location
0098  * @MMU_DR_PGT: page-table is located on device DRAM.
0099  * @MMU_HR_PGT: page-table is located on host memory.
0100  * @MMU_NUM_PGT_LOCATIONS: number of page-table locations currently supported.
0101  */
0102 enum hl_mmu_page_table_location {
0103     MMU_DR_PGT = 0,     /* device-dram-resident MMU PGT */
0104     MMU_HR_PGT,     /* host resident MMU PGT */
0105     MMU_NUM_PGT_LOCATIONS   /* num of PGT locations */
0106 };
0107 
0108 /**
0109  * enum hl_mmu_enablement - what mmu modules to enable
0110  * @MMU_EN_NONE: mmu disabled.
0111  * @MMU_EN_ALL: enable all.
0112  * @MMU_EN_PMMU_ONLY: Enable only the PMMU leaving the DMMU disabled.
0113  */
0114 enum hl_mmu_enablement {
0115     MMU_EN_NONE = 0,
0116     MMU_EN_ALL = 1,
0117     MMU_EN_PMMU_ONLY = 3,   /* N/A for Goya/Gaudi */
0118 };
0119 
0120 /*
0121  * HL_RSVD_SOBS 'sync stream' reserved sync objects per QMAN stream
0122  * HL_RSVD_MONS 'sync stream' reserved monitors per QMAN stream
0123  */
0124 #define HL_RSVD_SOBS            2
0125 #define HL_RSVD_MONS            1
0126 
0127 /*
0128  * HL_COLLECTIVE_RSVD_MSTR_MONS 'collective' reserved monitors per QMAN stream
0129  */
0130 #define HL_COLLECTIVE_RSVD_MSTR_MONS    2
0131 
0132 #define HL_MAX_SOB_VAL          (1 << 15)
0133 
0134 #define IS_POWER_OF_2(n)        (n != 0 && ((n & (n - 1)) == 0))
0135 #define IS_MAX_PENDING_CS_VALID(n)  (IS_POWER_OF_2(n) && (n > 1))
0136 
0137 #define HL_PCI_NUM_BARS         6
0138 
0139 /* Completion queue entry relates to completed job */
0140 #define HL_COMPLETION_MODE_JOB      0
0141 /* Completion queue entry relates to completed command submission */
0142 #define HL_COMPLETION_MODE_CS       1
0143 
0144 #define HL_MAX_DCORES           8
0145 
0146 /*
0147  * Reset Flags
0148  *
0149  * - HL_DRV_RESET_HARD
0150  *       If set do hard reset to all engines. If not set reset just
0151  *       compute/DMA engines.
0152  *
0153  * - HL_DRV_RESET_FROM_RESET_THR
0154  *       Set if the caller is the hard-reset thread
0155  *
0156  * - HL_DRV_RESET_HEARTBEAT
0157  *       Set if reset is due to heartbeat
0158  *
0159  * - HL_DRV_RESET_TDR
0160  *       Set if reset is due to TDR
0161  *
0162  * - HL_DRV_RESET_DEV_RELEASE
0163  *       Set if reset is due to device release
0164  *
0165  * - HL_DRV_RESET_BYPASS_REQ_TO_FW
0166  *       F/W will perform the reset. No need to ask it to reset the device. This is relevant
0167  *       only when running with secured f/w
0168  *
0169  * - HL_DRV_RESET_FW_FATAL_ERR
0170  *       Set if reset is due to a fatal error from FW
0171  *
0172  * - HL_DRV_RESET_DELAY
0173  *       Set if a delay should be added before the reset
0174  */
0175 
0176 #define HL_DRV_RESET_HARD       (1 << 0)
0177 #define HL_DRV_RESET_FROM_RESET_THR (1 << 1)
0178 #define HL_DRV_RESET_HEARTBEAT      (1 << 2)
0179 #define HL_DRV_RESET_TDR        (1 << 3)
0180 #define HL_DRV_RESET_DEV_RELEASE    (1 << 4)
0181 #define HL_DRV_RESET_BYPASS_REQ_TO_FW   (1 << 5)
0182 #define HL_DRV_RESET_FW_FATAL_ERR   (1 << 6)
0183 #define HL_DRV_RESET_DELAY      (1 << 7)
0184 
0185 /*
0186  * Security
0187  */
0188 
0189 #define HL_PB_SHARED        1
0190 #define HL_PB_NA        0
0191 #define HL_PB_SINGLE_INSTANCE   1
0192 #define HL_BLOCK_SIZE       0x1000
0193 #define HL_BLOCK_GLBL_ERR_MASK  0xF40
0194 #define HL_BLOCK_GLBL_ERR_ADDR  0xF44
0195 #define HL_BLOCK_GLBL_ERR_CAUSE 0xF48
0196 #define HL_BLOCK_GLBL_SEC_OFFS  0xF80
0197 #define HL_BLOCK_GLBL_SEC_SIZE  (HL_BLOCK_SIZE - HL_BLOCK_GLBL_SEC_OFFS)
0198 #define HL_BLOCK_GLBL_SEC_LEN   (HL_BLOCK_GLBL_SEC_SIZE / sizeof(u32))
0199 #define UNSET_GLBL_SEC_BIT(array, b) ((array)[((b) / 32)] |= (1 << ((b) % 32)))
0200 
0201 enum hl_protection_levels {
0202     SECURED_LVL,
0203     PRIVILEGED_LVL,
0204     NON_SECURED_LVL
0205 };
0206 
0207 /**
0208  * struct iterate_module_ctx - HW module iterator
0209  * @fn: function to apply to each HW module instance
0210  * @data: optional internal data to the function iterator
0211  */
0212 struct iterate_module_ctx {
0213     /*
0214      * callback for the HW module iterator
0215      * @hdev: pointer to the habanalabs device structure
0216      * @block: block (ASIC specific definition can be dcore/hdcore)
0217      * @inst: HW module instance within the block
0218      * @offset: current HW module instance offset from the 1-st HW module instance
0219      *          in the 1-st block
0220      * @data: function specific data
0221      */
0222     void (*fn)(struct hl_device *hdev, int block, int inst, u32 offset, void *data);
0223     void *data;
0224 };
0225 
0226 struct hl_block_glbl_sec {
0227     u32 sec_array[HL_BLOCK_GLBL_SEC_LEN];
0228 };
0229 
0230 #define HL_MAX_SOBS_PER_MONITOR 8
0231 
0232 /**
0233  * struct hl_gen_wait_properties - properties for generating a wait CB
0234  * @data: command buffer
0235  * @q_idx: queue id is used to extract fence register address
0236  * @size: offset in command buffer
0237  * @sob_base: SOB base to use in this wait CB
0238  * @sob_val: SOB value to wait for
0239  * @mon_id: monitor to use in this wait CB
0240  * @sob_mask: each bit represents a SOB offset from sob_base to be used
0241  */
0242 struct hl_gen_wait_properties {
0243     void    *data;
0244     u32 q_idx;
0245     u32 size;
0246     u16 sob_base;
0247     u16 sob_val;
0248     u16 mon_id;
0249     u8  sob_mask;
0250 };
0251 
0252 /**
0253  * struct pgt_info - MMU hop page info.
0254  * @node: hash linked-list node for the pgts on host (shadow pgts for device resident MMU and
0255  *        actual pgts for host resident MMU).
0256  * @phys_addr: physical address of the pgt.
0257  * @virt_addr: host virtual address of the pgt (see above device/host resident).
0258  * @shadow_addr: shadow hop in the host for device resident MMU.
0259  * @ctx: pointer to the owner ctx.
0260  * @num_of_ptes: indicates how many ptes are used in the pgt. used only for dynamically
0261  *               allocated HOPs (all HOPs but HOP0)
0262  *
0263  * The MMU page tables hierarchy can be placed either on the device's DRAM (in which case shadow
0264  * pgts will be stored on host memory) or on host memory (in which case no shadow is required).
0265  *
0266  * When a new level (hop) is needed during mapping this structure will be used to describe
0267  * the newly allocated hop as well as to track number of PTEs in it.
0268  * During unmapping, if no valid PTEs remained in the page of a newly allocated hop, it is
0269  * freed with its pgt_info structure.
0270  */
0271 struct pgt_info {
0272     struct hlist_node   node;
0273     u64         phys_addr;
0274     u64         virt_addr;
0275     u64         shadow_addr;
0276     struct hl_ctx       *ctx;
0277     int         num_of_ptes;
0278 };
0279 
0280 /**
0281  * enum hl_pci_match_mode - pci match mode per region
0282  * @PCI_ADDRESS_MATCH_MODE: address match mode
0283  * @PCI_BAR_MATCH_MODE: bar match mode
0284  */
0285 enum hl_pci_match_mode {
0286     PCI_ADDRESS_MATCH_MODE,
0287     PCI_BAR_MATCH_MODE
0288 };
0289 
0290 /**
0291  * enum hl_fw_component - F/W components to read version through registers.
0292  * @FW_COMP_BOOT_FIT: boot fit.
0293  * @FW_COMP_PREBOOT: preboot.
0294  * @FW_COMP_LINUX: linux.
0295  */
0296 enum hl_fw_component {
0297     FW_COMP_BOOT_FIT,
0298     FW_COMP_PREBOOT,
0299     FW_COMP_LINUX,
0300 };
0301 
0302 /**
0303  * enum hl_fw_types - F/W types present in the system
0304  * @FW_TYPE_NONE: no FW component indication
0305  * @FW_TYPE_LINUX: Linux image for device CPU
0306  * @FW_TYPE_BOOT_CPU: Boot image for device CPU
0307  * @FW_TYPE_PREBOOT_CPU: Indicates pre-loaded CPUs are present in the system
0308  *                       (preboot, ppboot etc...)
0309  * @FW_TYPE_ALL_TYPES: Mask for all types
0310  */
0311 enum hl_fw_types {
0312     FW_TYPE_NONE = 0x0,
0313     FW_TYPE_LINUX = 0x1,
0314     FW_TYPE_BOOT_CPU = 0x2,
0315     FW_TYPE_PREBOOT_CPU = 0x4,
0316     FW_TYPE_ALL_TYPES =
0317         (FW_TYPE_LINUX | FW_TYPE_BOOT_CPU | FW_TYPE_PREBOOT_CPU)
0318 };
0319 
0320 /**
0321  * enum hl_queue_type - Supported QUEUE types.
0322  * @QUEUE_TYPE_NA: queue is not available.
0323  * @QUEUE_TYPE_EXT: external queue which is a DMA channel that may access the
0324  *                  host.
0325  * @QUEUE_TYPE_INT: internal queue that performs DMA inside the device's
0326  *          memories and/or operates the compute engines.
0327  * @QUEUE_TYPE_CPU: S/W queue for communication with the device's CPU.
0328  * @QUEUE_TYPE_HW: queue of DMA and compute engines jobs, for which completion
0329  *                 notifications are sent by H/W.
0330  */
0331 enum hl_queue_type {
0332     QUEUE_TYPE_NA,
0333     QUEUE_TYPE_EXT,
0334     QUEUE_TYPE_INT,
0335     QUEUE_TYPE_CPU,
0336     QUEUE_TYPE_HW
0337 };
0338 
0339 enum hl_cs_type {
0340     CS_TYPE_DEFAULT,
0341     CS_TYPE_SIGNAL,
0342     CS_TYPE_WAIT,
0343     CS_TYPE_COLLECTIVE_WAIT,
0344     CS_RESERVE_SIGNALS,
0345     CS_UNRESERVE_SIGNALS
0346 };
0347 
0348 /*
0349  * struct hl_inbound_pci_region - inbound region descriptor
0350  * @mode: pci match mode for this region
0351  * @addr: region target address
0352  * @size: region size in bytes
0353  * @offset_in_bar: offset within bar (address match mode)
0354  * @bar: bar id
0355  */
0356 struct hl_inbound_pci_region {
0357     enum hl_pci_match_mode  mode;
0358     u64         addr;
0359     u64         size;
0360     u64         offset_in_bar;
0361     u8          bar;
0362 };
0363 
0364 /*
0365  * struct hl_outbound_pci_region - outbound region descriptor
0366  * @addr: region target address
0367  * @size: region size in bytes
0368  */
0369 struct hl_outbound_pci_region {
0370     u64 addr;
0371     u64 size;
0372 };
0373 
0374 /*
0375  * enum queue_cb_alloc_flags - Indicates queue support for CBs that
0376  * allocated by Kernel or by User
0377  * @CB_ALLOC_KERNEL: support only CBs that allocated by Kernel
0378  * @CB_ALLOC_USER: support only CBs that allocated by User
0379  */
0380 enum queue_cb_alloc_flags {
0381     CB_ALLOC_KERNEL = 0x1,
0382     CB_ALLOC_USER   = 0x2
0383 };
0384 
0385 /*
0386  * struct hl_hw_sob - H/W SOB info.
0387  * @hdev: habanalabs device structure.
0388  * @kref: refcount of this SOB. The SOB will reset once the refcount is zero.
0389  * @sob_id: id of this SOB.
0390  * @sob_addr: the sob offset from the base address.
0391  * @q_idx: the H/W queue that uses this SOB.
0392  * @need_reset: reset indication set when switching to the other sob.
0393  */
0394 struct hl_hw_sob {
0395     struct hl_device    *hdev;
0396     struct kref     kref;
0397     u32         sob_id;
0398     u32         sob_addr;
0399     u32         q_idx;
0400     bool            need_reset;
0401 };
0402 
0403 enum hl_collective_mode {
0404     HL_COLLECTIVE_NOT_SUPPORTED = 0x0,
0405     HL_COLLECTIVE_MASTER = 0x1,
0406     HL_COLLECTIVE_SLAVE = 0x2
0407 };
0408 
0409 /**
0410  * struct hw_queue_properties - queue information.
0411  * @type: queue type.
0412  * @cb_alloc_flags: bitmap which indicates if the hw queue supports CB
0413  *                  that allocated by the Kernel driver and therefore,
0414  *                  a CB handle can be provided for jobs on this queue.
0415  *                  Otherwise, a CB address must be provided.
0416  * @collective_mode: collective mode of current queue
0417  * @driver_only: true if only the driver is allowed to send a job to this queue,
0418  *               false otherwise.
0419  * @binned: True if the queue is binned out and should not be used
0420  * @supports_sync_stream: True if queue supports sync stream
0421  */
0422 struct hw_queue_properties {
0423     enum hl_queue_type      type;
0424     enum queue_cb_alloc_flags   cb_alloc_flags;
0425     enum hl_collective_mode     collective_mode;
0426     u8              driver_only;
0427     u8              binned;
0428     u8              supports_sync_stream;
0429 };
0430 
0431 /**
0432  * enum vm_type - virtual memory mapping request information.
0433  * @VM_TYPE_USERPTR: mapping of user memory to device virtual address.
0434  * @VM_TYPE_PHYS_PACK: mapping of DRAM memory to device virtual address.
0435  */
0436 enum vm_type {
0437     VM_TYPE_USERPTR = 0x1,
0438     VM_TYPE_PHYS_PACK = 0x2
0439 };
0440 
0441 /**
0442  * enum mmu_op_flags - mmu operation relevant information.
0443  * @MMU_OP_USERPTR: operation on user memory (host resident).
0444  * @MMU_OP_PHYS_PACK: operation on DRAM (device resident).
0445  * @MMU_OP_CLEAR_MEMCACHE: operation has to clear memcache.
0446  * @MMU_OP_SKIP_LOW_CACHE_INV: operation is allowed to skip parts of cache invalidation.
0447  */
0448 enum mmu_op_flags {
0449     MMU_OP_USERPTR = 0x1,
0450     MMU_OP_PHYS_PACK = 0x2,
0451     MMU_OP_CLEAR_MEMCACHE = 0x4,
0452     MMU_OP_SKIP_LOW_CACHE_INV = 0x8,
0453 };
0454 
0455 
0456 /**
0457  * enum hl_device_hw_state - H/W device state. use this to understand whether
0458  *                           to do reset before hw_init or not
0459  * @HL_DEVICE_HW_STATE_CLEAN: H/W state is clean. i.e. after hard reset
0460  * @HL_DEVICE_HW_STATE_DIRTY: H/W state is dirty. i.e. we started to execute
0461  *                            hw_init
0462  */
0463 enum hl_device_hw_state {
0464     HL_DEVICE_HW_STATE_CLEAN = 0,
0465     HL_DEVICE_HW_STATE_DIRTY
0466 };
0467 
0468 #define HL_MMU_VA_ALIGNMENT_NOT_NEEDED 0
0469 
0470 /**
0471  * struct hl_mmu_properties - ASIC specific MMU address translation properties.
0472  * @start_addr: virtual start address of the memory region.
0473  * @end_addr: virtual end address of the memory region.
0474  * @hop_shifts: array holds HOPs shifts.
0475  * @hop_masks: array holds HOPs masks.
0476  * @last_mask: mask to get the bit indicating this is the last hop.
0477  * @pgt_size: size for page tables.
0478  * @supported_pages_mask: bitmask for supported page size (relevant only for MMUs
0479  *                        supporting multiple page size).
0480  * @page_size: default page size used to allocate memory.
0481  * @num_hops: The amount of hops supported by the translation table.
0482  * @hop_table_size: HOP table size.
0483  * @hop0_tables_total_size: total size for all HOP0 tables.
0484  * @host_resident: Should the MMU page table reside in host memory or in the
0485  *                 device DRAM.
0486  */
0487 struct hl_mmu_properties {
0488     u64 start_addr;
0489     u64 end_addr;
0490     u64 hop_shifts[MMU_HOP_MAX];
0491     u64 hop_masks[MMU_HOP_MAX];
0492     u64 last_mask;
0493     u64 pgt_size;
0494     u64 supported_pages_mask;
0495     u32 page_size;
0496     u32 num_hops;
0497     u32 hop_table_size;
0498     u32 hop0_tables_total_size;
0499     u8  host_resident;
0500 };
0501 
0502 /**
0503  * struct hl_hints_range - hint addresses reserved va range.
0504  * @start_addr: start address of the va range.
0505  * @end_addr: end address of the va range.
0506  */
0507 struct hl_hints_range {
0508     u64 start_addr;
0509     u64 end_addr;
0510 };
0511 
0512 /**
0513  * struct asic_fixed_properties - ASIC specific immutable properties.
0514  * @hw_queues_props: H/W queues properties.
0515  * @cpucp_info: received various information from CPU-CP regarding the H/W, e.g.
0516  *      available sensors.
0517  * @uboot_ver: F/W U-boot version.
0518  * @preboot_ver: F/W Preboot version.
0519  * @dmmu: DRAM MMU address translation properties.
0520  * @pmmu: PCI (host) MMU address translation properties.
0521  * @pmmu_huge: PCI (host) MMU address translation properties for memory
0522  *              allocated with huge pages.
0523  * @hints_dram_reserved_va_range: dram hint addresses reserved range.
0524  * @hints_host_reserved_va_range: host hint addresses reserved range.
0525  * @hints_host_hpage_reserved_va_range: host huge page hint addresses reserved
0526  *                                      range.
0527  * @sram_base_address: SRAM physical start address.
0528  * @sram_end_address: SRAM physical end address.
0529  * @sram_user_base_address - SRAM physical start address for user access.
0530  * @dram_base_address: DRAM physical start address.
0531  * @dram_end_address: DRAM physical end address.
0532  * @dram_user_base_address: DRAM physical start address for user access.
0533  * @dram_size: DRAM total size.
0534  * @dram_pci_bar_size: size of PCI bar towards DRAM.
0535  * @max_power_default: max power of the device after reset.
0536  * @dc_power_default: power consumed by the device in mode idle.
0537  * @dram_size_for_default_page_mapping: DRAM size needed to map to avoid page
0538  *                                      fault.
0539  * @pcie_dbi_base_address: Base address of the PCIE_DBI block.
0540  * @pcie_aux_dbi_reg_addr: Address of the PCIE_AUX DBI register.
0541  * @mmu_pgt_addr: base physical address in DRAM of MMU page tables.
0542  * @mmu_dram_default_page_addr: DRAM default page physical address.
0543  * @tpc_enabled_mask: which TPCs are enabled.
0544  * @tpc_binning_mask: which TPCs are binned. 0 means usable and 1 means binned.
0545  * @dram_enabled_mask: which DRAMs are enabled.
0546  * @dram_binning_mask: which DRAMs are binned. 0 means usable, 1 means binned.
0547  * @cb_va_start_addr: virtual start address of command buffers which are mapped
0548  *                    to the device's MMU.
0549  * @cb_va_end_addr: virtual end address of command buffers which are mapped to
0550  *                  the device's MMU.
0551  * @dram_hints_align_mask: dram va hint addresses alignment mask which is used
0552  *                  for hints validity check.
0553  * @cfg_base_address: config space base address.
0554  * @mmu_cache_mng_addr: address of the MMU cache.
0555  * @mmu_cache_mng_size: size of the MMU cache.
0556  * @device_dma_offset_for_host_access: the offset to add to host DMA addresses
0557  *                                     to enable the device to access them.
0558  * @host_base_address: host physical start address for host DMA from device
0559  * @host_end_address: host physical end address for host DMA from device
0560  * @max_freq_value: current max clk frequency.
0561  * @clk_pll_index: clock PLL index that specify which PLL determines the clock
0562  *                 we display to the user
0563  * @mmu_pgt_size: MMU page tables total size.
0564  * @mmu_pte_size: PTE size in MMU page tables.
0565  * @mmu_hop_table_size: MMU hop table size.
0566  * @mmu_hop0_tables_total_size: total size of MMU hop0 tables.
0567  * @dram_page_size: page size for MMU DRAM allocation.
0568  * @cfg_size: configuration space size on SRAM.
0569  * @sram_size: total size of SRAM.
0570  * @max_asid: maximum number of open contexts (ASIDs).
0571  * @num_of_events: number of possible internal H/W IRQs.
0572  * @psoc_pci_pll_nr: PCI PLL NR value.
0573  * @psoc_pci_pll_nf: PCI PLL NF value.
0574  * @psoc_pci_pll_od: PCI PLL OD value.
0575  * @psoc_pci_pll_div_factor: PCI PLL DIV FACTOR 1 value.
0576  * @psoc_timestamp_frequency: frequency of the psoc timestamp clock.
0577  * @high_pll: high PLL frequency used by the device.
0578  * @cb_pool_cb_cnt: number of CBs in the CB pool.
0579  * @cb_pool_cb_size: size of each CB in the CB pool.
0580  * @decoder_enabled_mask: which decoders are enabled.
0581  * @decoder_binning_mask: which decoders are binned, 0 means usable and 1
0582  *                        means binned (at most one binned decoder per dcore).
0583  * @edma_enabled_mask: which EDMAs are enabled.
0584  * @edma_binning_mask: which EDMAs are binned, 0 means usable and 1 means
0585  *                     binned (at most one binned DMA).
0586  * @max_pending_cs: maximum of concurrent pending command submissions
0587  * @max_queues: maximum amount of queues in the system
0588  * @fw_preboot_cpu_boot_dev_sts0: bitmap representation of preboot cpu
0589  *                                capabilities reported by FW, bit description
0590  *                                can be found in CPU_BOOT_DEV_STS0
0591  * @fw_preboot_cpu_boot_dev_sts1: bitmap representation of preboot cpu
0592  *                                capabilities reported by FW, bit description
0593  *                                can be found in CPU_BOOT_DEV_STS1
0594  * @fw_bootfit_cpu_boot_dev_sts0: bitmap representation of boot cpu security
0595  *                                status reported by FW, bit description can be
0596  *                                found in CPU_BOOT_DEV_STS0
0597  * @fw_bootfit_cpu_boot_dev_sts1: bitmap representation of boot cpu security
0598  *                                status reported by FW, bit description can be
0599  *                                found in CPU_BOOT_DEV_STS1
0600  * @fw_app_cpu_boot_dev_sts0: bitmap representation of application security
0601  *                            status reported by FW, bit description can be
0602  *                            found in CPU_BOOT_DEV_STS0
0603  * @fw_app_cpu_boot_dev_sts1: bitmap representation of application security
0604  *                            status reported by FW, bit description can be
0605  *                            found in CPU_BOOT_DEV_STS1
0606  * @max_dec: maximum number of decoders
0607  * @hmmu_hif_enabled_mask: mask of HMMUs/HIFs that are not isolated (enabled)
0608  *                         1- enabled, 0- isolated.
0609  * @faulty_dram_cluster_map: mask of faulty DRAM cluster.
0610  *                         1- faulty cluster, 0- good cluster.
0611  * @xbar_edge_enabled_mask: mask of XBAR_EDGEs that are not isolated (enabled)
0612  *                          1- enabled, 0- isolated.
0613  * @device_mem_alloc_default_page_size: may be different than dram_page_size only for ASICs for
0614  *                                      which the property supports_user_set_page_size is true
0615  *                                      (i.e. the DRAM supports multiple page sizes), otherwise
0616  *                                      it will shall  be equal to dram_page_size.
0617  * @collective_first_sob: first sync object available for collective use
0618  * @collective_first_mon: first monitor available for collective use
0619  * @sync_stream_first_sob: first sync object available for sync stream use
0620  * @sync_stream_first_mon: first monitor available for sync stream use
0621  * @first_available_user_sob: first sob available for the user
0622  * @first_available_user_mon: first monitor available for the user
0623  * @first_available_user_interrupt: first available interrupt reserved for the user
0624  * @first_available_cq: first available CQ for the user.
0625  * @user_interrupt_count: number of user interrupts.
0626  * @user_dec_intr_count: number of decoder interrupts exposed to user.
0627  * @cache_line_size: device cache line size.
0628  * @server_type: Server type that the ASIC is currently installed in.
0629  *               The value is according to enum hl_server_type in uapi file.
0630  * @completion_queues_count: number of completion queues.
0631  * @completion_mode: 0 - job based completion, 1 - cs based completion
0632  * @mme_master_slave_mode: 0 - Each MME works independently, 1 - MME works
0633  *                         in Master/Slave mode
0634  * @fw_security_enabled: true if security measures are enabled in firmware,
0635  *                       false otherwise
0636  * @fw_cpu_boot_dev_sts0_valid: status bits are valid and can be fetched from
0637  *                              BOOT_DEV_STS0
0638  * @fw_cpu_boot_dev_sts1_valid: status bits are valid and can be fetched from
0639  *                              BOOT_DEV_STS1
0640  * @dram_supports_virtual_memory: is there an MMU towards the DRAM
0641  * @hard_reset_done_by_fw: true if firmware is handling hard reset flow
0642  * @num_functional_hbms: number of functional HBMs in each DCORE.
0643  * @hints_range_reservation: device support hint addresses range reservation.
0644  * @iatu_done_by_fw: true if iATU configuration is being done by FW.
0645  * @dynamic_fw_load: is dynamic FW load is supported.
0646  * @gic_interrupts_enable: true if FW is not blocking GIC controller,
0647  *                         false otherwise.
0648  * @use_get_power_for_reset_history: To support backward compatibility for Goya
0649  *                                   and Gaudi
0650  * @supports_compute_reset: is a reset which is not a hard-reset supported by this asic.
0651  * @allow_inference_soft_reset: true if the ASIC supports soft reset that is
0652  *                              initiated by user or TDR. This is only true
0653  *                              in inference ASICs, as there is no real-world
0654  *                              use-case of doing soft-reset in training (due
0655  *                              to the fact that training runs on multiple
0656  *                              devices)
0657  * @configurable_stop_on_err: is stop-on-error option configurable via debugfs.
0658  * @set_max_power_on_device_init: true if need to set max power in F/W on device init.
0659  * @supports_user_set_page_size: true if user can set the allocation page size.
0660  * @dma_mask: the dma mask to be set for this device
0661  */
0662 struct asic_fixed_properties {
0663     struct hw_queue_properties  *hw_queues_props;
0664     struct cpucp_info       cpucp_info;
0665     char                uboot_ver[VERSION_MAX_LEN];
0666     char                preboot_ver[VERSION_MAX_LEN];
0667     struct hl_mmu_properties    dmmu;
0668     struct hl_mmu_properties    pmmu;
0669     struct hl_mmu_properties    pmmu_huge;
0670     struct hl_hints_range       hints_dram_reserved_va_range;
0671     struct hl_hints_range       hints_host_reserved_va_range;
0672     struct hl_hints_range       hints_host_hpage_reserved_va_range;
0673     u64             sram_base_address;
0674     u64             sram_end_address;
0675     u64             sram_user_base_address;
0676     u64             dram_base_address;
0677     u64             dram_end_address;
0678     u64             dram_user_base_address;
0679     u64             dram_size;
0680     u64             dram_pci_bar_size;
0681     u64             max_power_default;
0682     u64             dc_power_default;
0683     u64             dram_size_for_default_page_mapping;
0684     u64             pcie_dbi_base_address;
0685     u64             pcie_aux_dbi_reg_addr;
0686     u64             mmu_pgt_addr;
0687     u64             mmu_dram_default_page_addr;
0688     u64             tpc_enabled_mask;
0689     u64             tpc_binning_mask;
0690     u64             dram_enabled_mask;
0691     u64             dram_binning_mask;
0692     u64             cb_va_start_addr;
0693     u64             cb_va_end_addr;
0694     u64             dram_hints_align_mask;
0695     u64             cfg_base_address;
0696     u64             mmu_cache_mng_addr;
0697     u64             mmu_cache_mng_size;
0698     u64             device_dma_offset_for_host_access;
0699     u64             host_base_address;
0700     u64             host_end_address;
0701     u64             max_freq_value;
0702     u32             clk_pll_index;
0703     u32             mmu_pgt_size;
0704     u32             mmu_pte_size;
0705     u32             mmu_hop_table_size;
0706     u32             mmu_hop0_tables_total_size;
0707     u32             dram_page_size;
0708     u32             cfg_size;
0709     u32             sram_size;
0710     u32             max_asid;
0711     u32             num_of_events;
0712     u32             psoc_pci_pll_nr;
0713     u32             psoc_pci_pll_nf;
0714     u32             psoc_pci_pll_od;
0715     u32             psoc_pci_pll_div_factor;
0716     u32             psoc_timestamp_frequency;
0717     u32             high_pll;
0718     u32             cb_pool_cb_cnt;
0719     u32             cb_pool_cb_size;
0720     u32             decoder_enabled_mask;
0721     u32             decoder_binning_mask;
0722     u32             edma_enabled_mask;
0723     u32             edma_binning_mask;
0724     u32             max_pending_cs;
0725     u32             max_queues;
0726     u32             fw_preboot_cpu_boot_dev_sts0;
0727     u32             fw_preboot_cpu_boot_dev_sts1;
0728     u32             fw_bootfit_cpu_boot_dev_sts0;
0729     u32             fw_bootfit_cpu_boot_dev_sts1;
0730     u32             fw_app_cpu_boot_dev_sts0;
0731     u32             fw_app_cpu_boot_dev_sts1;
0732     u32             max_dec;
0733     u32             hmmu_hif_enabled_mask;
0734     u32             faulty_dram_cluster_map;
0735     u32             xbar_edge_enabled_mask;
0736     u32             device_mem_alloc_default_page_size;
0737     u16             collective_first_sob;
0738     u16             collective_first_mon;
0739     u16             sync_stream_first_sob;
0740     u16             sync_stream_first_mon;
0741     u16             first_available_user_sob[HL_MAX_DCORES];
0742     u16             first_available_user_mon[HL_MAX_DCORES];
0743     u16             first_available_user_interrupt;
0744     u16             first_available_cq[HL_MAX_DCORES];
0745     u16             user_interrupt_count;
0746     u16             user_dec_intr_count;
0747     u16             cache_line_size;
0748     u16             server_type;
0749     u8              completion_queues_count;
0750     u8              completion_mode;
0751     u8              mme_master_slave_mode;
0752     u8              fw_security_enabled;
0753     u8              fw_cpu_boot_dev_sts0_valid;
0754     u8              fw_cpu_boot_dev_sts1_valid;
0755     u8              dram_supports_virtual_memory;
0756     u8              hard_reset_done_by_fw;
0757     u8              num_functional_hbms;
0758     u8              hints_range_reservation;
0759     u8              iatu_done_by_fw;
0760     u8              dynamic_fw_load;
0761     u8              gic_interrupts_enable;
0762     u8              use_get_power_for_reset_history;
0763     u8              supports_compute_reset;
0764     u8              allow_inference_soft_reset;
0765     u8              configurable_stop_on_err;
0766     u8              set_max_power_on_device_init;
0767     u8              supports_user_set_page_size;
0768     u8              dma_mask;
0769 };
0770 
0771 /**
0772  * struct hl_fence - software synchronization primitive
0773  * @completion: fence is implemented using completion
0774  * @refcount: refcount for this fence
0775  * @cs_sequence: sequence of the corresponding command submission
0776  * @stream_master_qid_map: streams masters QID bitmap to represent all streams
0777  *                         masters QIDs that multi cs is waiting on
0778  * @error: mark this fence with error
0779  * @timestamp: timestamp upon completion
0780  * @mcs_handling_done: indicates that corresponding command submission has
0781  *                     finished msc handling, this does not mean it was part
0782  *                     of the mcs
0783  */
0784 struct hl_fence {
0785     struct completion   completion;
0786     struct kref     refcount;
0787     u64         cs_sequence;
0788     u32         stream_master_qid_map;
0789     int         error;
0790     ktime_t         timestamp;
0791     u8          mcs_handling_done;
0792 };
0793 
0794 /**
0795  * struct hl_cs_compl - command submission completion object.
0796  * @base_fence: hl fence object.
0797  * @lock: spinlock to protect fence.
0798  * @hdev: habanalabs device structure.
0799  * @hw_sob: the H/W SOB used in this signal/wait CS.
0800  * @encaps_sig_hdl: encaps signals hanlder.
0801  * @cs_seq: command submission sequence number.
0802  * @type: type of the CS - signal/wait.
0803  * @sob_val: the SOB value that is used in this signal/wait CS.
0804  * @sob_group: the SOB group that is used in this collective wait CS.
0805  * @encaps_signals: indication whether it's a completion object of cs with
0806  * encaps signals or not.
0807  */
0808 struct hl_cs_compl {
0809     struct hl_fence     base_fence;
0810     spinlock_t      lock;
0811     struct hl_device    *hdev;
0812     struct hl_hw_sob    *hw_sob;
0813     struct hl_cs_encaps_sig_handle *encaps_sig_hdl;
0814     u64         cs_seq;
0815     enum hl_cs_type     type;
0816     u16         sob_val;
0817     u16         sob_group;
0818     bool            encaps_signals;
0819 };
0820 
0821 /*
0822  * Command Buffers
0823  */
0824 
0825 /**
0826  * struct hl_ts_buff - describes a timestamp buffer.
0827  * @kernel_buff_address: Holds the internal buffer's kernel virtual address.
0828  * @user_buff_address: Holds the user buffer's kernel virtual address.
0829  * @kernel_buff_size: Holds the internal kernel buffer size.
0830  */
0831 struct hl_ts_buff {
0832     void            *kernel_buff_address;
0833     void            *user_buff_address;
0834     u32         kernel_buff_size;
0835 };
0836 
0837 struct hl_mmap_mem_buf;
0838 
0839 /**
0840  * struct hl_mem_mgr - describes unified memory manager for mappable memory chunks.
0841  * @dev: back pointer to the owning device
0842  * @lock: protects handles
0843  * @handles: an idr holding all active handles to the memory buffers in the system.
0844  */
0845 struct hl_mem_mgr {
0846     struct device *dev;
0847     spinlock_t lock;
0848     struct idr handles;
0849 };
0850 
0851 /**
0852  * struct hl_mmap_mem_buf_behavior - describes unified memory manager buffer behavior
0853  * @topic: string identifier used for logging
0854  * @mem_id: memory type identifier, embedded in the handle and used to identify
0855  *          the memory type by handle.
0856  * @alloc: callback executed on buffer allocation, shall allocate the memory,
0857  *         set it under buffer private, and set mappable size.
0858  * @mmap: callback executed on mmap, must map the buffer to vma
0859  * @release: callback executed on release, must free the resources used by the buffer
0860  */
0861 struct hl_mmap_mem_buf_behavior {
0862     const char *topic;
0863     u64 mem_id;
0864 
0865     int (*alloc)(struct hl_mmap_mem_buf *buf, gfp_t gfp, void *args);
0866     int (*mmap)(struct hl_mmap_mem_buf *buf, struct vm_area_struct *vma, void *args);
0867     void (*release)(struct hl_mmap_mem_buf *buf);
0868 };
0869 
0870 /**
0871  * struct hl_mmap_mem_buf - describes a single unified memory buffer
0872  * @behavior: buffer behavior
0873  * @mmg: back pointer to the unified memory manager
0874  * @refcount: reference counter for buffer users
0875  * @private: pointer to buffer behavior private data
0876  * @mmap: atomic boolean indicating whether or not the buffer is mapped right now
0877  * @real_mapped_size: the actual size of buffer mapped, after part of it may be released,
0878  *                   may change at runtime.
0879  * @mappable_size: the original mappable size of the buffer, does not change after
0880  *                 the allocation.
0881  * @handle: the buffer id in mmg handles store
0882  */
0883 struct hl_mmap_mem_buf {
0884     struct hl_mmap_mem_buf_behavior *behavior;
0885     struct hl_mem_mgr *mmg;
0886     struct kref refcount;
0887     void *private;
0888     atomic_t mmap;
0889     u64 real_mapped_size;
0890     u64 mappable_size;
0891     u64 handle;
0892 };
0893 
0894 /**
0895  * struct hl_cb - describes a Command Buffer.
0896  * @hdev: pointer to device this CB belongs to.
0897  * @ctx: pointer to the CB owner's context.
0898  * @buf: back pointer to the parent mappable memory buffer
0899  * @debugfs_list: node in debugfs list of command buffers.
0900  * @pool_list: node in pool list of command buffers.
0901  * @va_block_list: list of virtual addresses blocks of the CB if it is mapped to
0902  *                 the device's MMU.
0903  * @kernel_address: Holds the CB's kernel virtual address.
0904  * @bus_address: Holds the CB's DMA address.
0905  * @size: holds the CB's size.
0906  * @cs_cnt: holds number of CS that this CB participates in.
0907  * @is_pool: true if CB was acquired from the pool, false otherwise.
0908  * @is_internal: internaly allocated
0909  * @is_mmu_mapped: true if the CB is mapped to the device's MMU.
0910  */
0911 struct hl_cb {
0912     struct hl_device    *hdev;
0913     struct hl_ctx       *ctx;
0914     struct hl_mmap_mem_buf  *buf;
0915     struct list_head    debugfs_list;
0916     struct list_head    pool_list;
0917     struct list_head    va_block_list;
0918     void            *kernel_address;
0919     dma_addr_t      bus_address;
0920     u32         size;
0921     atomic_t        cs_cnt;
0922     u8          is_pool;
0923     u8          is_internal;
0924     u8          is_mmu_mapped;
0925 };
0926 
0927 
0928 /*
0929  * QUEUES
0930  */
0931 
0932 struct hl_cs_job;
0933 
0934 /* Queue length of external and HW queues */
0935 #define HL_QUEUE_LENGTH         4096
0936 #define HL_QUEUE_SIZE_IN_BYTES      (HL_QUEUE_LENGTH * HL_BD_SIZE)
0937 
0938 #if (HL_MAX_JOBS_PER_CS > HL_QUEUE_LENGTH)
0939 #error "HL_QUEUE_LENGTH must be greater than HL_MAX_JOBS_PER_CS"
0940 #endif
0941 
0942 /* HL_CQ_LENGTH is in units of struct hl_cq_entry */
0943 #define HL_CQ_LENGTH            HL_QUEUE_LENGTH
0944 #define HL_CQ_SIZE_IN_BYTES     (HL_CQ_LENGTH * HL_CQ_ENTRY_SIZE)
0945 
0946 /* Must be power of 2 */
0947 #define HL_EQ_LENGTH            64
0948 #define HL_EQ_SIZE_IN_BYTES     (HL_EQ_LENGTH * HL_EQ_ENTRY_SIZE)
0949 
0950 /* Host <-> CPU-CP shared memory size */
0951 #define HL_CPU_ACCESSIBLE_MEM_SIZE  SZ_2M
0952 
0953 /**
0954  * struct hl_sync_stream_properties -
0955  *     describes a H/W queue sync stream properties
0956  * @hw_sob: array of the used H/W SOBs by this H/W queue.
0957  * @next_sob_val: the next value to use for the currently used SOB.
0958  * @base_sob_id: the base SOB id of the SOBs used by this queue.
0959  * @base_mon_id: the base MON id of the MONs used by this queue.
0960  * @collective_mstr_mon_id: the MON ids of the MONs used by this master queue
0961  *                          in order to sync with all slave queues.
0962  * @collective_slave_mon_id: the MON id used by this slave queue in order to
0963  *                           sync with its master queue.
0964  * @collective_sob_id: current SOB id used by this collective slave queue
0965  *                     to signal its collective master queue upon completion.
0966  * @curr_sob_offset: the id offset to the currently used SOB from the
0967  *                   HL_RSVD_SOBS that are being used by this queue.
0968  */
0969 struct hl_sync_stream_properties {
0970     struct hl_hw_sob hw_sob[HL_RSVD_SOBS];
0971     u16     next_sob_val;
0972     u16     base_sob_id;
0973     u16     base_mon_id;
0974     u16     collective_mstr_mon_id[HL_COLLECTIVE_RSVD_MSTR_MONS];
0975     u16     collective_slave_mon_id;
0976     u16     collective_sob_id;
0977     u8      curr_sob_offset;
0978 };
0979 
0980 /**
0981  * struct hl_encaps_signals_mgr - describes sync stream encapsulated signals
0982  * handlers manager
0983  * @lock: protects handles.
0984  * @handles: an idr to hold all encapsulated signals handles.
0985  */
0986 struct hl_encaps_signals_mgr {
0987     spinlock_t      lock;
0988     struct idr      handles;
0989 };
0990 
0991 /**
0992  * struct hl_hw_queue - describes a H/W transport queue.
0993  * @shadow_queue: pointer to a shadow queue that holds pointers to jobs.
0994  * @sync_stream_prop: sync stream queue properties
0995  * @queue_type: type of queue.
0996  * @collective_mode: collective mode of current queue
0997  * @kernel_address: holds the queue's kernel virtual address.
0998  * @bus_address: holds the queue's DMA address.
0999  * @pi: holds the queue's pi value.
1000  * @ci: holds the queue's ci value, AS CALCULATED BY THE DRIVER (not real ci).
1001  * @hw_queue_id: the id of the H/W queue.
1002  * @cq_id: the id for the corresponding CQ for this H/W queue.
1003  * @msi_vec: the IRQ number of the H/W queue.
1004  * @int_queue_len: length of internal queue (number of entries).
1005  * @valid: is the queue valid (we have array of 32 queues, not all of them
1006  *         exist).
1007  * @supports_sync_stream: True if queue supports sync stream
1008  */
1009 struct hl_hw_queue {
1010     struct hl_cs_job            **shadow_queue;
1011     struct hl_sync_stream_properties    sync_stream_prop;
1012     enum hl_queue_type          queue_type;
1013     enum hl_collective_mode         collective_mode;
1014     void                    *kernel_address;
1015     dma_addr_t              bus_address;
1016     u32                 pi;
1017     atomic_t                ci;
1018     u32                 hw_queue_id;
1019     u32                 cq_id;
1020     u32                 msi_vec;
1021     u16                 int_queue_len;
1022     u8                  valid;
1023     u8                  supports_sync_stream;
1024 };
1025 
1026 /**
1027  * struct hl_cq - describes a completion queue
1028  * @hdev: pointer to the device structure
1029  * @kernel_address: holds the queue's kernel virtual address
1030  * @bus_address: holds the queue's DMA address
1031  * @cq_idx: completion queue index in array
1032  * @hw_queue_id: the id of the matching H/W queue
1033  * @ci: ci inside the queue
1034  * @pi: pi inside the queue
1035  * @free_slots_cnt: counter of free slots in queue
1036  */
1037 struct hl_cq {
1038     struct hl_device    *hdev;
1039     void            *kernel_address;
1040     dma_addr_t      bus_address;
1041     u32         cq_idx;
1042     u32         hw_queue_id;
1043     u32         ci;
1044     u32         pi;
1045     atomic_t        free_slots_cnt;
1046 };
1047 
1048 /**
1049  * struct hl_user_interrupt - holds user interrupt information
1050  * @hdev: pointer to the device structure
1051  * @wait_list_head: head to the list of user threads pending on this interrupt
1052  * @wait_list_lock: protects wait_list_head
1053  * @interrupt_id: msix interrupt id
1054  * @is_decoder: whether this entry represents a decoder interrupt
1055  */
1056 struct hl_user_interrupt {
1057     struct hl_device    *hdev;
1058     struct list_head    wait_list_head;
1059     spinlock_t      wait_list_lock;
1060     u32         interrupt_id;
1061     bool            is_decoder;
1062 };
1063 
1064 /**
1065  * struct timestamp_reg_free_node - holds the timestamp registration free objects node
1066  * @free_objects_node: node in the list free_obj_jobs
1067  * @cq_cb: pointer to cq command buffer to be freed
1068  * @buf: pointer to timestamp buffer to be freed
1069  */
1070 struct timestamp_reg_free_node {
1071     struct list_head    free_objects_node;
1072     struct hl_cb        *cq_cb;
1073     struct hl_mmap_mem_buf  *buf;
1074 };
1075 
1076 /* struct timestamp_reg_work_obj - holds the timestamp registration free objects job
1077  * the job will be to pass over the free_obj_jobs list and put refcount to objects
1078  * in each node of the list
1079  * @free_obj: workqueue object to free timestamp registration node objects
1080  * @hdev: pointer to the device structure
1081  * @free_obj_head: list of free jobs nodes (node type timestamp_reg_free_node)
1082  */
1083 struct timestamp_reg_work_obj {
1084     struct work_struct  free_obj;
1085     struct hl_device    *hdev;
1086     struct list_head    *free_obj_head;
1087 };
1088 
1089 /* struct timestamp_reg_info - holds the timestamp registration related data.
1090  * @buf: pointer to the timestamp buffer which include both user/kernel buffers.
1091  *       relevant only when doing timestamps records registration.
1092  * @cq_cb: pointer to CQ counter CB.
1093  * @timestamp_kernel_addr: timestamp handle address, where to set timestamp
1094  *                         relevant only when doing timestamps records
1095  *                         registration.
1096  * @in_use: indicates if the node already in use. relevant only when doing
1097  *          timestamps records registration, since in this case the driver
1098  *          will have it's own buffer which serve as a records pool instead of
1099  *          allocating records dynamically.
1100  */
1101 struct timestamp_reg_info {
1102     struct hl_mmap_mem_buf  *buf;
1103     struct hl_cb        *cq_cb;
1104     u64         *timestamp_kernel_addr;
1105     u8          in_use;
1106 };
1107 
1108 /**
1109  * struct hl_user_pending_interrupt - holds a context to a user thread
1110  *                                    pending on an interrupt
1111  * @ts_reg_info: holds the timestamps registration nodes info
1112  * @wait_list_node: node in the list of user threads pending on an interrupt
1113  * @fence: hl fence object for interrupt completion
1114  * @cq_target_value: CQ target value
1115  * @cq_kernel_addr: CQ kernel address, to be used in the cq interrupt
1116  *                  handler for taget value comparison
1117  */
1118 struct hl_user_pending_interrupt {
1119     struct timestamp_reg_info   ts_reg_info;
1120     struct list_head        wait_list_node;
1121     struct hl_fence         fence;
1122     u64             cq_target_value;
1123     u64             *cq_kernel_addr;
1124 };
1125 
1126 /**
1127  * struct hl_eq - describes the event queue (single one per device)
1128  * @hdev: pointer to the device structure
1129  * @kernel_address: holds the queue's kernel virtual address
1130  * @bus_address: holds the queue's DMA address
1131  * @ci: ci inside the queue
1132  * @prev_eqe_index: the index of the previous event queue entry. The index of
1133  *                  the current entry's index must be +1 of the previous one.
1134  * @check_eqe_index: do we need to check the index of the current entry vs. the
1135  *                   previous one. This is for backward compatibility with older
1136  *                   firmwares
1137  */
1138 struct hl_eq {
1139     struct hl_device    *hdev;
1140     void            *kernel_address;
1141     dma_addr_t      bus_address;
1142     u32         ci;
1143     u32         prev_eqe_index;
1144     bool            check_eqe_index;
1145 };
1146 
1147 /**
1148  * struct hl_dec - describes a decoder sw instance.
1149  * @hdev: pointer to the device structure.
1150  * @completion_abnrm_work: workqueue object to run when decoder generates an error interrupt
1151  * @core_id: ID of the decoder.
1152  * @base_addr: base address of the decoder.
1153  */
1154 struct hl_dec {
1155     struct hl_device        *hdev;
1156     struct work_struct      completion_abnrm_work;
1157     u32             core_id;
1158     u32             base_addr;
1159 };
1160 
1161 /**
1162  * enum hl_asic_type - supported ASIC types.
1163  * @ASIC_INVALID: Invalid ASIC type.
1164  * @ASIC_GOYA: Goya device (HL-1000).
1165  * @ASIC_GAUDI: Gaudi device (HL-2000).
1166  * @ASIC_GAUDI_SEC: Gaudi secured device (HL-2000).
1167  * @ASIC_GAUDI2: Gaudi2 device.
1168  * @ASIC_GAUDI2_SEC: Gaudi2 secured device.
1169  */
1170 enum hl_asic_type {
1171     ASIC_INVALID,
1172     ASIC_GOYA,
1173     ASIC_GAUDI,
1174     ASIC_GAUDI_SEC,
1175     ASIC_GAUDI2,
1176     ASIC_GAUDI2_SEC,
1177 };
1178 
1179 struct hl_cs_parser;
1180 
1181 /**
1182  * enum hl_pm_mng_profile - power management profile.
1183  * @PM_AUTO: internal clock is set by the Linux driver.
1184  * @PM_MANUAL: internal clock is set by the user.
1185  * @PM_LAST: last power management type.
1186  */
1187 enum hl_pm_mng_profile {
1188     PM_AUTO = 1,
1189     PM_MANUAL,
1190     PM_LAST
1191 };
1192 
1193 /**
1194  * enum hl_pll_frequency - PLL frequency.
1195  * @PLL_HIGH: high frequency.
1196  * @PLL_LOW: low frequency.
1197  * @PLL_LAST: last frequency values that were configured by the user.
1198  */
1199 enum hl_pll_frequency {
1200     PLL_HIGH = 1,
1201     PLL_LOW,
1202     PLL_LAST
1203 };
1204 
1205 #define PLL_REF_CLK 50
1206 
1207 enum div_select_defs {
1208     DIV_SEL_REF_CLK = 0,
1209     DIV_SEL_PLL_CLK = 1,
1210     DIV_SEL_DIVIDED_REF = 2,
1211     DIV_SEL_DIVIDED_PLL = 3,
1212 };
1213 
1214 enum debugfs_access_type {
1215     DEBUGFS_READ8,
1216     DEBUGFS_WRITE8,
1217     DEBUGFS_READ32,
1218     DEBUGFS_WRITE32,
1219     DEBUGFS_READ64,
1220     DEBUGFS_WRITE64,
1221 };
1222 
1223 enum pci_region {
1224     PCI_REGION_CFG,
1225     PCI_REGION_SRAM,
1226     PCI_REGION_DRAM,
1227     PCI_REGION_SP_SRAM,
1228     PCI_REGION_NUMBER,
1229 };
1230 
1231 /**
1232  * struct pci_mem_region - describe memory region in a PCI bar
1233  * @region_base: region base address
1234  * @region_size: region size
1235  * @bar_size: size of the BAR
1236  * @offset_in_bar: region offset into the bar
1237  * @bar_id: bar ID of the region
1238  * @used: if used 1, otherwise 0
1239  */
1240 struct pci_mem_region {
1241     u64 region_base;
1242     u64 region_size;
1243     u64 bar_size;
1244     u64 offset_in_bar;
1245     u8 bar_id;
1246     u8 used;
1247 };
1248 
1249 /**
1250  * struct static_fw_load_mgr - static FW load manager
1251  * @preboot_version_max_off: max offset to preboot version
1252  * @boot_fit_version_max_off: max offset to boot fit version
1253  * @kmd_msg_to_cpu_reg: register address for KDM->CPU messages
1254  * @cpu_cmd_status_to_host_reg: register address for CPU command status response
1255  * @cpu_boot_status_reg: boot status register
1256  * @cpu_boot_dev_status0_reg: boot device status register 0
1257  * @cpu_boot_dev_status1_reg: boot device status register 1
1258  * @boot_err0_reg: boot error register 0
1259  * @boot_err1_reg: boot error register 1
1260  * @preboot_version_offset_reg: SRAM offset to preboot version register
1261  * @boot_fit_version_offset_reg: SRAM offset to boot fit version register
1262  * @sram_offset_mask: mask for getting offset into the SRAM
1263  * @cpu_reset_wait_msec: used when setting WFE via kmd_msg_to_cpu_reg
1264  */
1265 struct static_fw_load_mgr {
1266     u64 preboot_version_max_off;
1267     u64 boot_fit_version_max_off;
1268     u32 kmd_msg_to_cpu_reg;
1269     u32 cpu_cmd_status_to_host_reg;
1270     u32 cpu_boot_status_reg;
1271     u32 cpu_boot_dev_status0_reg;
1272     u32 cpu_boot_dev_status1_reg;
1273     u32 boot_err0_reg;
1274     u32 boot_err1_reg;
1275     u32 preboot_version_offset_reg;
1276     u32 boot_fit_version_offset_reg;
1277     u32 sram_offset_mask;
1278     u32 cpu_reset_wait_msec;
1279 };
1280 
1281 /**
1282  * struct fw_response - FW response to LKD command
1283  * @ram_offset: descriptor offset into the RAM
1284  * @ram_type: RAM type containing the descriptor (SRAM/DRAM)
1285  * @status: command status
1286  */
1287 struct fw_response {
1288     u32 ram_offset;
1289     u8 ram_type;
1290     u8 status;
1291 };
1292 
1293 /**
1294  * struct dynamic_fw_load_mgr - dynamic FW load manager
1295  * @response: FW to LKD response
1296  * @comm_desc: the communication descriptor with FW
1297  * @image_region: region to copy the FW image to
1298  * @fw_image_size: size of FW image to load
1299  * @wait_for_bl_timeout: timeout for waiting for boot loader to respond
1300  * @fw_desc_valid: true if FW descriptor has been validated and hence the data can be used
1301  */
1302 struct dynamic_fw_load_mgr {
1303     struct fw_response response;
1304     struct lkd_fw_comms_desc comm_desc;
1305     struct pci_mem_region *image_region;
1306     size_t fw_image_size;
1307     u32 wait_for_bl_timeout;
1308     bool fw_desc_valid;
1309 };
1310 
1311 /**
1312  * struct pre_fw_load_props - needed properties for pre-FW load
1313  * @cpu_boot_status_reg: cpu_boot_status register address
1314  * @sts_boot_dev_sts0_reg: sts_boot_dev_sts0 register address
1315  * @sts_boot_dev_sts1_reg: sts_boot_dev_sts1 register address
1316  * @boot_err0_reg: boot_err0 register address
1317  * @boot_err1_reg: boot_err1 register address
1318  * @wait_for_preboot_timeout: timeout to poll for preboot ready
1319  */
1320 struct pre_fw_load_props {
1321     u32 cpu_boot_status_reg;
1322     u32 sts_boot_dev_sts0_reg;
1323     u32 sts_boot_dev_sts1_reg;
1324     u32 boot_err0_reg;
1325     u32 boot_err1_reg;
1326     u32 wait_for_preboot_timeout;
1327 };
1328 
1329 /**
1330  * struct fw_image_props - properties of FW image
1331  * @image_name: name of the image
1332  * @src_off: offset in src FW to copy from
1333  * @copy_size: amount of bytes to copy (0 to copy the whole binary)
1334  */
1335 struct fw_image_props {
1336     char *image_name;
1337     u32 src_off;
1338     u32 copy_size;
1339 };
1340 
1341 /**
1342  * struct fw_load_mgr - manager FW loading process
1343  * @dynamic_loader: specific structure for dynamic load
1344  * @static_loader: specific structure for static load
1345  * @pre_fw_load_props: parameter for pre FW load
1346  * @boot_fit_img: boot fit image properties
1347  * @linux_img: linux image properties
1348  * @cpu_timeout: CPU response timeout in usec
1349  * @boot_fit_timeout: Boot fit load timeout in usec
1350  * @skip_bmc: should BMC be skipped
1351  * @sram_bar_id: SRAM bar ID
1352  * @dram_bar_id: DRAM bar ID
1353  * @fw_comp_loaded: bitmask of loaded FW components. set bit meaning loaded
1354  *                  component. values are set according to enum hl_fw_types.
1355  */
1356 struct fw_load_mgr {
1357     union {
1358         struct dynamic_fw_load_mgr dynamic_loader;
1359         struct static_fw_load_mgr static_loader;
1360     };
1361     struct pre_fw_load_props pre_fw_load;
1362     struct fw_image_props boot_fit_img;
1363     struct fw_image_props linux_img;
1364     u32 cpu_timeout;
1365     u32 boot_fit_timeout;
1366     u8 skip_bmc;
1367     u8 sram_bar_id;
1368     u8 dram_bar_id;
1369     u8 fw_comp_loaded;
1370 };
1371 
1372 struct hl_cs;
1373 
1374 /**
1375  * struct hl_asic_funcs - ASIC specific functions that are can be called from
1376  *                        common code.
1377  * @early_init: sets up early driver state (pre sw_init), doesn't configure H/W.
1378  * @early_fini: tears down what was done in early_init.
1379  * @late_init: sets up late driver/hw state (post hw_init) - Optional.
1380  * @late_fini: tears down what was done in late_init (pre hw_fini) - Optional.
1381  * @sw_init: sets up driver state, does not configure H/W.
1382  * @sw_fini: tears down driver state, does not configure H/W.
1383  * @hw_init: sets up the H/W state.
1384  * @hw_fini: tears down the H/W state.
1385  * @halt_engines: halt engines, needed for reset sequence. This also disables
1386  *                interrupts from the device. Should be called before
1387  *                hw_fini and before CS rollback.
1388  * @suspend: handles IP specific H/W or SW changes for suspend.
1389  * @resume: handles IP specific H/W or SW changes for resume.
1390  * @mmap: maps a memory.
1391  * @ring_doorbell: increment PI on a given QMAN.
1392  * @pqe_write: Write the PQ entry to the PQ. This is ASIC-specific
1393  *             function because the PQs are located in different memory areas
1394  *             per ASIC (SRAM, DRAM, Host memory) and therefore, the method of
1395  *             writing the PQE must match the destination memory area
1396  *             properties.
1397  * @asic_dma_alloc_coherent: Allocate coherent DMA memory by calling
1398  *                           dma_alloc_coherent(). This is ASIC function because
1399  *                           its implementation is not trivial when the driver
1400  *                           is loaded in simulation mode (not upstreamed).
1401  * @asic_dma_free_coherent:  Free coherent DMA memory by calling
1402  *                           dma_free_coherent(). This is ASIC function because
1403  *                           its implementation is not trivial when the driver
1404  *                           is loaded in simulation mode (not upstreamed).
1405  * @scrub_device_mem: Scrub the entire SRAM and DRAM.
1406  * @scrub_device_dram: Scrub the dram memory of the device.
1407  * @get_int_queue_base: get the internal queue base address.
1408  * @test_queues: run simple test on all queues for sanity check.
1409  * @asic_dma_pool_zalloc: small DMA allocation of coherent memory from DMA pool.
1410  *                        size of allocation is HL_DMA_POOL_BLK_SIZE.
1411  * @asic_dma_pool_free: free small DMA allocation from pool.
1412  * @cpu_accessible_dma_pool_alloc: allocate CPU PQ packet from DMA pool.
1413  * @cpu_accessible_dma_pool_free: free CPU PQ packet from DMA pool.
1414  * @asic_dma_unmap_single: unmap a single DMA buffer
1415  * @asic_dma_map_single: map a single buffer to a DMA
1416  * @hl_dma_unmap_sgtable: DMA unmap scatter-gather table.
1417  * @cs_parser: parse Command Submission.
1418  * @asic_dma_map_sgtable: DMA map scatter-gather table.
1419  * @add_end_of_cb_packets: Add packets to the end of CB, if device requires it.
1420  * @update_eq_ci: update event queue CI.
1421  * @context_switch: called upon ASID context switch.
1422  * @restore_phase_topology: clear all SOBs amd MONs.
1423  * @debugfs_read_dma: debug interface for reading up to 2MB from the device's
1424  *                    internal memory via DMA engine.
1425  * @add_device_attr: add ASIC specific device attributes.
1426  * @handle_eqe: handle event queue entry (IRQ) from CPU-CP.
1427  * @get_events_stat: retrieve event queue entries histogram.
1428  * @read_pte: read MMU page table entry from DRAM.
1429  * @write_pte: write MMU page table entry to DRAM.
1430  * @mmu_invalidate_cache: flush MMU STLB host/DRAM cache, either with soft
1431  *                        (L1 only) or hard (L0 & L1) flush.
1432  * @mmu_invalidate_cache_range: flush specific MMU STLB cache lines with ASID-VA-size mask.
1433  * @mmu_prefetch_cache_range: pre-fetch specific MMU STLB cache lines with ASID-VA-size mask.
1434  * @send_heartbeat: send is-alive packet to CPU-CP and verify response.
1435  * @debug_coresight: perform certain actions on Coresight for debugging.
1436  * @is_device_idle: return true if device is idle, false otherwise.
1437  * @non_hard_reset_late_init: perform certain actions needed after a reset which is not hard-reset
1438  * @hw_queues_lock: acquire H/W queues lock.
1439  * @hw_queues_unlock: release H/W queues lock.
1440  * @kdma_lock: acquire H/W queues lock. Relevant from GRECO ASIC
1441  * @kdma_unlock: release H/W queues lock. Relevant from GRECO ASIC
1442  * @get_pci_id: retrieve PCI ID.
1443  * @get_eeprom_data: retrieve EEPROM data from F/W.
1444  * @get_monitor_dump: retrieve monitor registers dump from F/W.
1445  * @send_cpu_message: send message to F/W. If the message is timedout, the
1446  *                    driver will eventually reset the device. The timeout can
1447  *                    be determined by the calling function or it can be 0 and
1448  *                    then the timeout is the default timeout for the specific
1449  *                    ASIC
1450  * @get_hw_state: retrieve the H/W state
1451  * @pci_bars_map: Map PCI BARs.
1452  * @init_iatu: Initialize the iATU unit inside the PCI controller.
1453  * @rreg: Read a register. Needed for simulator support.
1454  * @wreg: Write a register. Needed for simulator support.
1455  * @halt_coresight: stop the ETF and ETR traces.
1456  * @ctx_init: context dependent initialization.
1457  * @ctx_fini: context dependent cleanup.
1458  * @pre_schedule_cs: Perform pre-CS-scheduling operations.
1459  * @get_queue_id_for_cq: Get the H/W queue id related to the given CQ index.
1460  * @load_firmware_to_device: load the firmware to the device's memory
1461  * @load_boot_fit_to_device: load boot fit to device's memory
1462  * @get_signal_cb_size: Get signal CB size.
1463  * @get_wait_cb_size: Get wait CB size.
1464  * @gen_signal_cb: Generate a signal CB.
1465  * @gen_wait_cb: Generate a wait CB.
1466  * @reset_sob: Reset a SOB.
1467  * @reset_sob_group: Reset SOB group
1468  * @get_device_time: Get the device time.
1469  * @pb_print_security_errors: print security errors according block and cause
1470  * @collective_wait_init_cs: Generate collective master/slave packets
1471  *                           and place them in the relevant cs jobs
1472  * @collective_wait_create_jobs: allocate collective wait cs jobs
1473  * @get_dec_base_addr: get the base address of a given decoder.
1474  * @scramble_addr: Routine to scramble the address prior of mapping it
1475  *                 in the MMU.
1476  * @descramble_addr: Routine to de-scramble the address prior of
1477  *                   showing it to users.
1478  * @ack_protection_bits_errors: ack and dump all security violations
1479  * @get_hw_block_id: retrieve a HW block id to be used by the user to mmap it.
1480  *                   also returns the size of the block if caller supplies
1481  *                   a valid pointer for it
1482  * @hw_block_mmap: mmap a HW block with a given id.
1483  * @enable_events_from_fw: send interrupt to firmware to notify them the
1484  *                         driver is ready to receive asynchronous events. This
1485  *                         function should be called during the first init and
1486  *                         after every hard-reset of the device
1487  * @ack_mmu_errors: check and ack mmu errors, page fault, access violation.
1488  * @get_msi_info: Retrieve asic-specific MSI ID of the f/w async event
1489  * @map_pll_idx_to_fw_idx: convert driver specific per asic PLL index to
1490  *                         generic f/w compatible PLL Indexes
1491  * @init_firmware_preload_params: initialize pre FW-load parameters.
1492  * @init_firmware_loader: initialize data for FW loader.
1493  * @init_cpu_scrambler_dram: Enable CPU specific DRAM scrambling
1494  * @state_dump_init: initialize constants required for state dump
1495  * @get_sob_addr: get SOB base address offset.
1496  * @set_pci_memory_regions: setting properties of PCI memory regions
1497  * @get_stream_master_qid_arr: get pointer to stream masters QID array
1498  * @check_if_razwi_happened: check if there was a razwi due to RR violation.
1499  * @access_dev_mem: access device memory
1500  * @set_dram_bar_base: set the base of the DRAM BAR
1501  */
1502 struct hl_asic_funcs {
1503     int (*early_init)(struct hl_device *hdev);
1504     int (*early_fini)(struct hl_device *hdev);
1505     int (*late_init)(struct hl_device *hdev);
1506     void (*late_fini)(struct hl_device *hdev);
1507     int (*sw_init)(struct hl_device *hdev);
1508     int (*sw_fini)(struct hl_device *hdev);
1509     int (*hw_init)(struct hl_device *hdev);
1510     void (*hw_fini)(struct hl_device *hdev, bool hard_reset, bool fw_reset);
1511     void (*halt_engines)(struct hl_device *hdev, bool hard_reset, bool fw_reset);
1512     int (*suspend)(struct hl_device *hdev);
1513     int (*resume)(struct hl_device *hdev);
1514     int (*mmap)(struct hl_device *hdev, struct vm_area_struct *vma,
1515             void *cpu_addr, dma_addr_t dma_addr, size_t size);
1516     void (*ring_doorbell)(struct hl_device *hdev, u32 hw_queue_id, u32 pi);
1517     void (*pqe_write)(struct hl_device *hdev, __le64 *pqe,
1518             struct hl_bd *bd);
1519     void* (*asic_dma_alloc_coherent)(struct hl_device *hdev, size_t size,
1520                     dma_addr_t *dma_handle, gfp_t flag);
1521     void (*asic_dma_free_coherent)(struct hl_device *hdev, size_t size,
1522                     void *cpu_addr, dma_addr_t dma_handle);
1523     int (*scrub_device_mem)(struct hl_device *hdev);
1524     int (*scrub_device_dram)(struct hl_device *hdev, u64 val);
1525     void* (*get_int_queue_base)(struct hl_device *hdev, u32 queue_id,
1526                 dma_addr_t *dma_handle, u16 *queue_len);
1527     int (*test_queues)(struct hl_device *hdev);
1528     void* (*asic_dma_pool_zalloc)(struct hl_device *hdev, size_t size,
1529                 gfp_t mem_flags, dma_addr_t *dma_handle);
1530     void (*asic_dma_pool_free)(struct hl_device *hdev, void *vaddr,
1531                 dma_addr_t dma_addr);
1532     void* (*cpu_accessible_dma_pool_alloc)(struct hl_device *hdev,
1533                 size_t size, dma_addr_t *dma_handle);
1534     void (*cpu_accessible_dma_pool_free)(struct hl_device *hdev,
1535                 size_t size, void *vaddr);
1536     void (*asic_dma_unmap_single)(struct hl_device *hdev,
1537                 dma_addr_t dma_addr, int len,
1538                 enum dma_data_direction dir);
1539     dma_addr_t (*asic_dma_map_single)(struct hl_device *hdev,
1540                 void *addr, int len,
1541                 enum dma_data_direction dir);
1542     void (*hl_dma_unmap_sgtable)(struct hl_device *hdev,
1543                 struct sg_table *sgt,
1544                 enum dma_data_direction dir);
1545     int (*cs_parser)(struct hl_device *hdev, struct hl_cs_parser *parser);
1546     int (*asic_dma_map_sgtable)(struct hl_device *hdev, struct sg_table *sgt,
1547                 enum dma_data_direction dir);
1548     void (*add_end_of_cb_packets)(struct hl_device *hdev,
1549                     void *kernel_address, u32 len,
1550                     u32 original_len,
1551                     u64 cq_addr, u32 cq_val, u32 msix_num,
1552                     bool eb);
1553     void (*update_eq_ci)(struct hl_device *hdev, u32 val);
1554     int (*context_switch)(struct hl_device *hdev, u32 asid);
1555     void (*restore_phase_topology)(struct hl_device *hdev);
1556     int (*debugfs_read_dma)(struct hl_device *hdev, u64 addr, u32 size,
1557                 void *blob_addr);
1558     void (*add_device_attr)(struct hl_device *hdev, struct attribute_group *dev_clk_attr_grp,
1559                 struct attribute_group *dev_vrm_attr_grp);
1560     void (*handle_eqe)(struct hl_device *hdev,
1561                 struct hl_eq_entry *eq_entry);
1562     void* (*get_events_stat)(struct hl_device *hdev, bool aggregate,
1563                 u32 *size);
1564     u64 (*read_pte)(struct hl_device *hdev, u64 addr);
1565     void (*write_pte)(struct hl_device *hdev, u64 addr, u64 val);
1566     int (*mmu_invalidate_cache)(struct hl_device *hdev, bool is_hard,
1567                     u32 flags);
1568     int (*mmu_invalidate_cache_range)(struct hl_device *hdev, bool is_hard,
1569                 u32 flags, u32 asid, u64 va, u64 size);
1570     int (*mmu_prefetch_cache_range)(struct hl_ctx *ctx, u32 flags, u32 asid, u64 va, u64 size);
1571     int (*send_heartbeat)(struct hl_device *hdev);
1572     int (*debug_coresight)(struct hl_device *hdev, struct hl_ctx *ctx, void *data);
1573     bool (*is_device_idle)(struct hl_device *hdev, u64 *mask_arr,
1574                     u8 mask_len, struct seq_file *s);
1575     int (*non_hard_reset_late_init)(struct hl_device *hdev);
1576     void (*hw_queues_lock)(struct hl_device *hdev);
1577     void (*hw_queues_unlock)(struct hl_device *hdev);
1578     void (*kdma_lock)(struct hl_device *hdev, int dcore_id);
1579     void (*kdma_unlock)(struct hl_device *hdev, int dcore_id);
1580     u32 (*get_pci_id)(struct hl_device *hdev);
1581     int (*get_eeprom_data)(struct hl_device *hdev, void *data, size_t max_size);
1582     int (*get_monitor_dump)(struct hl_device *hdev, void *data);
1583     int (*send_cpu_message)(struct hl_device *hdev, u32 *msg,
1584                 u16 len, u32 timeout, u64 *result);
1585     int (*pci_bars_map)(struct hl_device *hdev);
1586     int (*init_iatu)(struct hl_device *hdev);
1587     u32 (*rreg)(struct hl_device *hdev, u32 reg);
1588     void (*wreg)(struct hl_device *hdev, u32 reg, u32 val);
1589     void (*halt_coresight)(struct hl_device *hdev, struct hl_ctx *ctx);
1590     int (*ctx_init)(struct hl_ctx *ctx);
1591     void (*ctx_fini)(struct hl_ctx *ctx);
1592     int (*pre_schedule_cs)(struct hl_cs *cs);
1593     u32 (*get_queue_id_for_cq)(struct hl_device *hdev, u32 cq_idx);
1594     int (*load_firmware_to_device)(struct hl_device *hdev);
1595     int (*load_boot_fit_to_device)(struct hl_device *hdev);
1596     u32 (*get_signal_cb_size)(struct hl_device *hdev);
1597     u32 (*get_wait_cb_size)(struct hl_device *hdev);
1598     u32 (*gen_signal_cb)(struct hl_device *hdev, void *data, u16 sob_id,
1599             u32 size, bool eb);
1600     u32 (*gen_wait_cb)(struct hl_device *hdev,
1601             struct hl_gen_wait_properties *prop);
1602     void (*reset_sob)(struct hl_device *hdev, void *data);
1603     void (*reset_sob_group)(struct hl_device *hdev, u16 sob_group);
1604     u64 (*get_device_time)(struct hl_device *hdev);
1605     void (*pb_print_security_errors)(struct hl_device *hdev,
1606             u32 block_addr, u32 cause, u32 offended_addr);
1607     int (*collective_wait_init_cs)(struct hl_cs *cs);
1608     int (*collective_wait_create_jobs)(struct hl_device *hdev,
1609             struct hl_ctx *ctx, struct hl_cs *cs,
1610             u32 wait_queue_id, u32 collective_engine_id,
1611             u32 encaps_signal_offset);
1612     u32 (*get_dec_base_addr)(struct hl_device *hdev, u32 core_id);
1613     u64 (*scramble_addr)(struct hl_device *hdev, u64 addr);
1614     u64 (*descramble_addr)(struct hl_device *hdev, u64 addr);
1615     void (*ack_protection_bits_errors)(struct hl_device *hdev);
1616     int (*get_hw_block_id)(struct hl_device *hdev, u64 block_addr,
1617                 u32 *block_size, u32 *block_id);
1618     int (*hw_block_mmap)(struct hl_device *hdev, struct vm_area_struct *vma,
1619             u32 block_id, u32 block_size);
1620     void (*enable_events_from_fw)(struct hl_device *hdev);
1621     int (*ack_mmu_errors)(struct hl_device *hdev, u64 mmu_cap_mask);
1622     void (*get_msi_info)(__le32 *table);
1623     int (*map_pll_idx_to_fw_idx)(u32 pll_idx);
1624     void (*init_firmware_preload_params)(struct hl_device *hdev);
1625     void (*init_firmware_loader)(struct hl_device *hdev);
1626     void (*init_cpu_scrambler_dram)(struct hl_device *hdev);
1627     void (*state_dump_init)(struct hl_device *hdev);
1628     u32 (*get_sob_addr)(struct hl_device *hdev, u32 sob_id);
1629     void (*set_pci_memory_regions)(struct hl_device *hdev);
1630     u32* (*get_stream_master_qid_arr)(void);
1631     void (*check_if_razwi_happened)(struct hl_device *hdev);
1632     int (*mmu_get_real_page_size)(struct hl_device *hdev, struct hl_mmu_properties *mmu_prop,
1633                     u32 page_size, u32 *real_page_size, bool is_dram_addr);
1634     int (*access_dev_mem)(struct hl_device *hdev, enum pci_region region_type,
1635                 u64 addr, u64 *val, enum debugfs_access_type acc_type);
1636     u64 (*set_dram_bar_base)(struct hl_device *hdev, u64 addr);
1637 };
1638 
1639 
1640 /*
1641  * CONTEXTS
1642  */
1643 
1644 #define HL_KERNEL_ASID_ID   0
1645 
1646 /**
1647  * enum hl_va_range_type - virtual address range type.
1648  * @HL_VA_RANGE_TYPE_HOST: range type of host pages
1649  * @HL_VA_RANGE_TYPE_HOST_HUGE: range type of host huge pages
1650  * @HL_VA_RANGE_TYPE_DRAM: range type of dram pages
1651  */
1652 enum hl_va_range_type {
1653     HL_VA_RANGE_TYPE_HOST,
1654     HL_VA_RANGE_TYPE_HOST_HUGE,
1655     HL_VA_RANGE_TYPE_DRAM,
1656     HL_VA_RANGE_TYPE_MAX
1657 };
1658 
1659 /**
1660  * struct hl_va_range - virtual addresses range.
1661  * @lock: protects the virtual addresses list.
1662  * @list: list of virtual addresses blocks available for mappings.
1663  * @start_addr: range start address.
1664  * @end_addr: range end address.
1665  * @page_size: page size of this va range.
1666  */
1667 struct hl_va_range {
1668     struct mutex        lock;
1669     struct list_head    list;
1670     u64         start_addr;
1671     u64         end_addr;
1672     u32         page_size;
1673 };
1674 
1675 /**
1676  * struct hl_cs_counters_atomic - command submission counters
1677  * @out_of_mem_drop_cnt: dropped due to memory allocation issue
1678  * @parsing_drop_cnt: dropped due to error in packet parsing
1679  * @queue_full_drop_cnt: dropped due to queue full
1680  * @device_in_reset_drop_cnt: dropped due to device in reset
1681  * @max_cs_in_flight_drop_cnt: dropped due to maximum CS in-flight
1682  * @validation_drop_cnt: dropped due to error in validation
1683  */
1684 struct hl_cs_counters_atomic {
1685     atomic64_t out_of_mem_drop_cnt;
1686     atomic64_t parsing_drop_cnt;
1687     atomic64_t queue_full_drop_cnt;
1688     atomic64_t device_in_reset_drop_cnt;
1689     atomic64_t max_cs_in_flight_drop_cnt;
1690     atomic64_t validation_drop_cnt;
1691 };
1692 
1693 /**
1694  * struct hl_dmabuf_priv - a dma-buf private object.
1695  * @dmabuf: pointer to dma-buf object.
1696  * @ctx: pointer to the dma-buf owner's context.
1697  * @phys_pg_pack: pointer to physical page pack if the dma-buf was exported for
1698  *                memory allocation handle.
1699  * @device_address: physical address of the device's memory. Relevant only
1700  *                  if phys_pg_pack is NULL (dma-buf was exported from address).
1701  *                  The total size can be taken from the dmabuf object.
1702  */
1703 struct hl_dmabuf_priv {
1704     struct dma_buf          *dmabuf;
1705     struct hl_ctx           *ctx;
1706     struct hl_vm_phys_pg_pack   *phys_pg_pack;
1707     uint64_t            device_address;
1708 };
1709 
1710 #define HL_CS_OUTCOME_HISTORY_LEN 256
1711 
1712 /**
1713  * struct hl_cs_outcome - represents a single completed CS outcome
1714  * @list_link: link to either container's used list or free list
1715  * @map_link: list to the container hash map
1716  * @ts: completion ts
1717  * @seq: the original cs sequence
1718  * @error: error code cs completed with, if any
1719  */
1720 struct hl_cs_outcome {
1721     struct list_head list_link;
1722     struct hlist_node map_link;
1723     ktime_t ts;
1724     u64 seq;
1725     int error;
1726 };
1727 
1728 /**
1729  * struct hl_cs_outcome_store - represents a limited store of completed CS outcomes
1730  * @outcome_map: index of completed CS searcheable by sequence number
1731  * @used_list: list of outcome objects currently in use
1732  * @free_list: list of outcome objects currently not in use
1733  * @nodes_pool: a static pool of preallocated outcome objects
1734  * @db_lock: any operation on the store must take this lock
1735  */
1736 struct hl_cs_outcome_store {
1737     DECLARE_HASHTABLE(outcome_map, 8);
1738     struct list_head used_list;
1739     struct list_head free_list;
1740     struct hl_cs_outcome nodes_pool[HL_CS_OUTCOME_HISTORY_LEN];
1741     spinlock_t db_lock;
1742 };
1743 
1744 /**
1745  * struct hl_ctx - user/kernel context.
1746  * @mem_hash: holds mapping from virtual address to virtual memory area
1747  *      descriptor (hl_vm_phys_pg_list or hl_userptr).
1748  * @mmu_shadow_hash: holds a mapping from shadow address to pgt_info structure.
1749  * @hr_mmu_phys_hash: if host-resident MMU is used, holds a mapping from
1750  *                    MMU-hop-page physical address to its host-resident
1751  *                    pgt_info structure.
1752  * @hpriv: pointer to the private (Kernel Driver) data of the process (fd).
1753  * @hdev: pointer to the device structure.
1754  * @refcount: reference counter for the context. Context is released only when
1755  *      this hits 0l. It is incremented on CS and CS_WAIT.
1756  * @cs_pending: array of hl fence objects representing pending CS.
1757  * @outcome_store: storage data structure used to remember ouitcomes of completed
1758  *                 command submissions for a long time after CS id wraparound.
1759  * @va_range: holds available virtual addresses for host and dram mappings.
1760  * @mem_hash_lock: protects the mem_hash.
1761  * @mmu_lock: protects the MMU page tables. Any change to the PGT, modifying the
1762  *            MMU hash or walking the PGT requires talking this lock.
1763  * @hw_block_list_lock: protects the HW block memory list.
1764  * @debugfs_list: node in debugfs list of contexts.
1765  * @hw_block_mem_list: list of HW block virtual mapped addresses.
1766  * @cs_counters: context command submission counters.
1767  * @cb_va_pool: device VA pool for command buffers which are mapped to the
1768  *              device's MMU.
1769  * @sig_mgr: encaps signals handle manager.
1770  * @cs_sequence: sequence number for CS. Value is assigned to a CS and passed
1771  *          to user so user could inquire about CS. It is used as
1772  *          index to cs_pending array.
1773  * @dram_default_hops: array that holds all hops addresses needed for default
1774  *                     DRAM mapping.
1775  * @cs_lock: spinlock to protect cs_sequence.
1776  * @dram_phys_mem: amount of used physical DRAM memory by this context.
1777  * @thread_ctx_switch_token: token to prevent multiple threads of the same
1778  *              context from running the context switch phase.
1779  *              Only a single thread should run it.
1780  * @thread_ctx_switch_wait_token: token to prevent the threads that didn't run
1781  *              the context switch phase from moving to their
1782  *              execution phase before the context switch phase
1783  *              has finished.
1784  * @asid: context's unique address space ID in the device's MMU.
1785  * @handle: context's opaque handle for user
1786  */
1787 struct hl_ctx {
1788     DECLARE_HASHTABLE(mem_hash, MEM_HASH_TABLE_BITS);
1789     DECLARE_HASHTABLE(mmu_shadow_hash, MMU_HASH_TABLE_BITS);
1790     DECLARE_HASHTABLE(hr_mmu_phys_hash, MMU_HASH_TABLE_BITS);
1791     struct hl_fpriv         *hpriv;
1792     struct hl_device        *hdev;
1793     struct kref         refcount;
1794     struct hl_fence         **cs_pending;
1795     struct hl_cs_outcome_store  outcome_store;
1796     struct hl_va_range      *va_range[HL_VA_RANGE_TYPE_MAX];
1797     struct mutex            mem_hash_lock;
1798     struct mutex            mmu_lock;
1799     struct mutex            hw_block_list_lock;
1800     struct list_head        debugfs_list;
1801     struct list_head        hw_block_mem_list;
1802     struct hl_cs_counters_atomic    cs_counters;
1803     struct gen_pool         *cb_va_pool;
1804     struct hl_encaps_signals_mgr    sig_mgr;
1805     u64             cs_sequence;
1806     u64             *dram_default_hops;
1807     spinlock_t          cs_lock;
1808     atomic64_t          dram_phys_mem;
1809     atomic_t            thread_ctx_switch_token;
1810     u32             thread_ctx_switch_wait_token;
1811     u32             asid;
1812     u32             handle;
1813 };
1814 
1815 /**
1816  * struct hl_ctx_mgr - for handling multiple contexts.
1817  * @lock: protects ctx_handles.
1818  * @handles: idr to hold all ctx handles.
1819  */
1820 struct hl_ctx_mgr {
1821     struct mutex    lock;
1822     struct idr  handles;
1823 };
1824 
1825 
1826 
1827 /*
1828  * COMMAND SUBMISSIONS
1829  */
1830 
1831 /**
1832  * struct hl_userptr - memory mapping chunk information
1833  * @vm_type: type of the VM.
1834  * @job_node: linked-list node for hanging the object on the Job's list.
1835  * @pages: pointer to struct page array
1836  * @npages: size of @pages array
1837  * @sgt: pointer to the scatter-gather table that holds the pages.
1838  * @dir: for DMA unmapping, the direction must be supplied, so save it.
1839  * @debugfs_list: node in debugfs list of command submissions.
1840  * @pid: the pid of the user process owning the memory
1841  * @addr: user-space virtual address of the start of the memory area.
1842  * @size: size of the memory area to pin & map.
1843  * @dma_mapped: true if the SG was mapped to DMA addresses, false otherwise.
1844  */
1845 struct hl_userptr {
1846     enum vm_type        vm_type; /* must be first */
1847     struct list_head    job_node;
1848     struct page     **pages;
1849     unsigned int        npages;
1850     struct sg_table     *sgt;
1851     enum dma_data_direction dir;
1852     struct list_head    debugfs_list;
1853     pid_t           pid;
1854     u64         addr;
1855     u64         size;
1856     u8          dma_mapped;
1857 };
1858 
1859 /**
1860  * struct hl_cs - command submission.
1861  * @jobs_in_queue_cnt: per each queue, maintain counter of submitted jobs.
1862  * @ctx: the context this CS belongs to.
1863  * @job_list: list of the CS's jobs in the various queues.
1864  * @job_lock: spinlock for the CS's jobs list. Needed for free_job.
1865  * @refcount: reference counter for usage of the CS.
1866  * @fence: pointer to the fence object of this CS.
1867  * @signal_fence: pointer to the fence object of the signal CS (used by wait
1868  *                CS only).
1869  * @finish_work: workqueue object to run when CS is completed by H/W.
1870  * @work_tdr: delayed work node for TDR.
1871  * @mirror_node : node in device mirror list of command submissions.
1872  * @staged_cs_node: node in the staged cs list.
1873  * @debugfs_list: node in debugfs list of command submissions.
1874  * @encaps_sig_hdl: holds the encaps signals handle.
1875  * @sequence: the sequence number of this CS.
1876  * @staged_sequence: the sequence of the staged submission this CS is part of,
1877  *                   relevant only if staged_cs is set.
1878  * @timeout_jiffies: cs timeout in jiffies.
1879  * @submission_time_jiffies: submission time of the cs
1880  * @type: CS_TYPE_*.
1881  * @jobs_cnt: counter of submitted jobs on all queues.
1882  * @encaps_sig_hdl_id: encaps signals handle id, set for the first staged cs.
1883  * @sob_addr_offset: sob offset from the configuration base address.
1884  * @initial_sob_count: count of completed signals in SOB before current submission of signal or
1885  *                     cs with encaps signals.
1886  * @submitted: true if CS was submitted to H/W.
1887  * @completed: true if CS was completed by device.
1888  * @timedout : true if CS was timedout.
1889  * @tdr_active: true if TDR was activated for this CS (to prevent
1890  *      double TDR activation).
1891  * @aborted: true if CS was aborted due to some device error.
1892  * @timestamp: true if a timestmap must be captured upon completion.
1893  * @staged_last: true if this is the last staged CS and needs completion.
1894  * @staged_first: true if this is the first staged CS and we need to receive
1895  *                timeout for this CS.
1896  * @staged_cs: true if this CS is part of a staged submission.
1897  * @skip_reset_on_timeout: true if we shall not reset the device in case
1898  *                         timeout occurs (debug scenario).
1899  * @encaps_signals: true if this CS has encaps reserved signals.
1900  */
1901 struct hl_cs {
1902     u16         *jobs_in_queue_cnt;
1903     struct hl_ctx       *ctx;
1904     struct list_head    job_list;
1905     spinlock_t      job_lock;
1906     struct kref     refcount;
1907     struct hl_fence     *fence;
1908     struct hl_fence     *signal_fence;
1909     struct work_struct  finish_work;
1910     struct delayed_work work_tdr;
1911     struct list_head    mirror_node;
1912     struct list_head    staged_cs_node;
1913     struct list_head    debugfs_list;
1914     struct hl_cs_encaps_sig_handle *encaps_sig_hdl;
1915     u64         sequence;
1916     u64         staged_sequence;
1917     u64         timeout_jiffies;
1918     u64         submission_time_jiffies;
1919     enum hl_cs_type     type;
1920     u32         jobs_cnt;
1921     u32         encaps_sig_hdl_id;
1922     u32         sob_addr_offset;
1923     u16         initial_sob_count;
1924     u8          submitted;
1925     u8          completed;
1926     u8          timedout;
1927     u8          tdr_active;
1928     u8          aborted;
1929     u8          timestamp;
1930     u8          staged_last;
1931     u8          staged_first;
1932     u8          staged_cs;
1933     u8          skip_reset_on_timeout;
1934     u8          encaps_signals;
1935 };
1936 
1937 /**
1938  * struct hl_cs_job - command submission job.
1939  * @cs_node: the node to hang on the CS jobs list.
1940  * @cs: the CS this job belongs to.
1941  * @user_cb: the CB we got from the user.
1942  * @patched_cb: in case of patching, this is internal CB which is submitted on
1943  *      the queue instead of the CB we got from the IOCTL.
1944  * @finish_work: workqueue object to run when job is completed.
1945  * @userptr_list: linked-list of userptr mappings that belong to this job and
1946  *          wait for completion.
1947  * @debugfs_list: node in debugfs list of command submission jobs.
1948  * @refcount: reference counter for usage of the CS job.
1949  * @queue_type: the type of the H/W queue this job is submitted to.
1950  * @id: the id of this job inside a CS.
1951  * @hw_queue_id: the id of the H/W queue this job is submitted to.
1952  * @user_cb_size: the actual size of the CB we got from the user.
1953  * @job_cb_size: the actual size of the CB that we put on the queue.
1954  * @encaps_sig_wait_offset: encapsulated signals offset, which allow user
1955  *                          to wait on part of the reserved signals.
1956  * @is_kernel_allocated_cb: true if the CB handle we got from the user holds a
1957  *                          handle to a kernel-allocated CB object, false
1958  *                          otherwise (SRAM/DRAM/host address).
1959  * @contains_dma_pkt: whether the JOB contains at least one DMA packet. This
1960  *                    info is needed later, when adding the 2xMSG_PROT at the
1961  *                    end of the JOB, to know which barriers to put in the
1962  *                    MSG_PROT packets. Relevant only for GAUDI as GOYA doesn't
1963  *                    have streams so the engine can't be busy by another
1964  *                    stream.
1965  */
1966 struct hl_cs_job {
1967     struct list_head    cs_node;
1968     struct hl_cs        *cs;
1969     struct hl_cb        *user_cb;
1970     struct hl_cb        *patched_cb;
1971     struct work_struct  finish_work;
1972     struct list_head    userptr_list;
1973     struct list_head    debugfs_list;
1974     struct kref     refcount;
1975     enum hl_queue_type  queue_type;
1976     u32         id;
1977     u32         hw_queue_id;
1978     u32         user_cb_size;
1979     u32         job_cb_size;
1980     u32         encaps_sig_wait_offset;
1981     u8          is_kernel_allocated_cb;
1982     u8          contains_dma_pkt;
1983 };
1984 
1985 /**
1986  * struct hl_cs_parser - command submission parser properties.
1987  * @user_cb: the CB we got from the user.
1988  * @patched_cb: in case of patching, this is internal CB which is submitted on
1989  *      the queue instead of the CB we got from the IOCTL.
1990  * @job_userptr_list: linked-list of userptr mappings that belong to the related
1991  *          job and wait for completion.
1992  * @cs_sequence: the sequence number of the related CS.
1993  * @queue_type: the type of the H/W queue this job is submitted to.
1994  * @ctx_id: the ID of the context the related CS belongs to.
1995  * @hw_queue_id: the id of the H/W queue this job is submitted to.
1996  * @user_cb_size: the actual size of the CB we got from the user.
1997  * @patched_cb_size: the size of the CB after parsing.
1998  * @job_id: the id of the related job inside the related CS.
1999  * @is_kernel_allocated_cb: true if the CB handle we got from the user holds a
2000  *                          handle to a kernel-allocated CB object, false
2001  *                          otherwise (SRAM/DRAM/host address).
2002  * @contains_dma_pkt: whether the JOB contains at least one DMA packet. This
2003  *                    info is needed later, when adding the 2xMSG_PROT at the
2004  *                    end of the JOB, to know which barriers to put in the
2005  *                    MSG_PROT packets. Relevant only for GAUDI as GOYA doesn't
2006  *                    have streams so the engine can't be busy by another
2007  *                    stream.
2008  * @completion: true if we need completion for this CS.
2009  */
2010 struct hl_cs_parser {
2011     struct hl_cb        *user_cb;
2012     struct hl_cb        *patched_cb;
2013     struct list_head    *job_userptr_list;
2014     u64         cs_sequence;
2015     enum hl_queue_type  queue_type;
2016     u32         ctx_id;
2017     u32         hw_queue_id;
2018     u32         user_cb_size;
2019     u32         patched_cb_size;
2020     u8          job_id;
2021     u8          is_kernel_allocated_cb;
2022     u8          contains_dma_pkt;
2023     u8          completion;
2024 };
2025 
2026 /*
2027  * MEMORY STRUCTURE
2028  */
2029 
2030 /**
2031  * struct hl_vm_hash_node - hash element from virtual address to virtual
2032  *              memory area descriptor (hl_vm_phys_pg_list or
2033  *              hl_userptr).
2034  * @node: node to hang on the hash table in context object.
2035  * @vaddr: key virtual address.
2036  * @ptr: value pointer (hl_vm_phys_pg_list or hl_userptr).
2037  */
2038 struct hl_vm_hash_node {
2039     struct hlist_node   node;
2040     u64         vaddr;
2041     void            *ptr;
2042 };
2043 
2044 /**
2045  * struct hl_vm_hw_block_list_node - list element from user virtual address to
2046  *              HW block id.
2047  * @node: node to hang on the list in context object.
2048  * @ctx: the context this node belongs to.
2049  * @vaddr: virtual address of the HW block.
2050  * @size: size of the block.
2051  * @id: HW block id (handle).
2052  */
2053 struct hl_vm_hw_block_list_node {
2054     struct list_head    node;
2055     struct hl_ctx       *ctx;
2056     unsigned long       vaddr;
2057     u32         size;
2058     u32         id;
2059 };
2060 
2061 /**
2062  * struct hl_vm_phys_pg_pack - physical page pack.
2063  * @vm_type: describes the type of the virtual area descriptor.
2064  * @pages: the physical page array.
2065  * @npages: num physical pages in the pack.
2066  * @total_size: total size of all the pages in this list.
2067  * @node: used to attach to deletion list that is used when all the allocations are cleared
2068  *        at the teardown of the context.
2069  * @mapping_cnt: number of shared mappings.
2070  * @exporting_cnt: number of dma-buf exporting.
2071  * @asid: the context related to this list.
2072  * @page_size: size of each page in the pack.
2073  * @flags: HL_MEM_* flags related to this list.
2074  * @handle: the provided handle related to this list.
2075  * @offset: offset from the first page.
2076  * @contiguous: is contiguous physical memory.
2077  * @created_from_userptr: is product of host virtual address.
2078  */
2079 struct hl_vm_phys_pg_pack {
2080     enum vm_type        vm_type; /* must be first */
2081     u64         *pages;
2082     u64         npages;
2083     u64         total_size;
2084     struct list_head    node;
2085     atomic_t        mapping_cnt;
2086     u32         exporting_cnt;
2087     u32         asid;
2088     u32         page_size;
2089     u32         flags;
2090     u32         handle;
2091     u32         offset;
2092     u8          contiguous;
2093     u8          created_from_userptr;
2094 };
2095 
2096 /**
2097  * struct hl_vm_va_block - virtual range block information.
2098  * @node: node to hang on the virtual range list in context object.
2099  * @start: virtual range start address.
2100  * @end: virtual range end address.
2101  * @size: virtual range size.
2102  */
2103 struct hl_vm_va_block {
2104     struct list_head    node;
2105     u64         start;
2106     u64         end;
2107     u64         size;
2108 };
2109 
2110 /**
2111  * struct hl_vm - virtual memory manager for MMU.
2112  * @dram_pg_pool: pool for DRAM physical pages of 2MB.
2113  * @dram_pg_pool_refcount: reference counter for the pool usage.
2114  * @idr_lock: protects the phys_pg_list_handles.
2115  * @phys_pg_pack_handles: idr to hold all device allocations handles.
2116  * @init_done: whether initialization was done. We need this because VM
2117  *      initialization might be skipped during device initialization.
2118  */
2119 struct hl_vm {
2120     struct gen_pool     *dram_pg_pool;
2121     struct kref     dram_pg_pool_refcount;
2122     spinlock_t      idr_lock;
2123     struct idr      phys_pg_pack_handles;
2124     u8          init_done;
2125 };
2126 
2127 
2128 /*
2129  * DEBUG, PROFILING STRUCTURE
2130  */
2131 
2132 /**
2133  * struct hl_debug_params - Coresight debug parameters.
2134  * @input: pointer to component specific input parameters.
2135  * @output: pointer to component specific output parameters.
2136  * @output_size: size of output buffer.
2137  * @reg_idx: relevant register ID.
2138  * @op: component operation to execute.
2139  * @enable: true if to enable component debugging, false otherwise.
2140  */
2141 struct hl_debug_params {
2142     void *input;
2143     void *output;
2144     u32 output_size;
2145     u32 reg_idx;
2146     u32 op;
2147     bool enable;
2148 };
2149 
2150 /**
2151  * struct hl_notifier_event - holds the notifier data structure
2152  * @eventfd: the event file descriptor to raise the notifications
2153  * @lock: mutex lock to protect the notifier data flows
2154  * @events_mask: indicates the bitmap events
2155  */
2156 struct hl_notifier_event {
2157     struct eventfd_ctx  *eventfd;
2158     struct mutex        lock;
2159     u64         events_mask;
2160 };
2161 
2162 /*
2163  * FILE PRIVATE STRUCTURE
2164  */
2165 
2166 /**
2167  * struct hl_fpriv - process information stored in FD private data.
2168  * @hdev: habanalabs device structure.
2169  * @filp: pointer to the given file structure.
2170  * @taskpid: current process ID.
2171  * @ctx: current executing context. TODO: remove for multiple ctx per process
2172  * @ctx_mgr: context manager to handle multiple context for this FD.
2173  * @mem_mgr: manager descriptor for memory exportable via mmap
2174  * @notifier_event: notifier eventfd towards user process
2175  * @debugfs_list: list of relevant ASIC debugfs.
2176  * @dev_node: node in the device list of file private data
2177  * @refcount: number of related contexts.
2178  * @restore_phase_mutex: lock for context switch and restore phase.
2179  * @ctx_lock: protects the pointer to current executing context pointer. TODO: remove for multiple
2180  *            ctx per process.
2181  */
2182 struct hl_fpriv {
2183     struct hl_device        *hdev;
2184     struct file         *filp;
2185     struct pid          *taskpid;
2186     struct hl_ctx           *ctx;
2187     struct hl_ctx_mgr       ctx_mgr;
2188     struct hl_mem_mgr       mem_mgr;
2189     struct hl_notifier_event    notifier_event;
2190     struct list_head        debugfs_list;
2191     struct list_head        dev_node;
2192     struct kref         refcount;
2193     struct mutex            restore_phase_mutex;
2194     struct mutex            ctx_lock;
2195 };
2196 
2197 
2198 /*
2199  * DebugFS
2200  */
2201 
2202 /**
2203  * struct hl_info_list - debugfs file ops.
2204  * @name: file name.
2205  * @show: function to output information.
2206  * @write: function to write to the file.
2207  */
2208 struct hl_info_list {
2209     const char  *name;
2210     int     (*show)(struct seq_file *s, void *data);
2211     ssize_t     (*write)(struct file *file, const char __user *buf,
2212                 size_t count, loff_t *f_pos);
2213 };
2214 
2215 /**
2216  * struct hl_debugfs_entry - debugfs dentry wrapper.
2217  * @info_ent: dentry realted ops.
2218  * @dev_entry: ASIC specific debugfs manager.
2219  */
2220 struct hl_debugfs_entry {
2221     const struct hl_info_list   *info_ent;
2222     struct hl_dbg_device_entry  *dev_entry;
2223 };
2224 
2225 /**
2226  * struct hl_dbg_device_entry - ASIC specific debugfs manager.
2227  * @root: root dentry.
2228  * @hdev: habanalabs device structure.
2229  * @entry_arr: array of available hl_debugfs_entry.
2230  * @file_list: list of available debugfs files.
2231  * @file_mutex: protects file_list.
2232  * @cb_list: list of available CBs.
2233  * @cb_spinlock: protects cb_list.
2234  * @cs_list: list of available CSs.
2235  * @cs_spinlock: protects cs_list.
2236  * @cs_job_list: list of available CB jobs.
2237  * @cs_job_spinlock: protects cs_job_list.
2238  * @userptr_list: list of available userptrs (virtual memory chunk descriptor).
2239  * @userptr_spinlock: protects userptr_list.
2240  * @ctx_mem_hash_list: list of available contexts with MMU mappings.
2241  * @ctx_mem_hash_spinlock: protects cb_list.
2242  * @data_dma_blob_desc: data DMA descriptor of blob.
2243  * @mon_dump_blob_desc: monitor dump descriptor of blob.
2244  * @state_dump: data of the system states in case of a bad cs.
2245  * @state_dump_sem: protects state_dump.
2246  * @addr: next address to read/write from/to in read/write32.
2247  * @mmu_addr: next virtual address to translate to physical address in mmu_show.
2248  * @mmu_cap_mask: mmu hw capability mask, to be used in mmu_ack_error.
2249  * @userptr_lookup: the target user ptr to look up for on demand.
2250  * @mmu_asid: ASID to use while translating in mmu_show.
2251  * @state_dump_head: index of the latest state dump
2252  * @i2c_bus: generic u8 debugfs file for bus value to use in i2c_data_read.
2253  * @i2c_addr: generic u8 debugfs file for address value to use in i2c_data_read.
2254  * @i2c_reg: generic u8 debugfs file for register value to use in i2c_data_read.
2255  * @i2c_len: generic u8 debugfs file for length value to use in i2c_data_read.
2256  */
2257 struct hl_dbg_device_entry {
2258     struct dentry           *root;
2259     struct hl_device        *hdev;
2260     struct hl_debugfs_entry     *entry_arr;
2261     struct list_head        file_list;
2262     struct mutex            file_mutex;
2263     struct list_head        cb_list;
2264     spinlock_t          cb_spinlock;
2265     struct list_head        cs_list;
2266     spinlock_t          cs_spinlock;
2267     struct list_head        cs_job_list;
2268     spinlock_t          cs_job_spinlock;
2269     struct list_head        userptr_list;
2270     spinlock_t          userptr_spinlock;
2271     struct list_head        ctx_mem_hash_list;
2272     spinlock_t          ctx_mem_hash_spinlock;
2273     struct debugfs_blob_wrapper data_dma_blob_desc;
2274     struct debugfs_blob_wrapper mon_dump_blob_desc;
2275     char                *state_dump[HL_STATE_DUMP_HIST_LEN];
2276     struct rw_semaphore     state_dump_sem;
2277     u64             addr;
2278     u64             mmu_addr;
2279     u64             mmu_cap_mask;
2280     u64             userptr_lookup;
2281     u32             mmu_asid;
2282     u32             state_dump_head;
2283     u8              i2c_bus;
2284     u8              i2c_addr;
2285     u8              i2c_reg;
2286     u8              i2c_len;
2287 };
2288 
2289 /**
2290  * struct hl_hw_obj_name_entry - single hw object name, member of
2291  * hl_state_dump_specs
2292  * @node: link to the containing hash table
2293  * @name: hw object name
2294  * @id: object identifier
2295  */
2296 struct hl_hw_obj_name_entry {
2297     struct hlist_node   node;
2298     const char      *name;
2299     u32         id;
2300 };
2301 
2302 enum hl_state_dump_specs_props {
2303     SP_SYNC_OBJ_BASE_ADDR,
2304     SP_NEXT_SYNC_OBJ_ADDR,
2305     SP_SYNC_OBJ_AMOUNT,
2306     SP_MON_OBJ_WR_ADDR_LOW,
2307     SP_MON_OBJ_WR_ADDR_HIGH,
2308     SP_MON_OBJ_WR_DATA,
2309     SP_MON_OBJ_ARM_DATA,
2310     SP_MON_OBJ_STATUS,
2311     SP_MONITORS_AMOUNT,
2312     SP_TPC0_CMDQ,
2313     SP_TPC0_CFG_SO,
2314     SP_NEXT_TPC,
2315     SP_MME_CMDQ,
2316     SP_MME_CFG_SO,
2317     SP_NEXT_MME,
2318     SP_DMA_CMDQ,
2319     SP_DMA_CFG_SO,
2320     SP_DMA_QUEUES_OFFSET,
2321     SP_NUM_OF_MME_ENGINES,
2322     SP_SUB_MME_ENG_NUM,
2323     SP_NUM_OF_DMA_ENGINES,
2324     SP_NUM_OF_TPC_ENGINES,
2325     SP_ENGINE_NUM_OF_QUEUES,
2326     SP_ENGINE_NUM_OF_STREAMS,
2327     SP_ENGINE_NUM_OF_FENCES,
2328     SP_FENCE0_CNT_OFFSET,
2329     SP_FENCE0_RDATA_OFFSET,
2330     SP_CP_STS_OFFSET,
2331     SP_NUM_CORES,
2332 
2333     SP_MAX
2334 };
2335 
2336 enum hl_sync_engine_type {
2337     ENGINE_TPC,
2338     ENGINE_DMA,
2339     ENGINE_MME,
2340 };
2341 
2342 /**
2343  * struct hl_mon_state_dump - represents a state dump of a single monitor
2344  * @id: monitor id
2345  * @wr_addr_low: address monitor will write to, low bits
2346  * @wr_addr_high: address monitor will write to, high bits
2347  * @wr_data: data monitor will write
2348  * @arm_data: register value containing monitor configuration
2349  * @status: monitor status
2350  */
2351 struct hl_mon_state_dump {
2352     u32     id;
2353     u32     wr_addr_low;
2354     u32     wr_addr_high;
2355     u32     wr_data;
2356     u32     arm_data;
2357     u32     status;
2358 };
2359 
2360 /**
2361  * struct hl_sync_to_engine_map_entry - sync object id to engine mapping entry
2362  * @engine_type: type of the engine
2363  * @engine_id: id of the engine
2364  * @sync_id: id of the sync object
2365  */
2366 struct hl_sync_to_engine_map_entry {
2367     struct hlist_node       node;
2368     enum hl_sync_engine_type    engine_type;
2369     u32             engine_id;
2370     u32             sync_id;
2371 };
2372 
2373 /**
2374  * struct hl_sync_to_engine_map - maps sync object id to associated engine id
2375  * @tb: hash table containing the mapping, each element is of type
2376  *      struct hl_sync_to_engine_map_entry
2377  */
2378 struct hl_sync_to_engine_map {
2379     DECLARE_HASHTABLE(tb, SYNC_TO_ENGINE_HASH_TABLE_BITS);
2380 };
2381 
2382 /**
2383  * struct hl_state_dump_specs_funcs - virtual functions used by the state dump
2384  * @gen_sync_to_engine_map: generate a hash map from sync obj id to its engine
2385  * @print_single_monitor: format monitor data as string
2386  * @monitor_valid: return true if given monitor dump is valid
2387  * @print_fences_single_engine: format fences data as string
2388  */
2389 struct hl_state_dump_specs_funcs {
2390     int (*gen_sync_to_engine_map)(struct hl_device *hdev,
2391                 struct hl_sync_to_engine_map *map);
2392     int (*print_single_monitor)(char **buf, size_t *size, size_t *offset,
2393                     struct hl_device *hdev,
2394                     struct hl_mon_state_dump *mon);
2395     int (*monitor_valid)(struct hl_mon_state_dump *mon);
2396     int (*print_fences_single_engine)(struct hl_device *hdev,
2397                     u64 base_offset,
2398                     u64 status_base_offset,
2399                     enum hl_sync_engine_type engine_type,
2400                     u32 engine_id, char **buf,
2401                     size_t *size, size_t *offset);
2402 };
2403 
2404 /**
2405  * struct hl_state_dump_specs - defines ASIC known hw objects names
2406  * @so_id_to_str_tb: sync objects names index table
2407  * @monitor_id_to_str_tb: monitors names index table
2408  * @funcs: virtual functions used for state dump
2409  * @sync_namager_names: readable names for sync manager if available (ex: N_E)
2410  * @props: pointer to a per asic const props array required for state dump
2411  */
2412 struct hl_state_dump_specs {
2413     DECLARE_HASHTABLE(so_id_to_str_tb, OBJ_NAMES_HASH_TABLE_BITS);
2414     DECLARE_HASHTABLE(monitor_id_to_str_tb, OBJ_NAMES_HASH_TABLE_BITS);
2415     struct hl_state_dump_specs_funcs    funcs;
2416     const char * const          *sync_namager_names;
2417     s64                 *props;
2418 };
2419 
2420 
2421 /*
2422  * DEVICES
2423  */
2424 
2425 #define HL_STR_MAX  32
2426 
2427 #define HL_DEV_STS_MAX (HL_DEVICE_STATUS_LAST + 1)
2428 
2429 /* Theoretical limit only. A single host can only contain up to 4 or 8 PCIe
2430  * x16 cards. In extreme cases, there are hosts that can accommodate 16 cards.
2431  */
2432 #define HL_MAX_MINORS   256
2433 
2434 /*
2435  * Registers read & write functions.
2436  */
2437 
2438 u32 hl_rreg(struct hl_device *hdev, u32 reg);
2439 void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
2440 
2441 #define RREG32(reg) hdev->asic_funcs->rreg(hdev, (reg))
2442 #define WREG32(reg, v) hdev->asic_funcs->wreg(hdev, (reg), (v))
2443 #define DREG32(reg) pr_info("REGISTER: " #reg " : 0x%08X\n",    \
2444             hdev->asic_funcs->rreg(hdev, (reg)))
2445 
2446 #define WREG32_P(reg, val, mask)                \
2447     do {                            \
2448         u32 tmp_ = RREG32(reg);             \
2449         tmp_ &= (mask);                 \
2450         tmp_ |= ((val) & ~(mask));          \
2451         WREG32(reg, tmp_);              \
2452     } while (0)
2453 #define WREG32_AND(reg, and) WREG32_P(reg, 0, and)
2454 #define WREG32_OR(reg, or) WREG32_P(reg, or, ~(or))
2455 
2456 #define RMWREG32(reg, val, mask)                \
2457     do {                            \
2458         u32 tmp_ = RREG32(reg);             \
2459         tmp_ &= ~(mask);                \
2460         tmp_ |= ((val) << __ffs(mask));         \
2461         WREG32(reg, tmp_);              \
2462     } while (0)
2463 
2464 #define RREG32_MASK(reg, mask) ((RREG32(reg) & mask) >> __ffs(mask))
2465 
2466 #define REG_FIELD_SHIFT(reg, field) reg##_##field##_SHIFT
2467 #define REG_FIELD_MASK(reg, field) reg##_##field##_MASK
2468 #define WREG32_FIELD(reg, offset, field, val)   \
2469     WREG32(mm##reg + offset, (RREG32(mm##reg + offset) & \
2470                 ~REG_FIELD_MASK(reg, field)) | \
2471                 (val) << REG_FIELD_SHIFT(reg, field))
2472 
2473 /* Timeout should be longer when working with simulator but cap the
2474  * increased timeout to some maximum
2475  */
2476 #define hl_poll_timeout_common(hdev, addr, val, cond, sleep_us, timeout_us, elbi) \
2477 ({ \
2478     ktime_t __timeout; \
2479     u32 __elbi_read; \
2480     int __rc = 0; \
2481     if (hdev->pdev) \
2482         __timeout = ktime_add_us(ktime_get(), timeout_us); \
2483     else \
2484         __timeout = ktime_add_us(ktime_get(),\
2485                 min((u64)(timeout_us * 10), \
2486                     (u64) HL_SIM_MAX_TIMEOUT_US)); \
2487     might_sleep_if(sleep_us); \
2488     for (;;) { \
2489         if (elbi) { \
2490             __rc = hl_pci_elbi_read(hdev, addr, &__elbi_read); \
2491             if (__rc) \
2492                 break; \
2493             (val) = __elbi_read; \
2494         } else {\
2495             (val) = RREG32((u32)addr); \
2496         } \
2497         if (cond) \
2498             break; \
2499         if (timeout_us && ktime_compare(ktime_get(), __timeout) > 0) { \
2500             if (elbi) { \
2501                 __rc = hl_pci_elbi_read(hdev, addr, &__elbi_read); \
2502                 if (__rc) \
2503                     break; \
2504                 (val) = __elbi_read; \
2505             } else {\
2506                 (val) = RREG32((u32)addr); \
2507             } \
2508             break; \
2509         } \
2510         if (sleep_us) \
2511             usleep_range((sleep_us >> 2) + 1, sleep_us); \
2512     } \
2513     __rc ? __rc : ((cond) ? 0 : -ETIMEDOUT); \
2514 })
2515 
2516 #define hl_poll_timeout(hdev, addr, val, cond, sleep_us, timeout_us) \
2517         hl_poll_timeout_common(hdev, addr, val, cond, sleep_us, timeout_us, false)
2518 
2519 #define hl_poll_timeout_elbi(hdev, addr, val, cond, sleep_us, timeout_us) \
2520         hl_poll_timeout_common(hdev, addr, val, cond, sleep_us, timeout_us, true)
2521 
2522 /*
2523  * poll array of register addresses.
2524  * condition is satisfied if all registers values match the expected value.
2525  * once some register in the array satisfies the condition it will not be polled again,
2526  * this is done both for efficiency and due to some registers are "clear on read".
2527  * TODO: use read from PCI bar in other places in the code (SW-91406)
2528  */
2529 #define hl_poll_reg_array_timeout_common(hdev, addr_arr, arr_size, expected_val, sleep_us, \
2530                         timeout_us, elbi) \
2531 ({ \
2532     ktime_t __timeout; \
2533     u64 __elem_bitmask; \
2534     u32 __read_val; \
2535     u8 __arr_idx;   \
2536     int __rc = 0; \
2537     \
2538     if (hdev->pdev) \
2539         __timeout = ktime_add_us(ktime_get(), timeout_us); \
2540     else \
2541         __timeout = ktime_add_us(ktime_get(),\
2542                 min(((u64)timeout_us * 10), \
2543                     (u64) HL_SIM_MAX_TIMEOUT_US)); \
2544     \
2545     might_sleep_if(sleep_us); \
2546     if (arr_size >= 64) \
2547         __rc = -EINVAL; \
2548     else \
2549         __elem_bitmask = BIT_ULL(arr_size) - 1; \
2550     for (;;) { \
2551         if (__rc) \
2552             break; \
2553         for (__arr_idx = 0; __arr_idx < (arr_size); __arr_idx++) {  \
2554             if (!(__elem_bitmask & BIT_ULL(__arr_idx))) \
2555                 continue;   \
2556             if (elbi) { \
2557                 __rc = hl_pci_elbi_read(hdev, (addr_arr)[__arr_idx], &__read_val); \
2558                 if (__rc) \
2559                     break; \
2560             } else { \
2561                 __read_val = RREG32((u32)(addr_arr)[__arr_idx]); \
2562             } \
2563             if (__read_val == (expected_val))   \
2564                 __elem_bitmask &= ~BIT_ULL(__arr_idx);  \
2565         }   \
2566         if (__rc || (__elem_bitmask == 0)) \
2567             break; \
2568         if (timeout_us && ktime_compare(ktime_get(), __timeout) > 0) \
2569             break; \
2570         if (sleep_us) \
2571             usleep_range((sleep_us >> 2) + 1, sleep_us); \
2572     } \
2573     __rc ? __rc : ((__elem_bitmask == 0) ? 0 : -ETIMEDOUT); \
2574 })
2575 
2576 #define hl_poll_reg_array_timeout(hdev, addr_arr, arr_size, expected_val, sleep_us, \
2577                     timeout_us) \
2578     hl_poll_reg_array_timeout_common(hdev, addr_arr, arr_size, expected_val, sleep_us, \
2579                         timeout_us, false)
2580 
2581 #define hl_poll_reg_array_timeout_elbi(hdev, addr_arr, arr_size, expected_val, sleep_us, \
2582                     timeout_us) \
2583     hl_poll_reg_array_timeout_common(hdev, addr_arr, arr_size, expected_val, sleep_us, \
2584                         timeout_us, true)
2585 
2586 /*
2587  * address in this macro points always to a memory location in the
2588  * host's (server's) memory. That location is updated asynchronously
2589  * either by the direct access of the device or by another core.
2590  *
2591  * To work both in LE and BE architectures, we need to distinguish between the
2592  * two states (device or another core updates the memory location). Therefore,
2593  * if mem_written_by_device is true, the host memory being polled will be
2594  * updated directly by the device. If false, the host memory being polled will
2595  * be updated by host CPU. Required so host knows whether or not the memory
2596  * might need to be byte-swapped before returning value to caller.
2597  */
2598 #define hl_poll_timeout_memory(hdev, addr, val, cond, sleep_us, timeout_us, \
2599                 mem_written_by_device) \
2600 ({ \
2601     ktime_t __timeout; \
2602     if (hdev->pdev) \
2603         __timeout = ktime_add_us(ktime_get(), timeout_us); \
2604     else \
2605         __timeout = ktime_add_us(ktime_get(),\
2606                 min((u64)(timeout_us * 100), \
2607                     (u64) HL_SIM_MAX_TIMEOUT_US)); \
2608     might_sleep_if(sleep_us); \
2609     for (;;) { \
2610         /* Verify we read updates done by other cores or by device */ \
2611         mb(); \
2612         (val) = *((u32 *)(addr)); \
2613         if (mem_written_by_device) \
2614             (val) = le32_to_cpu(*(__le32 *) &(val)); \
2615         if (cond) \
2616             break; \
2617         if (timeout_us && ktime_compare(ktime_get(), __timeout) > 0) { \
2618             (val) = *((u32 *)(addr)); \
2619             if (mem_written_by_device) \
2620                 (val) = le32_to_cpu(*(__le32 *) &(val)); \
2621             break; \
2622         } \
2623         if (sleep_us) \
2624             usleep_range((sleep_us >> 2) + 1, sleep_us); \
2625     } \
2626     (cond) ? 0 : -ETIMEDOUT; \
2627 })
2628 
2629 #define HL_USR_MAPPED_BLK_INIT(blk, base, sz) \
2630 ({ \
2631     struct user_mapped_block *p = blk; \
2632 \
2633     p->address = base; \
2634     p->size = sz; \
2635 })
2636 
2637 #define HL_USR_INTR_STRUCT_INIT(usr_intr, hdev, intr_id, decoder) \
2638 ({ \
2639     usr_intr.hdev = hdev; \
2640     usr_intr.interrupt_id = intr_id; \
2641     usr_intr.is_decoder = decoder; \
2642     INIT_LIST_HEAD(&usr_intr.wait_list_head); \
2643     spin_lock_init(&usr_intr.wait_list_lock); \
2644 })
2645 
2646 struct hwmon_chip_info;
2647 
2648 /**
2649  * struct hl_device_reset_work - reset workqueue task wrapper.
2650  * @wq: work queue for device reset procedure.
2651  * @reset_work: reset work to be done.
2652  * @hdev: habanalabs device structure.
2653  * @flags: reset flags.
2654  */
2655 struct hl_device_reset_work {
2656     struct workqueue_struct     *wq;
2657     struct delayed_work     reset_work;
2658     struct hl_device        *hdev;
2659     u32             flags;
2660 };
2661 
2662 /**
2663  * struct hl_mmu_hr_pgt_priv - used for holding per-device mmu host-resident
2664  * page-table internal information.
2665  * @mmu_pgt_pool: pool of page tables used by a host-resident MMU for
2666  *                allocating hops.
2667  * @mmu_asid_hop0: per-ASID array of host-resident hop0 tables.
2668  */
2669 struct hl_mmu_hr_priv {
2670     struct gen_pool *mmu_pgt_pool;
2671     struct pgt_info *mmu_asid_hop0;
2672 };
2673 
2674 /**
2675  * struct hl_mmu_dr_pgt_priv - used for holding per-device mmu device-resident
2676  * page-table internal information.
2677  * @mmu_pgt_pool: pool of page tables used by MMU for allocating hops.
2678  * @mmu_shadow_hop0: shadow array of hop0 tables.
2679  */
2680 struct hl_mmu_dr_priv {
2681     struct gen_pool *mmu_pgt_pool;
2682     void *mmu_shadow_hop0;
2683 };
2684 
2685 /**
2686  * struct hl_mmu_priv - used for holding per-device mmu internal information.
2687  * @dr: information on the device-resident MMU, when exists.
2688  * @hr: information on the host-resident MMU, when exists.
2689  */
2690 struct hl_mmu_priv {
2691     struct hl_mmu_dr_priv dr;
2692     struct hl_mmu_hr_priv hr;
2693 };
2694 
2695 /**
2696  * struct hl_mmu_per_hop_info - A structure describing one TLB HOP and its entry
2697  *                that was created in order to translate a virtual address to a
2698  *                physical one.
2699  * @hop_addr: The address of the hop.
2700  * @hop_pte_addr: The address of the hop entry.
2701  * @hop_pte_val: The value in the hop entry.
2702  */
2703 struct hl_mmu_per_hop_info {
2704     u64 hop_addr;
2705     u64 hop_pte_addr;
2706     u64 hop_pte_val;
2707 };
2708 
2709 /**
2710  * struct hl_mmu_hop_info - A structure describing the TLB hops and their
2711  * hop-entries that were created in order to translate a virtual address to a
2712  * physical one.
2713  * @scrambled_vaddr: The value of the virtual address after scrambling. This
2714  *                   address replaces the original virtual-address when mapped
2715  *                   in the MMU tables.
2716  * @unscrambled_paddr: The un-scrambled physical address.
2717  * @hop_info: Array holding the per-hop information used for the translation.
2718  * @used_hops: The number of hops used for the translation.
2719  * @range_type: virtual address range type.
2720  */
2721 struct hl_mmu_hop_info {
2722     u64 scrambled_vaddr;
2723     u64 unscrambled_paddr;
2724     struct hl_mmu_per_hop_info hop_info[MMU_ARCH_6_HOPS];
2725     u32 used_hops;
2726     enum hl_va_range_type range_type;
2727 };
2728 
2729 /**
2730  * struct hl_hr_mmu_funcs - Device related host resident MMU functions.
2731  * @get_hop0_pgt_info: get page table info structure for HOP0.
2732  * @get_pgt_info: get page table info structure for HOP other than HOP0.
2733  * @add_pgt_info: add page table info structure to hash.
2734  * @get_tlb_mapping_params: get mapping parameters needed for getting TLB info for specific mapping.
2735  */
2736 struct hl_hr_mmu_funcs {
2737     struct pgt_info *(*get_hop0_pgt_info)(struct hl_ctx *ctx);
2738     struct pgt_info *(*get_pgt_info)(struct hl_ctx *ctx, u64 phys_hop_addr);
2739     void (*add_pgt_info)(struct hl_ctx *ctx, struct pgt_info *pgt_info, dma_addr_t phys_addr);
2740     int (*get_tlb_mapping_params)(struct hl_device *hdev, struct hl_mmu_properties **mmu_prop,
2741                                 struct hl_mmu_hop_info *hops,
2742                                 u64 virt_addr, bool *is_huge);
2743 };
2744 
2745 /**
2746  * struct hl_mmu_funcs - Device related MMU functions.
2747  * @init: initialize the MMU module.
2748  * @fini: release the MMU module.
2749  * @ctx_init: Initialize a context for using the MMU module.
2750  * @ctx_fini: disable a ctx from using the mmu module.
2751  * @map: maps a virtual address to physical address for a context.
2752  * @unmap: unmap a virtual address of a context.
2753  * @flush: flush all writes from all cores to reach device MMU.
2754  * @swap_out: marks all mapping of the given context as swapped out.
2755  * @swap_in: marks all mapping of the given context as swapped in.
2756  * @get_tlb_info: returns the list of hops and hop-entries used that were
2757  *                created in order to translate the giver virtual address to a
2758  *                physical one.
2759  * @hr_funcs: functions specific to host resident MMU.
2760  */
2761 struct hl_mmu_funcs {
2762     int (*init)(struct hl_device *hdev);
2763     void (*fini)(struct hl_device *hdev);
2764     int (*ctx_init)(struct hl_ctx *ctx);
2765     void (*ctx_fini)(struct hl_ctx *ctx);
2766     int (*map)(struct hl_ctx *ctx, u64 virt_addr, u64 phys_addr, u32 page_size,
2767                 bool is_dram_addr);
2768     int (*unmap)(struct hl_ctx *ctx, u64 virt_addr, bool is_dram_addr);
2769     void (*flush)(struct hl_ctx *ctx);
2770     void (*swap_out)(struct hl_ctx *ctx);
2771     void (*swap_in)(struct hl_ctx *ctx);
2772     int (*get_tlb_info)(struct hl_ctx *ctx, u64 virt_addr, struct hl_mmu_hop_info *hops);
2773     struct hl_hr_mmu_funcs hr_funcs;
2774 };
2775 
2776 /**
2777  * struct hl_prefetch_work - prefetch work structure handler
2778  * @pf_work: actual work struct.
2779  * @ctx: compute context.
2780  * @va: virtual address to pre-fetch.
2781  * @size: pre-fetch size.
2782  * @flags: operation flags.
2783  * @asid: ASID for maintenance operation.
2784  */
2785 struct hl_prefetch_work {
2786     struct work_struct  pf_work;
2787     struct hl_ctx       *ctx;
2788     u64         va;
2789     u64         size;
2790     u32         flags;
2791     u32         asid;
2792 };
2793 
2794 /*
2795  * number of user contexts allowed to call wait_for_multi_cs ioctl in
2796  * parallel
2797  */
2798 #define MULTI_CS_MAX_USER_CTX   2
2799 
2800 /**
2801  * struct multi_cs_completion - multi CS wait completion.
2802  * @completion: completion of any of the CS in the list
2803  * @lock: spinlock for the completion structure
2804  * @timestamp: timestamp for the multi-CS completion
2805  * @stream_master_qid_map: bitmap of all stream masters on which the multi-CS
2806  *                        is waiting
2807  * @used: 1 if in use, otherwise 0
2808  */
2809 struct multi_cs_completion {
2810     struct completion   completion;
2811     spinlock_t      lock;
2812     s64         timestamp;
2813     u32         stream_master_qid_map;
2814     u8          used;
2815 };
2816 
2817 /**
2818  * struct multi_cs_data - internal data for multi CS call
2819  * @ctx: pointer to the context structure
2820  * @fence_arr: array of fences of all CSs
2821  * @seq_arr: array of CS sequence numbers
2822  * @timeout_jiffies: timeout in jiffies for waiting for CS to complete
2823  * @timestamp: timestamp of first completed CS
2824  * @wait_status: wait for CS status
2825  * @completion_bitmap: bitmap of completed CSs (1- completed, otherwise 0)
2826  * @arr_len: fence_arr and seq_arr array length
2827  * @gone_cs: indication of gone CS (1- there was gone CS, otherwise 0)
2828  * @update_ts: update timestamp. 1- update the timestamp, otherwise 0.
2829  */
2830 struct multi_cs_data {
2831     struct hl_ctx   *ctx;
2832     struct hl_fence **fence_arr;
2833     u64     *seq_arr;
2834     s64     timeout_jiffies;
2835     s64     timestamp;
2836     long        wait_status;
2837     u32     completion_bitmap;
2838     u8      arr_len;
2839     u8      gone_cs;
2840     u8      update_ts;
2841 };
2842 
2843 /**
2844  * struct hl_clk_throttle_timestamp - current/last clock throttling timestamp
2845  * @start: timestamp taken when 'start' event is received in driver
2846  * @end: timestamp taken when 'end' event is received in driver
2847  */
2848 struct hl_clk_throttle_timestamp {
2849     ktime_t     start;
2850     ktime_t     end;
2851 };
2852 
2853 /**
2854  * struct hl_clk_throttle - keeps current/last clock throttling timestamps
2855  * @timestamp: timestamp taken by driver and firmware, index 0 refers to POWER
2856  *             index 1 refers to THERMAL
2857  * @lock: protects this structure as it can be accessed from both event queue
2858  *        context and info_ioctl context
2859  * @current_reason: bitmask represents the current clk throttling reasons
2860  * @aggregated_reason: bitmask represents aggregated clk throttling reasons since driver load
2861  */
2862 struct hl_clk_throttle {
2863     struct hl_clk_throttle_timestamp timestamp[HL_CLK_THROTTLE_TYPE_MAX];
2864     struct mutex    lock;
2865     u32     current_reason;
2866     u32     aggregated_reason;
2867 };
2868 
2869 /**
2870  * struct user_mapped_block - describes a hw block allowed to be mmapped by user
2871  * @address: physical HW block address
2872  * @size: allowed size for mmap
2873  */
2874 struct user_mapped_block {
2875     u32 address;
2876     u32 size;
2877 };
2878 
2879 /**
2880  * struct cs_timeout_info - info of last CS timeout occurred.
2881  * @timestamp: CS timeout timestamp.
2882  * @write_enable: if set writing to CS parameters in the structure is enabled. otherwise - disabled,
2883  *                so the first (root cause) CS timeout will not be overwritten.
2884  * @seq: CS timeout sequence number.
2885  */
2886 struct cs_timeout_info {
2887     ktime_t     timestamp;
2888     atomic_t    write_enable;
2889     u64     seq;
2890 };
2891 
2892 /**
2893  * struct razwi_info - info about last razwi error occurred.
2894  * @timestamp: razwi timestamp.
2895  * @write_enable: if set writing to razwi parameters in the structure is enabled.
2896  *                otherwise - disabled, so the first (root cause) razwi will not be overwritten.
2897  * @addr: address that caused razwi.
2898  * @engine_id_1: engine id of the razwi initiator, if it was initiated by engine that does
2899  *               not have engine id it will be set to U16_MAX.
2900  * @engine_id_2: second engine id of razwi initiator. Might happen that razwi have 2 possible
2901  *               engines which one them caused the razwi. In that case, it will contain the
2902  *               second possible engine id, otherwise it will be set to U16_MAX.
2903  * @non_engine_initiator: in case the initiator of the razwi does not have engine id.
2904  * @type: cause of razwi, page fault or access error, otherwise it will be set to U8_MAX.
2905  */
2906 struct razwi_info {
2907     ktime_t     timestamp;
2908     atomic_t    write_enable;
2909     u64     addr;
2910     u16     engine_id_1;
2911     u16     engine_id_2;
2912     u8      non_engine_initiator;
2913     u8      type;
2914 };
2915 
2916 #define MAX_QMAN_STREAMS_INFO       4
2917 #define OPCODE_INFO_MAX_ADDR_SIZE   8
2918 /**
2919  * struct undefined_opcode_info - info about last undefined opcode error
2920  * @timestamp: timestamp of the undefined opcode error
2921  * @cb_addr_streams: CB addresses (per stream) that are currently exists in the PQ
2922  *                   entiers. In case all streams array entries are
2923  *                   filled with values, it means the execution was in Lower-CP.
2924  * @cq_addr: the address of the current handled command buffer
2925  * @cq_size: the size of the current handled command buffer
2926  * @cb_addr_streams_len: num of streams - actual len of cb_addr_streams array.
2927  *                       should be equal to 1 incase of undefined opcode
2928  *                       in Upper-CP (specific stream) and equal to 4 incase
2929  *                       of undefined opcode in Lower-CP.
2930  * @engine_id: engine-id that the error occurred on
2931  * @stream_id: the stream id the error occurred on. In case the stream equals to
2932  *             MAX_QMAN_STREAMS_INFO it means the error occurred on a Lower-CP.
2933  * @write_enable: if set, writing to undefined opcode parameters in the structure
2934  *                 is enable so the first (root cause) undefined opcode will not be
2935  *                 overwritten.
2936  */
2937 struct undefined_opcode_info {
2938     ktime_t timestamp;
2939     u64 cb_addr_streams[MAX_QMAN_STREAMS_INFO][OPCODE_INFO_MAX_ADDR_SIZE];
2940     u64 cq_addr;
2941     u32 cq_size;
2942     u32 cb_addr_streams_len;
2943     u32 engine_id;
2944     u32 stream_id;
2945     bool write_enable;
2946 };
2947 
2948 /**
2949  * struct last_error_session_info - info about last session errors occurred.
2950  * @cs_timeout: CS timeout error last information.
2951  * @razwi: razwi last information.
2952  * @undef_opcode: undefined opcode information
2953  */
2954 struct last_error_session_info {
2955     struct cs_timeout_info      cs_timeout;
2956     struct razwi_info       razwi;
2957     struct undefined_opcode_info    undef_opcode;
2958 };
2959 
2960 /**
2961  * struct hl_reset_info - holds current device reset information.
2962  * @lock: lock to protect critical reset flows.
2963  * @compute_reset_cnt: number of compte resets since the driver was loaded.
2964  * @hard_reset_cnt: number of hard resets since the driver was loaded.
2965  * @hard_reset_schedule_flags: hard reset is scheduled to after current compute reset,
2966  *                             here we hold the hard reset flags.
2967  * @in_reset: is device in reset flow.
2968  * @in_compute_reset: Device is currently in reset but not in hard-reset.
2969  * @needs_reset: true if reset_on_lockup is false and device should be reset
2970  *               due to lockup.
2971  * @hard_reset_pending: is there a hard reset work pending.
2972  * @curr_reset_cause: saves an enumerated reset cause when a hard reset is
2973  *                    triggered, and cleared after it is shared with preboot.
2974  * @prev_reset_trigger: saves the previous trigger which caused a reset, overidden
2975  *                      with a new value on next reset
2976  * @reset_trigger_repeated: set if device reset is triggered more than once with
2977  *                          same cause.
2978  * @skip_reset_on_timeout: Skip device reset if CS has timed out, wait for it to
2979  *                         complete instead.
2980  */
2981 struct hl_reset_info {
2982     spinlock_t  lock;
2983     u32     compute_reset_cnt;
2984     u32     hard_reset_cnt;
2985     u32     hard_reset_schedule_flags;
2986     u8      in_reset;
2987     u8      in_compute_reset;
2988     u8      needs_reset;
2989     u8      hard_reset_pending;
2990 
2991     u8      curr_reset_cause;
2992     u8      prev_reset_trigger;
2993     u8      reset_trigger_repeated;
2994 
2995     u8      skip_reset_on_timeout;
2996 };
2997 
2998 /**
2999  * struct hl_device - habanalabs device structure.
3000  * @pdev: pointer to PCI device, can be NULL in case of simulator device.
3001  * @pcie_bar_phys: array of available PCIe bars physical addresses.
3002  *         (required only for PCI address match mode)
3003  * @pcie_bar: array of available PCIe bars virtual addresses.
3004  * @rmmio: configuration area address on SRAM.
3005  * @cdev: related char device.
3006  * @cdev_ctrl: char device for control operations only (INFO IOCTL)
3007  * @dev: related kernel basic device structure.
3008  * @dev_ctrl: related kernel device structure for the control device
3009  * @work_heartbeat: delayed work for CPU-CP is-alive check.
3010  * @device_reset_work: delayed work which performs hard reset
3011  * @asic_name: ASIC specific name.
3012  * @asic_type: ASIC specific type.
3013  * @completion_queue: array of hl_cq.
3014  * @user_interrupt: array of hl_user_interrupt. upon the corresponding user
3015  *                  interrupt, driver will monitor the list of fences
3016  *                  registered to this interrupt.
3017  * @common_user_cq_interrupt: common user CQ interrupt for all user CQ interrupts.
3018  *                         upon any user CQ interrupt, driver will monitor the
3019  *                         list of fences registered to this common structure.
3020  * @common_decoder_interrupt: common decoder interrupt for all user decoder interrupts.
3021  * @shadow_cs_queue: pointer to a shadow queue that holds pointers to
3022  *                   outstanding command submissions.
3023  * @cq_wq: work queues of completion queues for executing work in process
3024  *         context.
3025  * @eq_wq: work queue of event queue for executing work in process context.
3026  * @cs_cmplt_wq: work queue of CS completions for executing work in process
3027  *               context.
3028  * @ts_free_obj_wq: work queue for timestamp registration objects release.
3029  * @pf_wq: work queue for MMU pre-fetch operations.
3030  * @kernel_ctx: Kernel driver context structure.
3031  * @kernel_queues: array of hl_hw_queue.
3032  * @cs_mirror_list: CS mirror list for TDR.
3033  * @cs_mirror_lock: protects cs_mirror_list.
3034  * @kernel_mem_mgr: memory manager for memory buffers with lifespan of driver.
3035  * @event_queue: event queue for IRQ from CPU-CP.
3036  * @dma_pool: DMA pool for small allocations.
3037  * @cpu_accessible_dma_mem: Host <-> CPU-CP shared memory CPU address.
3038  * @cpu_accessible_dma_address: Host <-> CPU-CP shared memory DMA address.
3039  * @cpu_accessible_dma_pool: Host <-> CPU-CP shared memory pool.
3040  * @asid_bitmap: holds used/available ASIDs.
3041  * @asid_mutex: protects asid_bitmap.
3042  * @send_cpu_message_lock: enforces only one message in Host <-> CPU-CP queue.
3043  * @debug_lock: protects critical section of setting debug mode for device
3044  * @asic_prop: ASIC specific immutable properties.
3045  * @asic_funcs: ASIC specific functions.
3046  * @asic_specific: ASIC specific information to use only from ASIC files.
3047  * @vm: virtual memory manager for MMU.
3048  * @hwmon_dev: H/W monitor device.
3049  * @hl_chip_info: ASIC's sensors information.
3050  * @device_status_description: device status description.
3051  * @hl_debugfs: device's debugfs manager.
3052  * @cb_pool: list of preallocated CBs.
3053  * @cb_pool_lock: protects the CB pool.
3054  * @internal_cb_pool_virt_addr: internal command buffer pool virtual address.
3055  * @internal_cb_pool_dma_addr: internal command buffer pool dma address.
3056  * @internal_cb_pool: internal command buffer memory pool.
3057  * @internal_cb_va_base: internal cb pool mmu virtual address base
3058  * @fpriv_list: list of file private data structures. Each structure is created
3059  *              when a user opens the device
3060  * @fpriv_ctrl_list: list of file private data structures. Each structure is created
3061  *              when a user opens the control device
3062  * @fpriv_list_lock: protects the fpriv_list
3063  * @fpriv_ctrl_list_lock: protects the fpriv_ctrl_list
3064  * @aggregated_cs_counters: aggregated cs counters among all contexts
3065  * @mmu_priv: device-specific MMU data.
3066  * @mmu_func: device-related MMU functions.
3067  * @dec: list of decoder sw instance
3068  * @fw_loader: FW loader manager.
3069  * @pci_mem_region: array of memory regions in the PCI
3070  * @state_dump_specs: constants and dictionaries needed to dump system state.
3071  * @multi_cs_completion: array of multi-CS completion.
3072  * @clk_throttling: holds information about current/previous clock throttling events
3073  * @last_error: holds information about last session in which CS timeout or razwi error occurred.
3074  * @reset_info: holds current device reset information.
3075  * @stream_master_qid_arr: pointer to array with QIDs of master streams.
3076  * @fw_major_version: major version of current loaded preboot.
3077  * @fw_minor_version: minor version of current loaded preboot.
3078  * @dram_used_mem: current DRAM memory consumption.
3079  * @memory_scrub_val: the value to which the dram will be scrubbed to using cb scrub_device_dram
3080  * @timeout_jiffies: device CS timeout value.
3081  * @max_power: the max power of the device, as configured by the sysadmin. This
3082  *             value is saved so in case of hard-reset, the driver will restore
3083  *             this value and update the F/W after the re-initialization
3084  * @boot_error_status_mask: contains a mask of the device boot error status.
3085  *                          Each bit represents a different error, according to
3086  *                          the defines in hl_boot_if.h. If the bit is cleared,
3087  *                          the error will be ignored by the driver during
3088  *                          device initialization. Mainly used to debug and
3089  *                          workaround firmware bugs
3090  * @dram_pci_bar_start: start bus address of PCIe bar towards DRAM.
3091  * @last_successful_open_ktime: timestamp (ktime) of the last successful device open.
3092  * @last_successful_open_jif: timestamp (jiffies) of the last successful
3093  *                            device open.
3094  * @last_open_session_duration_jif: duration (jiffies) of the last device open
3095  *                                  session.
3096  * @open_counter: number of successful device open operations.
3097  * @fw_poll_interval_usec: FW status poll interval in usec.
3098  *                         used for CPU boot status
3099  * @fw_comms_poll_interval_usec: FW comms/protocol poll interval in usec.
3100  *                                  used for COMMs protocols cmds(COMMS_STS_*)
3101  * @dram_binning: contains mask of drams that is received from the f/w which indicates which
3102  *                drams are binned-out
3103  * @tpc_binning: contains mask of tpc engines that is received from the f/w which indicates which
3104  *               tpc engines are binned-out
3105  * @card_type: Various ASICs have several card types. This indicates the card
3106  *             type of the current device.
3107  * @major: habanalabs kernel driver major.
3108  * @high_pll: high PLL profile frequency.
3109  * @decoder_binning: contains mask of decoder engines that is received from the f/w which
3110  *                   indicates which decoder engines are binned-out
3111  * @edma_binning: contains mask of edma engines that is received from the f/w which
3112  *                   indicates which edma engines are binned-out
3113  * @id: device minor.
3114  * @id_control: minor of the control device
3115  * @cpu_pci_msb_addr: 50-bit extension bits for the device CPU's 40-bit
3116  *                    addresses.
3117  * @is_in_dram_scrub: true if dram scrub operation is on going.
3118  * @disabled: is device disabled.
3119  * @late_init_done: is late init stage was done during initialization.
3120  * @hwmon_initialized: is H/W monitor sensors was initialized.
3121  * @reset_on_lockup: true if a reset should be done in case of stuck CS, false
3122  *                   otherwise.
3123  * @dram_default_page_mapping: is DRAM default page mapping enabled.
3124  * @memory_scrub: true to perform device memory scrub in various locations,
3125  *                such as context-switch, context close, page free, etc.
3126  * @pmmu_huge_range: is a different virtual addresses range used for PMMU with
3127  *                   huge pages.
3128  * @init_done: is the initialization of the device done.
3129  * @device_cpu_disabled: is the device CPU disabled (due to timeouts)
3130  * @in_debug: whether the device is in a state where the profiling/tracing infrastructure
3131  *            can be used. This indication is needed because in some ASICs we need to do
3132  *            specific operations to enable that infrastructure.
3133  * @cdev_sysfs_created: were char devices and sysfs nodes created.
3134  * @stop_on_err: true if engines should stop on error.
3135  * @supports_sync_stream: is sync stream supported.
3136  * @sync_stream_queue_idx: helper index for sync stream queues initialization.
3137  * @collective_mon_idx: helper index for collective initialization
3138  * @supports_coresight: is CoreSight supported.
3139  * @supports_cb_mapping: is mapping a CB to the device's MMU supported.
3140  * @process_kill_trial_cnt: number of trials reset thread tried killing
3141  *                          user processes
3142  * @device_fini_pending: true if device_fini was called and might be
3143  *                       waiting for the reset thread to finish
3144  * @supports_staged_submission: true if staged submissions are supported
3145  * @device_cpu_is_halted: Flag to indicate whether the device CPU was already
3146  *                        halted. We can't halt it again because the COMMS
3147  *                        protocol will throw an error. Relevant only for
3148  *                        cases where Linux was not loaded to device CPU
3149  * @supports_wait_for_multi_cs: true if wait for multi CS is supported
3150  * @is_compute_ctx_active: Whether there is an active compute context executing.
3151  * @compute_ctx_in_release: true if the current compute context is being released.
3152  * @supports_mmu_prefetch: true if prefetch is supported, otherwise false.
3153  * @reset_upon_device_release: reset the device when the user closes the file descriptor of the
3154  *                             device.
3155  * @nic_ports_mask: Controls which NIC ports are enabled. Used only for testing.
3156  * @fw_components: Controls which f/w components to load to the device. There are multiple f/w
3157  *                 stages and sometimes we want to stop at a certain stage. Used only for testing.
3158  * @mmu_enable: Whether to enable or disable the device MMU(s). Used only for testing.
3159  * @cpu_queues_enable: Whether to enable queues communication vs. the f/w. Used only for testing.
3160  * @pldm: Whether we are running in Palladium environment. Used only for testing.
3161  * @hard_reset_on_fw_events: Whether to do device hard-reset when a fatal event is received from
3162  *                           the f/w. Used only for testing.
3163  * @bmc_enable: Whether we are running in a box with BMC. Used only for testing.
3164  * @reset_on_preboot_fail: Whether to reset the device if preboot f/w fails to load.
3165  *                         Used only for testing.
3166  * @heartbeat: Controls if we want to enable the heartbeat mechanism vs. the f/w, which verifies
3167  *             that the f/w is always alive. Used only for testing.
3168  */
3169 struct hl_device {
3170     struct pci_dev          *pdev;
3171     u64             pcie_bar_phys[HL_PCI_NUM_BARS];
3172     void __iomem            *pcie_bar[HL_PCI_NUM_BARS];
3173     void __iomem            *rmmio;
3174     struct cdev         cdev;
3175     struct cdev         cdev_ctrl;
3176     struct device           *dev;
3177     struct device           *dev_ctrl;
3178     struct delayed_work     work_heartbeat;
3179     struct hl_device_reset_work device_reset_work;
3180     char                asic_name[HL_STR_MAX];
3181     char                status[HL_DEV_STS_MAX][HL_STR_MAX];
3182     enum hl_asic_type       asic_type;
3183     struct hl_cq            *completion_queue;
3184     struct hl_user_interrupt    *user_interrupt;
3185     struct hl_user_interrupt    common_user_cq_interrupt;
3186     struct hl_user_interrupt    common_decoder_interrupt;
3187     struct hl_cs            **shadow_cs_queue;
3188     struct workqueue_struct     **cq_wq;
3189     struct workqueue_struct     *eq_wq;
3190     struct workqueue_struct     *cs_cmplt_wq;
3191     struct workqueue_struct     *ts_free_obj_wq;
3192     struct workqueue_struct     *pf_wq;
3193     struct hl_ctx           *kernel_ctx;
3194     struct hl_hw_queue      *kernel_queues;
3195     struct list_head        cs_mirror_list;
3196     spinlock_t          cs_mirror_lock;
3197     struct hl_mem_mgr       kernel_mem_mgr;
3198     struct hl_eq            event_queue;
3199     struct dma_pool         *dma_pool;
3200     void                *cpu_accessible_dma_mem;
3201     dma_addr_t          cpu_accessible_dma_address;
3202     struct gen_pool         *cpu_accessible_dma_pool;
3203     unsigned long           *asid_bitmap;
3204     struct mutex            asid_mutex;
3205     struct mutex            send_cpu_message_lock;
3206     struct mutex            debug_lock;
3207     struct asic_fixed_properties    asic_prop;
3208     const struct hl_asic_funcs  *asic_funcs;
3209     void                *asic_specific;
3210     struct hl_vm            vm;
3211     struct device           *hwmon_dev;
3212     struct hwmon_chip_info      *hl_chip_info;
3213 
3214     struct hl_dbg_device_entry  hl_debugfs;
3215 
3216     struct list_head        cb_pool;
3217     spinlock_t          cb_pool_lock;
3218 
3219     void                *internal_cb_pool_virt_addr;
3220     dma_addr_t          internal_cb_pool_dma_addr;
3221     struct gen_pool         *internal_cb_pool;
3222     u64             internal_cb_va_base;
3223 
3224     struct list_head        fpriv_list;
3225     struct list_head        fpriv_ctrl_list;
3226     struct mutex            fpriv_list_lock;
3227     struct mutex            fpriv_ctrl_list_lock;
3228 
3229     struct hl_cs_counters_atomic    aggregated_cs_counters;
3230 
3231     struct hl_mmu_priv      mmu_priv;
3232     struct hl_mmu_funcs     mmu_func[MMU_NUM_PGT_LOCATIONS];
3233 
3234     struct hl_dec           *dec;
3235 
3236     struct fw_load_mgr      fw_loader;
3237 
3238     struct pci_mem_region       pci_mem_region[PCI_REGION_NUMBER];
3239 
3240     struct hl_state_dump_specs  state_dump_specs;
3241 
3242     struct multi_cs_completion  multi_cs_completion[
3243                             MULTI_CS_MAX_USER_CTX];
3244     struct hl_clk_throttle      clk_throttling;
3245     struct last_error_session_info  last_error;
3246 
3247     struct hl_reset_info        reset_info;
3248 
3249     u32             *stream_master_qid_arr;
3250     u32             fw_major_version;
3251     u32             fw_minor_version;
3252     atomic64_t          dram_used_mem;
3253     u64             memory_scrub_val;
3254     u64             timeout_jiffies;
3255     u64             max_power;
3256     u64             boot_error_status_mask;
3257     u64             dram_pci_bar_start;
3258     u64             last_successful_open_jif;
3259     u64             last_open_session_duration_jif;
3260     u64             open_counter;
3261     u64             fw_poll_interval_usec;
3262     ktime_t             last_successful_open_ktime;
3263     u64             fw_comms_poll_interval_usec;
3264     u64             dram_binning;
3265     u64             tpc_binning;
3266 
3267     enum cpucp_card_types       card_type;
3268     u32             major;
3269     u32             high_pll;
3270     u32             decoder_binning;
3271     u32             edma_binning;
3272     u16             id;
3273     u16             id_control;
3274     u16             cpu_pci_msb_addr;
3275     u8              is_in_dram_scrub;
3276     u8              disabled;
3277     u8              late_init_done;
3278     u8              hwmon_initialized;
3279     u8              reset_on_lockup;
3280     u8              dram_default_page_mapping;
3281     u8              memory_scrub;
3282     u8              pmmu_huge_range;
3283     u8              init_done;
3284     u8              device_cpu_disabled;
3285     u8              in_debug;
3286     u8              cdev_sysfs_created;
3287     u8              stop_on_err;
3288     u8              supports_sync_stream;
3289     u8              sync_stream_queue_idx;
3290     u8              collective_mon_idx;
3291     u8              supports_coresight;
3292     u8              supports_cb_mapping;
3293     u8              process_kill_trial_cnt;
3294     u8              device_fini_pending;
3295     u8              supports_staged_submission;
3296     u8              device_cpu_is_halted;
3297     u8              supports_wait_for_multi_cs;
3298     u8              stream_master_qid_arr_size;
3299     u8              is_compute_ctx_active;
3300     u8              compute_ctx_in_release;
3301     u8              supports_mmu_prefetch;
3302     u8              reset_upon_device_release;
3303 
3304     /* Parameters for bring-up */
3305     u64             nic_ports_mask;
3306     u64             fw_components;
3307     u8              mmu_enable;
3308     u8              cpu_queues_enable;
3309     u8              pldm;
3310     u8              hard_reset_on_fw_events;
3311     u8              bmc_enable;
3312     u8              reset_on_preboot_fail;
3313     u8              heartbeat;
3314 };
3315 
3316 
3317 /**
3318  * struct hl_cs_encaps_sig_handle - encapsulated signals handle structure
3319  * @refcount: refcount used to protect removing this id when several
3320  *            wait cs are used to wait of the reserved encaps signals.
3321  * @hdev: pointer to habanalabs device structure.
3322  * @hw_sob: pointer to  H/W SOB used in the reservation.
3323  * @ctx: pointer to the user's context data structure
3324  * @cs_seq: staged cs sequence which contains encapsulated signals
3325  * @id: idr handler id to be used to fetch the handler info
3326  * @q_idx: stream queue index
3327  * @pre_sob_val: current SOB value before reservation
3328  * @count: signals number
3329  */
3330 struct hl_cs_encaps_sig_handle {
3331     struct kref refcount;
3332     struct hl_device *hdev;
3333     struct hl_hw_sob *hw_sob;
3334     struct hl_ctx *ctx;
3335     u64  cs_seq;
3336     u32  id;
3337     u32  q_idx;
3338     u32  pre_sob_val;
3339     u32  count;
3340 };
3341 
3342 /*
3343  * IOCTLs
3344  */
3345 
3346 /**
3347  * typedef hl_ioctl_t - typedef for ioctl function in the driver
3348  * @hpriv: pointer to the FD's private data, which contains state of
3349  *      user process
3350  * @data: pointer to the input/output arguments structure of the IOCTL
3351  *
3352  * Return: 0 for success, negative value for error
3353  */
3354 typedef int hl_ioctl_t(struct hl_fpriv *hpriv, void *data);
3355 
3356 /**
3357  * struct hl_ioctl_desc - describes an IOCTL entry of the driver.
3358  * @cmd: the IOCTL code as created by the kernel macros.
3359  * @func: pointer to the driver's function that should be called for this IOCTL.
3360  */
3361 struct hl_ioctl_desc {
3362     unsigned int cmd;
3363     hl_ioctl_t *func;
3364 };
3365 
3366 
3367 /*
3368  * Kernel module functions that can be accessed by entire module
3369  */
3370 
3371 /**
3372  * hl_get_sg_info() - get number of pages and the DMA address from SG list.
3373  * @sg: the SG list.
3374  * @dma_addr: pointer to DMA address to return.
3375  *
3376  * Calculate the number of consecutive pages described by the SG list. Take the
3377  * offset of the address in the first page, add to it the length and round it up
3378  * to the number of needed pages.
3379  */
3380 static inline u32 hl_get_sg_info(struct scatterlist *sg, dma_addr_t *dma_addr)
3381 {
3382     *dma_addr = sg_dma_address(sg);
3383 
3384     return ((((*dma_addr) & (PAGE_SIZE - 1)) + sg_dma_len(sg)) +
3385             (PAGE_SIZE - 1)) >> PAGE_SHIFT;
3386 }
3387 
3388 /**
3389  * hl_mem_area_inside_range() - Checks whether address+size are inside a range.
3390  * @address: The start address of the area we want to validate.
3391  * @size: The size in bytes of the area we want to validate.
3392  * @range_start_address: The start address of the valid range.
3393  * @range_end_address: The end address of the valid range.
3394  *
3395  * Return: true if the area is inside the valid range, false otherwise.
3396  */
3397 static inline bool hl_mem_area_inside_range(u64 address, u64 size,
3398                 u64 range_start_address, u64 range_end_address)
3399 {
3400     u64 end_address = address + size;
3401 
3402     if ((address >= range_start_address) &&
3403             (end_address <= range_end_address) &&
3404             (end_address > address))
3405         return true;
3406 
3407     return false;
3408 }
3409 
3410 /**
3411  * hl_mem_area_crosses_range() - Checks whether address+size crossing a range.
3412  * @address: The start address of the area we want to validate.
3413  * @size: The size in bytes of the area we want to validate.
3414  * @range_start_address: The start address of the valid range.
3415  * @range_end_address: The end address of the valid range.
3416  *
3417  * Return: true if the area overlaps part or all of the valid range,
3418  *      false otherwise.
3419  */
3420 static inline bool hl_mem_area_crosses_range(u64 address, u32 size,
3421                 u64 range_start_address, u64 range_end_address)
3422 {
3423     u64 end_address = address + size - 1;
3424 
3425     return ((address <= range_end_address) && (range_start_address <= end_address));
3426 }
3427 
3428 uint64_t hl_set_dram_bar_default(struct hl_device *hdev, u64 addr);
3429 void *hl_asic_dma_alloc_coherent(struct hl_device *hdev, size_t size, dma_addr_t *dma_handle,
3430                     gfp_t flag);
3431 void hl_asic_dma_free_coherent(struct hl_device *hdev, size_t size, void *cpu_addr,
3432                     dma_addr_t dma_handle);
3433 void *hl_cpu_accessible_dma_pool_alloc(struct hl_device *hdev, size_t size, dma_addr_t *dma_handle);
3434 void hl_cpu_accessible_dma_pool_free(struct hl_device *hdev, size_t size, void *vaddr);
3435 void *hl_asic_dma_pool_zalloc(struct hl_device *hdev, size_t size, gfp_t mem_flags,
3436                     dma_addr_t *dma_handle);
3437 void hl_asic_dma_pool_free(struct hl_device *hdev, void *vaddr, dma_addr_t dma_addr);
3438 int hl_dma_map_sgtable(struct hl_device *hdev, struct sg_table *sgt, enum dma_data_direction dir);
3439 void hl_dma_unmap_sgtable(struct hl_device *hdev, struct sg_table *sgt,
3440                 enum dma_data_direction dir);
3441 int hl_access_cfg_region(struct hl_device *hdev, u64 addr, u64 *val,
3442     enum debugfs_access_type acc_type);
3443 int hl_access_dev_mem(struct hl_device *hdev, enum pci_region region_type,
3444             u64 addr, u64 *val, enum debugfs_access_type acc_type);
3445 int hl_device_open(struct inode *inode, struct file *filp);
3446 int hl_device_open_ctrl(struct inode *inode, struct file *filp);
3447 bool hl_device_operational(struct hl_device *hdev,
3448         enum hl_device_status *status);
3449 enum hl_device_status hl_device_status(struct hl_device *hdev);
3450 int hl_device_set_debug_mode(struct hl_device *hdev, struct hl_ctx *ctx, bool enable);
3451 int hl_hw_queues_create(struct hl_device *hdev);
3452 void hl_hw_queues_destroy(struct hl_device *hdev);
3453 int hl_hw_queue_send_cb_no_cmpl(struct hl_device *hdev, u32 hw_queue_id,
3454         u32 cb_size, u64 cb_ptr);
3455 void hl_hw_queue_submit_bd(struct hl_device *hdev, struct hl_hw_queue *q,
3456         u32 ctl, u32 len, u64 ptr);
3457 int hl_hw_queue_schedule_cs(struct hl_cs *cs);
3458 u32 hl_hw_queue_add_ptr(u32 ptr, u16 val);
3459 void hl_hw_queue_inc_ci_kernel(struct hl_device *hdev, u32 hw_queue_id);
3460 void hl_hw_queue_update_ci(struct hl_cs *cs);
3461 void hl_hw_queue_reset(struct hl_device *hdev, bool hard_reset);
3462 
3463 #define hl_queue_inc_ptr(p)     hl_hw_queue_add_ptr(p, 1)
3464 #define hl_pi_2_offset(pi)      ((pi) & (HL_QUEUE_LENGTH - 1))
3465 
3466 int hl_cq_init(struct hl_device *hdev, struct hl_cq *q, u32 hw_queue_id);
3467 void hl_cq_fini(struct hl_device *hdev, struct hl_cq *q);
3468 int hl_eq_init(struct hl_device *hdev, struct hl_eq *q);
3469 void hl_eq_fini(struct hl_device *hdev, struct hl_eq *q);
3470 void hl_cq_reset(struct hl_device *hdev, struct hl_cq *q);
3471 void hl_eq_reset(struct hl_device *hdev, struct hl_eq *q);
3472 irqreturn_t hl_irq_handler_cq(int irq, void *arg);
3473 irqreturn_t hl_irq_handler_eq(int irq, void *arg);
3474 irqreturn_t hl_irq_handler_dec_abnrm(int irq, void *arg);
3475 irqreturn_t hl_irq_handler_user_interrupt(int irq, void *arg);
3476 irqreturn_t hl_irq_handler_default(int irq, void *arg);
3477 u32 hl_cq_inc_ptr(u32 ptr);
3478 
3479 int hl_asid_init(struct hl_device *hdev);
3480 void hl_asid_fini(struct hl_device *hdev);
3481 unsigned long hl_asid_alloc(struct hl_device *hdev);
3482 void hl_asid_free(struct hl_device *hdev, unsigned long asid);
3483 
3484 int hl_ctx_create(struct hl_device *hdev, struct hl_fpriv *hpriv);
3485 void hl_ctx_free(struct hl_device *hdev, struct hl_ctx *ctx);
3486 int hl_ctx_init(struct hl_device *hdev, struct hl_ctx *ctx, bool is_kernel_ctx);
3487 void hl_ctx_do_release(struct kref *ref);
3488 void hl_ctx_get(struct hl_ctx *ctx);
3489 int hl_ctx_put(struct hl_ctx *ctx);
3490 struct hl_ctx *hl_get_compute_ctx(struct hl_device *hdev);
3491 struct hl_fence *hl_ctx_get_fence(struct hl_ctx *ctx, u64 seq);
3492 int hl_ctx_get_fences(struct hl_ctx *ctx, u64 *seq_arr,
3493                 struct hl_fence **fence, u32 arr_len);
3494 void hl_ctx_mgr_init(struct hl_ctx_mgr *mgr);
3495 void hl_ctx_mgr_fini(struct hl_device *hdev, struct hl_ctx_mgr *mgr);
3496 
3497 int hl_device_init(struct hl_device *hdev, struct class *hclass);
3498 void hl_device_fini(struct hl_device *hdev);
3499 int hl_device_suspend(struct hl_device *hdev);
3500 int hl_device_resume(struct hl_device *hdev);
3501 int hl_device_reset(struct hl_device *hdev, u32 flags);
3502 void hl_hpriv_get(struct hl_fpriv *hpriv);
3503 int hl_hpriv_put(struct hl_fpriv *hpriv);
3504 int hl_device_utilization(struct hl_device *hdev, u32 *utilization);
3505 
3506 int hl_build_hwmon_channel_info(struct hl_device *hdev,
3507         struct cpucp_sensor *sensors_arr);
3508 
3509 void hl_notifier_event_send_all(struct hl_device *hdev, u64 event_mask);
3510 
3511 int hl_sysfs_init(struct hl_device *hdev);
3512 void hl_sysfs_fini(struct hl_device *hdev);
3513 
3514 int hl_hwmon_init(struct hl_device *hdev);
3515 void hl_hwmon_fini(struct hl_device *hdev);
3516 
3517 int hl_cb_create(struct hl_device *hdev, struct hl_mem_mgr *mmg,
3518             struct hl_ctx *ctx, u32 cb_size, bool internal_cb,
3519             bool map_cb, u64 *handle);
3520 int hl_cb_destroy(struct hl_mem_mgr *mmg, u64 cb_handle);
3521 int hl_hw_block_mmap(struct hl_fpriv *hpriv, struct vm_area_struct *vma);
3522 struct hl_cb *hl_cb_get(struct hl_mem_mgr *mmg, u64 handle);
3523 void hl_cb_put(struct hl_cb *cb);
3524 struct hl_cb *hl_cb_kernel_create(struct hl_device *hdev, u32 cb_size,
3525                     bool internal_cb);
3526 int hl_cb_pool_init(struct hl_device *hdev);
3527 int hl_cb_pool_fini(struct hl_device *hdev);
3528 int hl_cb_va_pool_init(struct hl_ctx *ctx);
3529 void hl_cb_va_pool_fini(struct hl_ctx *ctx);
3530 
3531 void hl_cs_rollback_all(struct hl_device *hdev, bool skip_wq_flush);
3532 struct hl_cs_job *hl_cs_allocate_job(struct hl_device *hdev,
3533         enum hl_queue_type queue_type, bool is_kernel_allocated_cb);
3534 void hl_sob_reset_error(struct kref *ref);
3535 int hl_gen_sob_mask(u16 sob_base, u8 sob_mask, u8 *mask);
3536 void hl_fence_put(struct hl_fence *fence);
3537 void hl_fences_put(struct hl_fence **fence, int len);
3538 void hl_fence_get(struct hl_fence *fence);
3539 void cs_get(struct hl_cs *cs);
3540 bool cs_needs_completion(struct hl_cs *cs);
3541 bool cs_needs_timeout(struct hl_cs *cs);
3542 bool is_staged_cs_last_exists(struct hl_device *hdev, struct hl_cs *cs);
3543 struct hl_cs *hl_staged_cs_find_first(struct hl_device *hdev, u64 cs_seq);
3544 void hl_multi_cs_completion_init(struct hl_device *hdev);
3545 
3546 void goya_set_asic_funcs(struct hl_device *hdev);
3547 void gaudi_set_asic_funcs(struct hl_device *hdev);
3548 void gaudi2_set_asic_funcs(struct hl_device *hdev);
3549 
3550 int hl_vm_ctx_init(struct hl_ctx *ctx);
3551 void hl_vm_ctx_fini(struct hl_ctx *ctx);
3552 
3553 int hl_vm_init(struct hl_device *hdev);
3554 void hl_vm_fini(struct hl_device *hdev);
3555 
3556 void hl_hw_block_mem_init(struct hl_ctx *ctx);
3557 void hl_hw_block_mem_fini(struct hl_ctx *ctx);
3558 
3559 u64 hl_reserve_va_block(struct hl_device *hdev, struct hl_ctx *ctx,
3560         enum hl_va_range_type type, u32 size, u32 alignment);
3561 int hl_unreserve_va_block(struct hl_device *hdev, struct hl_ctx *ctx,
3562         u64 start_addr, u64 size);
3563 int hl_pin_host_memory(struct hl_device *hdev, u64 addr, u64 size,
3564             struct hl_userptr *userptr);
3565 void hl_unpin_host_memory(struct hl_device *hdev, struct hl_userptr *userptr);
3566 void hl_userptr_delete_list(struct hl_device *hdev,
3567                 struct list_head *userptr_list);
3568 bool hl_userptr_is_pinned(struct hl_device *hdev, u64 addr, u32 size,
3569                 struct list_head *userptr_list,
3570                 struct hl_userptr **userptr);
3571 
3572 int hl_mmu_init(struct hl_device *hdev);
3573 void hl_mmu_fini(struct hl_device *hdev);
3574 int hl_mmu_ctx_init(struct hl_ctx *ctx);
3575 void hl_mmu_ctx_fini(struct hl_ctx *ctx);
3576 int hl_mmu_map_page(struct hl_ctx *ctx, u64 virt_addr, u64 phys_addr,
3577         u32 page_size, bool flush_pte);
3578 int hl_mmu_get_real_page_size(struct hl_device *hdev, struct hl_mmu_properties *mmu_prop,
3579                 u32 page_size, u32 *real_page_size, bool is_dram_addr);
3580 int hl_mmu_unmap_page(struct hl_ctx *ctx, u64 virt_addr, u32 page_size,
3581         bool flush_pte);
3582 int hl_mmu_map_contiguous(struct hl_ctx *ctx, u64 virt_addr,
3583                     u64 phys_addr, u32 size);
3584 int hl_mmu_unmap_contiguous(struct hl_ctx *ctx, u64 virt_addr, u32 size);
3585 int hl_mmu_invalidate_cache(struct hl_device *hdev, bool is_hard, u32 flags);
3586 int hl_mmu_invalidate_cache_range(struct hl_device *hdev, bool is_hard,
3587                     u32 flags, u32 asid, u64 va, u64 size);
3588 int hl_mmu_prefetch_cache_range(struct hl_ctx *ctx, u32 flags, u32 asid, u64 va, u64 size);
3589 u64 hl_mmu_get_next_hop_addr(struct hl_ctx *ctx, u64 curr_pte);
3590 u64 hl_mmu_get_hop_pte_phys_addr(struct hl_ctx *ctx, struct hl_mmu_properties *mmu_prop,
3591                     u8 hop_idx, u64 hop_addr, u64 virt_addr);
3592 void hl_mmu_hr_flush(struct hl_ctx *ctx);
3593 int hl_mmu_hr_init(struct hl_device *hdev, struct hl_mmu_hr_priv *hr_priv, u32 hop_table_size,
3594             u64 pgt_size);
3595 void hl_mmu_hr_fini(struct hl_device *hdev, struct hl_mmu_hr_priv *hr_priv, u32 hop_table_size);
3596 void hl_mmu_hr_free_hop_remove_pgt(struct pgt_info *pgt_info, struct hl_mmu_hr_priv *hr_priv,
3597                 u32 hop_table_size);
3598 u64 hl_mmu_hr_pte_phys_to_virt(struct hl_ctx *ctx, struct pgt_info *pgt, u64 phys_pte_addr,
3599                             u32 hop_table_size);
3600 void hl_mmu_hr_write_pte(struct hl_ctx *ctx, struct pgt_info *pgt_info, u64 phys_pte_addr,
3601                             u64 val, u32 hop_table_size);
3602 void hl_mmu_hr_clear_pte(struct hl_ctx *ctx, struct pgt_info *pgt_info, u64 phys_pte_addr,
3603                             u32 hop_table_size);
3604 int hl_mmu_hr_put_pte(struct hl_ctx *ctx, struct pgt_info *pgt_info, struct hl_mmu_hr_priv *hr_priv,
3605                             u32 hop_table_size);
3606 void hl_mmu_hr_get_pte(struct hl_ctx *ctx, struct hl_hr_mmu_funcs *hr_func, u64 phys_hop_addr);
3607 struct pgt_info *hl_mmu_hr_get_next_hop_pgt_info(struct hl_ctx *ctx,
3608                             struct hl_hr_mmu_funcs *hr_func,
3609                             u64 curr_pte);
3610 struct pgt_info *hl_mmu_hr_alloc_hop(struct hl_ctx *ctx, struct hl_mmu_hr_priv *hr_priv,
3611                             struct hl_hr_mmu_funcs *hr_func,
3612                             struct hl_mmu_properties *mmu_prop);
3613 struct pgt_info *hl_mmu_hr_get_alloc_next_hop(struct hl_ctx *ctx,
3614                             struct hl_mmu_hr_priv *hr_priv,
3615                             struct hl_hr_mmu_funcs *hr_func,
3616                             struct hl_mmu_properties *mmu_prop,
3617                             u64 curr_pte, bool *is_new_hop);
3618 int hl_mmu_hr_get_tlb_info(struct hl_ctx *ctx, u64 virt_addr, struct hl_mmu_hop_info *hops,
3619                             struct hl_hr_mmu_funcs *hr_func);
3620 void hl_mmu_swap_out(struct hl_ctx *ctx);
3621 void hl_mmu_swap_in(struct hl_ctx *ctx);
3622 int hl_mmu_if_set_funcs(struct hl_device *hdev);
3623 void hl_mmu_v1_set_funcs(struct hl_device *hdev, struct hl_mmu_funcs *mmu);
3624 void hl_mmu_v2_hr_set_funcs(struct hl_device *hdev, struct hl_mmu_funcs *mmu);
3625 int hl_mmu_va_to_pa(struct hl_ctx *ctx, u64 virt_addr, u64 *phys_addr);
3626 int hl_mmu_get_tlb_info(struct hl_ctx *ctx, u64 virt_addr,
3627             struct hl_mmu_hop_info *hops);
3628 u64 hl_mmu_scramble_addr(struct hl_device *hdev, u64 addr);
3629 u64 hl_mmu_descramble_addr(struct hl_device *hdev, u64 addr);
3630 bool hl_is_dram_va(struct hl_device *hdev, u64 virt_addr);
3631 
3632 int hl_fw_load_fw_to_device(struct hl_device *hdev, const char *fw_name,
3633                 void __iomem *dst, u32 src_offset, u32 size);
3634 int hl_fw_send_pci_access_msg(struct hl_device *hdev, u32 opcode, u64 value);
3635 int hl_fw_send_cpu_message(struct hl_device *hdev, u32 hw_queue_id, u32 *msg,
3636                 u16 len, u32 timeout, u64 *result);
3637 int hl_fw_unmask_irq(struct hl_device *hdev, u16 event_type);
3638 int hl_fw_unmask_irq_arr(struct hl_device *hdev, const u32 *irq_arr,
3639         size_t irq_arr_size);
3640 int hl_fw_test_cpu_queue(struct hl_device *hdev);
3641 void *hl_fw_cpu_accessible_dma_pool_alloc(struct hl_device *hdev, size_t size,
3642                         dma_addr_t *dma_handle);
3643 void hl_fw_cpu_accessible_dma_pool_free(struct hl_device *hdev, size_t size,
3644                     void *vaddr);
3645 int hl_fw_send_heartbeat(struct hl_device *hdev);
3646 int hl_fw_cpucp_info_get(struct hl_device *hdev,
3647                 u32 sts_boot_dev_sts0_reg,
3648                 u32 sts_boot_dev_sts1_reg, u32 boot_err0_reg,
3649                 u32 boot_err1_reg);
3650 int hl_fw_cpucp_handshake(struct hl_device *hdev,
3651                 u32 sts_boot_dev_sts0_reg,
3652                 u32 sts_boot_dev_sts1_reg, u32 boot_err0_reg,
3653                 u32 boot_err1_reg);
3654 int hl_fw_get_eeprom_data(struct hl_device *hdev, void *data, size_t max_size);
3655 int hl_fw_get_monitor_dump(struct hl_device *hdev, void *data);
3656 int hl_fw_cpucp_pci_counters_get(struct hl_device *hdev,
3657         struct hl_info_pci_counters *counters);
3658 int hl_fw_cpucp_total_energy_get(struct hl_device *hdev,
3659             u64 *total_energy);
3660 int get_used_pll_index(struct hl_device *hdev, u32 input_pll_index,
3661                         enum pll_index *pll_index);
3662 int hl_fw_cpucp_pll_info_get(struct hl_device *hdev, u32 pll_index,
3663         u16 *pll_freq_arr);
3664 int hl_fw_cpucp_power_get(struct hl_device *hdev, u64 *power);
3665 void hl_fw_ask_hard_reset_without_linux(struct hl_device *hdev);
3666 void hl_fw_ask_halt_machine_without_linux(struct hl_device *hdev);
3667 int hl_fw_init_cpu(struct hl_device *hdev);
3668 int hl_fw_read_preboot_status(struct hl_device *hdev);
3669 int hl_fw_dynamic_send_protocol_cmd(struct hl_device *hdev,
3670                 struct fw_load_mgr *fw_loader,
3671                 enum comms_cmd cmd, unsigned int size,
3672                 bool wait_ok, u32 timeout);
3673 int hl_fw_dram_replaced_row_get(struct hl_device *hdev,
3674                 struct cpucp_hbm_row_info *info);
3675 int hl_fw_dram_pending_row_get(struct hl_device *hdev, u32 *pend_rows_num);
3676 int hl_fw_cpucp_engine_core_asid_set(struct hl_device *hdev, u32 asid);
3677 int hl_pci_bars_map(struct hl_device *hdev, const char * const name[3],
3678             bool is_wc[3]);
3679 int hl_pci_elbi_read(struct hl_device *hdev, u64 addr, u32 *data);
3680 int hl_pci_iatu_write(struct hl_device *hdev, u32 addr, u32 data);
3681 int hl_pci_set_inbound_region(struct hl_device *hdev, u8 region,
3682         struct hl_inbound_pci_region *pci_region);
3683 int hl_pci_set_outbound_region(struct hl_device *hdev,
3684         struct hl_outbound_pci_region *pci_region);
3685 enum pci_region hl_get_pci_memory_region(struct hl_device *hdev, u64 addr);
3686 int hl_pci_init(struct hl_device *hdev);
3687 void hl_pci_fini(struct hl_device *hdev);
3688 
3689 long hl_fw_get_frequency(struct hl_device *hdev, u32 pll_index, bool curr);
3690 void hl_fw_set_frequency(struct hl_device *hdev, u32 pll_index, u64 freq);
3691 int hl_get_temperature(struct hl_device *hdev, int sensor_index, u32 attr, long *value);
3692 int hl_set_temperature(struct hl_device *hdev, int sensor_index, u32 attr, long value);
3693 int hl_get_voltage(struct hl_device *hdev, int sensor_index, u32 attr, long *value);
3694 int hl_get_current(struct hl_device *hdev, int sensor_index, u32 attr, long *value);
3695 int hl_get_fan_speed(struct hl_device *hdev, int sensor_index, u32 attr, long *value);
3696 int hl_get_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr, long *value);
3697 void hl_set_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr, long value);
3698 long hl_fw_get_max_power(struct hl_device *hdev);
3699 void hl_fw_set_max_power(struct hl_device *hdev);
3700 int hl_set_voltage(struct hl_device *hdev, int sensor_index, u32 attr, long value);
3701 int hl_set_current(struct hl_device *hdev, int sensor_index, u32 attr, long value);
3702 int hl_set_power(struct hl_device *hdev, int sensor_index, u32 attr, long value);
3703 int hl_get_power(struct hl_device *hdev, int sensor_index, u32 attr, long *value);
3704 int hl_fw_get_clk_rate(struct hl_device *hdev, u32 *cur_clk, u32 *max_clk);
3705 void hl_fw_set_pll_profile(struct hl_device *hdev);
3706 void hl_sysfs_add_dev_clk_attr(struct hl_device *hdev, struct attribute_group *dev_clk_attr_grp);
3707 void hl_sysfs_add_dev_vrm_attr(struct hl_device *hdev, struct attribute_group *dev_vrm_attr_grp);
3708 
3709 void hw_sob_get(struct hl_hw_sob *hw_sob);
3710 void hw_sob_put(struct hl_hw_sob *hw_sob);
3711 void hl_encaps_handle_do_release(struct kref *ref);
3712 void hl_hw_queue_encaps_sig_set_sob_info(struct hl_device *hdev,
3713             struct hl_cs *cs, struct hl_cs_job *job,
3714             struct hl_cs_compl *cs_cmpl);
3715 
3716 int hl_dec_init(struct hl_device *hdev);
3717 void hl_dec_fini(struct hl_device *hdev);
3718 void hl_dec_ctx_fini(struct hl_ctx *ctx);
3719 
3720 void hl_release_pending_user_interrupts(struct hl_device *hdev);
3721 int hl_cs_signal_sob_wraparound_handler(struct hl_device *hdev, u32 q_idx,
3722             struct hl_hw_sob **hw_sob, u32 count, bool encaps_sig);
3723 
3724 int hl_state_dump(struct hl_device *hdev);
3725 const char *hl_state_dump_get_sync_name(struct hl_device *hdev, u32 sync_id);
3726 const char *hl_state_dump_get_monitor_name(struct hl_device *hdev,
3727                     struct hl_mon_state_dump *mon);
3728 void hl_state_dump_free_sync_to_engine_map(struct hl_sync_to_engine_map *map);
3729 __printf(4, 5) int hl_snprintf_resize(char **buf, size_t *size, size_t *offset,
3730                     const char *format, ...);
3731 char *hl_format_as_binary(char *buf, size_t buf_len, u32 n);
3732 const char *hl_sync_engine_to_string(enum hl_sync_engine_type engine_type);
3733 
3734 void hl_mem_mgr_init(struct device *dev, struct hl_mem_mgr *mmg);
3735 void hl_mem_mgr_fini(struct hl_mem_mgr *mmg);
3736 int hl_mem_mgr_mmap(struct hl_mem_mgr *mmg, struct vm_area_struct *vma,
3737             void *args);
3738 struct hl_mmap_mem_buf *hl_mmap_mem_buf_get(struct hl_mem_mgr *mmg,
3739                            u64 handle);
3740 int hl_mmap_mem_buf_put_handle(struct hl_mem_mgr *mmg, u64 handle);
3741 int hl_mmap_mem_buf_put(struct hl_mmap_mem_buf *buf);
3742 struct hl_mmap_mem_buf *
3743 hl_mmap_mem_buf_alloc(struct hl_mem_mgr *mmg,
3744               struct hl_mmap_mem_buf_behavior *behavior, gfp_t gfp,
3745               void *args);
3746 
3747 #ifdef CONFIG_DEBUG_FS
3748 
3749 void hl_debugfs_init(void);
3750 void hl_debugfs_fini(void);
3751 void hl_debugfs_add_device(struct hl_device *hdev);
3752 void hl_debugfs_remove_device(struct hl_device *hdev);
3753 void hl_debugfs_add_file(struct hl_fpriv *hpriv);
3754 void hl_debugfs_remove_file(struct hl_fpriv *hpriv);
3755 void hl_debugfs_add_cb(struct hl_cb *cb);
3756 void hl_debugfs_remove_cb(struct hl_cb *cb);
3757 void hl_debugfs_add_cs(struct hl_cs *cs);
3758 void hl_debugfs_remove_cs(struct hl_cs *cs);
3759 void hl_debugfs_add_job(struct hl_device *hdev, struct hl_cs_job *job);
3760 void hl_debugfs_remove_job(struct hl_device *hdev, struct hl_cs_job *job);
3761 void hl_debugfs_add_userptr(struct hl_device *hdev, struct hl_userptr *userptr);
3762 void hl_debugfs_remove_userptr(struct hl_device *hdev,
3763                 struct hl_userptr *userptr);
3764 void hl_debugfs_add_ctx_mem_hash(struct hl_device *hdev, struct hl_ctx *ctx);
3765 void hl_debugfs_remove_ctx_mem_hash(struct hl_device *hdev, struct hl_ctx *ctx);
3766 void hl_debugfs_set_state_dump(struct hl_device *hdev, char *data,
3767                     unsigned long length);
3768 
3769 #else
3770 
3771 static inline void __init hl_debugfs_init(void)
3772 {
3773 }
3774 
3775 static inline void hl_debugfs_fini(void)
3776 {
3777 }
3778 
3779 static inline void hl_debugfs_add_device(struct hl_device *hdev)
3780 {
3781 }
3782 
3783 static inline void hl_debugfs_remove_device(struct hl_device *hdev)
3784 {
3785 }
3786 
3787 static inline void hl_debugfs_add_file(struct hl_fpriv *hpriv)
3788 {
3789 }
3790 
3791 static inline void hl_debugfs_remove_file(struct hl_fpriv *hpriv)
3792 {
3793 }
3794 
3795 static inline void hl_debugfs_add_cb(struct hl_cb *cb)
3796 {
3797 }
3798 
3799 static inline void hl_debugfs_remove_cb(struct hl_cb *cb)
3800 {
3801 }
3802 
3803 static inline void hl_debugfs_add_cs(struct hl_cs *cs)
3804 {
3805 }
3806 
3807 static inline void hl_debugfs_remove_cs(struct hl_cs *cs)
3808 {
3809 }
3810 
3811 static inline void hl_debugfs_add_job(struct hl_device *hdev,
3812                     struct hl_cs_job *job)
3813 {
3814 }
3815 
3816 static inline void hl_debugfs_remove_job(struct hl_device *hdev,
3817                     struct hl_cs_job *job)
3818 {
3819 }
3820 
3821 static inline void hl_debugfs_add_userptr(struct hl_device *hdev,
3822                     struct hl_userptr *userptr)
3823 {
3824 }
3825 
3826 static inline void hl_debugfs_remove_userptr(struct hl_device *hdev,
3827                     struct hl_userptr *userptr)
3828 {
3829 }
3830 
3831 static inline void hl_debugfs_add_ctx_mem_hash(struct hl_device *hdev,
3832                     struct hl_ctx *ctx)
3833 {
3834 }
3835 
3836 static inline void hl_debugfs_remove_ctx_mem_hash(struct hl_device *hdev,
3837                     struct hl_ctx *ctx)
3838 {
3839 }
3840 
3841 static inline void hl_debugfs_set_state_dump(struct hl_device *hdev,
3842                     char *data, unsigned long length)
3843 {
3844 }
3845 
3846 #endif
3847 
3848 /* Security */
3849 int hl_unsecure_register(struct hl_device *hdev, u32 mm_reg_addr, int offset,
3850         const u32 pb_blocks[], struct hl_block_glbl_sec sgs_array[],
3851         int array_size);
3852 int hl_unsecure_registers(struct hl_device *hdev, const u32 mm_reg_array[],
3853         int mm_array_size, int offset, const u32 pb_blocks[],
3854         struct hl_block_glbl_sec sgs_array[], int blocks_array_size);
3855 void hl_config_glbl_sec(struct hl_device *hdev, const u32 pb_blocks[],
3856         struct hl_block_glbl_sec sgs_array[], u32 block_offset,
3857         int array_size);
3858 void hl_secure_block(struct hl_device *hdev,
3859         struct hl_block_glbl_sec sgs_array[], int array_size);
3860 int hl_init_pb_with_mask(struct hl_device *hdev, u32 num_dcores,
3861         u32 dcore_offset, u32 num_instances, u32 instance_offset,
3862         const u32 pb_blocks[], u32 blocks_array_size,
3863         const u32 *regs_array, u32 regs_array_size, u64 mask);
3864 int hl_init_pb(struct hl_device *hdev, u32 num_dcores, u32 dcore_offset,
3865         u32 num_instances, u32 instance_offset,
3866         const u32 pb_blocks[], u32 blocks_array_size,
3867         const u32 *regs_array, u32 regs_array_size);
3868 int hl_init_pb_ranges_with_mask(struct hl_device *hdev, u32 num_dcores,
3869         u32 dcore_offset, u32 num_instances, u32 instance_offset,
3870         const u32 pb_blocks[], u32 blocks_array_size,
3871         const struct range *regs_range_array, u32 regs_range_array_size,
3872         u64 mask);
3873 int hl_init_pb_ranges(struct hl_device *hdev, u32 num_dcores,
3874         u32 dcore_offset, u32 num_instances, u32 instance_offset,
3875         const u32 pb_blocks[], u32 blocks_array_size,
3876         const struct range *regs_range_array,
3877         u32 regs_range_array_size);
3878 int hl_init_pb_single_dcore(struct hl_device *hdev, u32 dcore_offset,
3879         u32 num_instances, u32 instance_offset,
3880         const u32 pb_blocks[], u32 blocks_array_size,
3881         const u32 *regs_array, u32 regs_array_size);
3882 int hl_init_pb_ranges_single_dcore(struct hl_device *hdev, u32 dcore_offset,
3883         u32 num_instances, u32 instance_offset,
3884         const u32 pb_blocks[], u32 blocks_array_size,
3885         const struct range *regs_range_array,
3886         u32 regs_range_array_size);
3887 void hl_ack_pb(struct hl_device *hdev, u32 num_dcores, u32 dcore_offset,
3888         u32 num_instances, u32 instance_offset,
3889         const u32 pb_blocks[], u32 blocks_array_size);
3890 void hl_ack_pb_with_mask(struct hl_device *hdev, u32 num_dcores,
3891         u32 dcore_offset, u32 num_instances, u32 instance_offset,
3892         const u32 pb_blocks[], u32 blocks_array_size, u64 mask);
3893 void hl_ack_pb_single_dcore(struct hl_device *hdev, u32 dcore_offset,
3894         u32 num_instances, u32 instance_offset,
3895         const u32 pb_blocks[], u32 blocks_array_size);
3896 
3897 /* IOCTLs */
3898 long hl_ioctl(struct file *filep, unsigned int cmd, unsigned long arg);
3899 long hl_ioctl_control(struct file *filep, unsigned int cmd, unsigned long arg);
3900 int hl_cb_ioctl(struct hl_fpriv *hpriv, void *data);
3901 int hl_cs_ioctl(struct hl_fpriv *hpriv, void *data);
3902 int hl_wait_ioctl(struct hl_fpriv *hpriv, void *data);
3903 int hl_mem_ioctl(struct hl_fpriv *hpriv, void *data);
3904 
3905 #endif /* HABANALABSP_H_ */