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