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