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