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