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