6579f8767abdaccc6edee903449a44541b789815
[linux-2.6-microblaze.git] / drivers / misc / habanalabs / common / habanalabs.h
1 /* SPDX-License-Identifier: GPL-2.0
2  *
3  * Copyright 2016-2019 HabanaLabs, Ltd.
4  * All Rights Reserved.
5  *
6  */
7
8 #ifndef HABANALABSP_H_
9 #define HABANALABSP_H_
10
11 #include "../include/common/cpucp_if.h"
12 #include "../include/common/qman_if.h"
13 #include "../include/hw_ip/mmu/mmu_general.h"
14 #include <uapi/misc/habanalabs.h>
15
16 #include <linux/cdev.h>
17 #include <linux/iopoll.h>
18 #include <linux/irqreturn.h>
19 #include <linux/dma-direction.h>
20 #include <linux/scatterlist.h>
21 #include <linux/hashtable.h>
22 #include <linux/debugfs.h>
23 #include <linux/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  * @get_msi_info: Retrieve asic-specific MSI ID of the f/w async event
934  * @map_pll_idx_to_fw_idx: convert driver specific per asic PLL index to
935  *                         generic f/w compatible PLL Indexes
936  */
937 struct hl_asic_funcs {
938         int (*early_init)(struct hl_device *hdev);
939         int (*early_fini)(struct hl_device *hdev);
940         int (*late_init)(struct hl_device *hdev);
941         void (*late_fini)(struct hl_device *hdev);
942         int (*sw_init)(struct hl_device *hdev);
943         int (*sw_fini)(struct hl_device *hdev);
944         int (*hw_init)(struct hl_device *hdev);
945         void (*hw_fini)(struct hl_device *hdev, bool hard_reset);
946         void (*halt_engines)(struct hl_device *hdev, bool hard_reset);
947         int (*suspend)(struct hl_device *hdev);
948         int (*resume)(struct hl_device *hdev);
949         int (*cb_mmap)(struct hl_device *hdev, struct vm_area_struct *vma,
950                         void *cpu_addr, dma_addr_t dma_addr, size_t size);
951         void (*ring_doorbell)(struct hl_device *hdev, u32 hw_queue_id, u32 pi);
952         void (*pqe_write)(struct hl_device *hdev, __le64 *pqe,
953                         struct hl_bd *bd);
954         void* (*asic_dma_alloc_coherent)(struct hl_device *hdev, size_t size,
955                                         dma_addr_t *dma_handle, gfp_t flag);
956         void (*asic_dma_free_coherent)(struct hl_device *hdev, size_t size,
957                                         void *cpu_addr, dma_addr_t dma_handle);
958         int (*scrub_device_mem)(struct hl_device *hdev, u64 addr, u64 size);
959         void* (*get_int_queue_base)(struct hl_device *hdev, u32 queue_id,
960                                 dma_addr_t *dma_handle, u16 *queue_len);
961         int (*test_queues)(struct hl_device *hdev);
962         void* (*asic_dma_pool_zalloc)(struct hl_device *hdev, size_t size,
963                                 gfp_t mem_flags, dma_addr_t *dma_handle);
964         void (*asic_dma_pool_free)(struct hl_device *hdev, void *vaddr,
965                                 dma_addr_t dma_addr);
966         void* (*cpu_accessible_dma_pool_alloc)(struct hl_device *hdev,
967                                 size_t size, dma_addr_t *dma_handle);
968         void (*cpu_accessible_dma_pool_free)(struct hl_device *hdev,
969                                 size_t size, void *vaddr);
970         void (*hl_dma_unmap_sg)(struct hl_device *hdev,
971                                 struct scatterlist *sgl, int nents,
972                                 enum dma_data_direction dir);
973         int (*cs_parser)(struct hl_device *hdev, struct hl_cs_parser *parser);
974         int (*asic_dma_map_sg)(struct hl_device *hdev,
975                                 struct scatterlist *sgl, int nents,
976                                 enum dma_data_direction dir);
977         u32 (*get_dma_desc_list_size)(struct hl_device *hdev,
978                                         struct sg_table *sgt);
979         void (*add_end_of_cb_packets)(struct hl_device *hdev,
980                                         void *kernel_address, u32 len,
981                                         u64 cq_addr, u32 cq_val, u32 msix_num,
982                                         bool eb);
983         void (*update_eq_ci)(struct hl_device *hdev, u32 val);
984         int (*context_switch)(struct hl_device *hdev, u32 asid);
985         void (*restore_phase_topology)(struct hl_device *hdev);
986         int (*debugfs_read32)(struct hl_device *hdev, u64 addr,
987                                 bool user_address, u32 *val);
988         int (*debugfs_write32)(struct hl_device *hdev, u64 addr,
989                                 bool user_address, u32 val);
990         int (*debugfs_read64)(struct hl_device *hdev, u64 addr,
991                                 bool user_address, u64 *val);
992         int (*debugfs_write64)(struct hl_device *hdev, u64 addr,
993                                 bool user_address, u64 val);
994         int (*debugfs_read_dma)(struct hl_device *hdev, u64 addr, u32 size,
995                                 void *blob_addr);
996         void (*add_device_attr)(struct hl_device *hdev,
997                                 struct attribute_group *dev_attr_grp);
998         void (*handle_eqe)(struct hl_device *hdev,
999                                 struct hl_eq_entry *eq_entry);
1000         void (*set_pll_profile)(struct hl_device *hdev,
1001                         enum hl_pll_frequency freq);
1002         void* (*get_events_stat)(struct hl_device *hdev, bool aggregate,
1003                                 u32 *size);
1004         u64 (*read_pte)(struct hl_device *hdev, u64 addr);
1005         void (*write_pte)(struct hl_device *hdev, u64 addr, u64 val);
1006         int (*mmu_invalidate_cache)(struct hl_device *hdev, bool is_hard,
1007                                         u32 flags);
1008         int (*mmu_invalidate_cache_range)(struct hl_device *hdev, bool is_hard,
1009                         u32 asid, u64 va, u64 size);
1010         int (*send_heartbeat)(struct hl_device *hdev);
1011         void (*set_clock_gating)(struct hl_device *hdev);
1012         void (*disable_clock_gating)(struct hl_device *hdev);
1013         int (*debug_coresight)(struct hl_device *hdev, void *data);
1014         bool (*is_device_idle)(struct hl_device *hdev, u64 *mask_arr,
1015                                         u8 mask_len, struct seq_file *s);
1016         int (*soft_reset_late_init)(struct hl_device *hdev);
1017         void (*hw_queues_lock)(struct hl_device *hdev);
1018         void (*hw_queues_unlock)(struct hl_device *hdev);
1019         u32 (*get_pci_id)(struct hl_device *hdev);
1020         int (*get_eeprom_data)(struct hl_device *hdev, void *data,
1021                                 size_t max_size);
1022         int (*send_cpu_message)(struct hl_device *hdev, u32 *msg,
1023                                 u16 len, u32 timeout, u64 *result);
1024         int (*pci_bars_map)(struct hl_device *hdev);
1025         int (*init_iatu)(struct hl_device *hdev);
1026         u32 (*rreg)(struct hl_device *hdev, u32 reg);
1027         void (*wreg)(struct hl_device *hdev, u32 reg, u32 val);
1028         void (*halt_coresight)(struct hl_device *hdev);
1029         int (*ctx_init)(struct hl_ctx *ctx);
1030         void (*ctx_fini)(struct hl_ctx *ctx);
1031         int (*get_clk_rate)(struct hl_device *hdev, u32 *cur_clk, u32 *max_clk);
1032         u32 (*get_queue_id_for_cq)(struct hl_device *hdev, u32 cq_idx);
1033         int (*read_device_fw_version)(struct hl_device *hdev,
1034                                         enum hl_fw_component fwc);
1035         int (*load_firmware_to_device)(struct hl_device *hdev);
1036         int (*load_boot_fit_to_device)(struct hl_device *hdev);
1037         u32 (*get_signal_cb_size)(struct hl_device *hdev);
1038         u32 (*get_wait_cb_size)(struct hl_device *hdev);
1039         u32 (*gen_signal_cb)(struct hl_device *hdev, void *data, u16 sob_id,
1040                         u32 size, bool eb);
1041         u32 (*gen_wait_cb)(struct hl_device *hdev,
1042                         struct hl_gen_wait_properties *prop);
1043         void (*reset_sob)(struct hl_device *hdev, void *data);
1044         void (*reset_sob_group)(struct hl_device *hdev, u16 sob_group);
1045         void (*set_dma_mask_from_fw)(struct hl_device *hdev);
1046         u64 (*get_device_time)(struct hl_device *hdev);
1047         void (*collective_wait_init_cs)(struct hl_cs *cs);
1048         int (*collective_wait_create_jobs)(struct hl_device *hdev,
1049                         struct hl_ctx *ctx, struct hl_cs *cs, u32 wait_queue_id,
1050                         u32 collective_engine_id);
1051         u64 (*scramble_addr)(struct hl_device *hdev, u64 addr);
1052         u64 (*descramble_addr)(struct hl_device *hdev, u64 addr);
1053         void (*ack_protection_bits_errors)(struct hl_device *hdev);
1054         int (*get_hw_block_id)(struct hl_device *hdev, u64 block_addr,
1055                                 u32 *block_size, u32 *block_id);
1056         int (*hw_block_mmap)(struct hl_device *hdev, struct vm_area_struct *vma,
1057                         u32 block_id, u32 block_size);
1058         void (*enable_events_from_fw)(struct hl_device *hdev);
1059         void (*get_msi_info)(u32 *table);
1060         int (*map_pll_idx_to_fw_idx)(u32 pll_idx);
1061 };
1062
1063
1064 /*
1065  * CONTEXTS
1066  */
1067
1068 #define HL_KERNEL_ASID_ID       0
1069
1070 /**
1071  * enum hl_va_range_type - virtual address range type.
1072  * @HL_VA_RANGE_TYPE_HOST: range type of host pages
1073  * @HL_VA_RANGE_TYPE_HOST_HUGE: range type of host huge pages
1074  * @HL_VA_RANGE_TYPE_DRAM: range type of dram pages
1075  */
1076 enum hl_va_range_type {
1077         HL_VA_RANGE_TYPE_HOST,
1078         HL_VA_RANGE_TYPE_HOST_HUGE,
1079         HL_VA_RANGE_TYPE_DRAM,
1080         HL_VA_RANGE_TYPE_MAX
1081 };
1082
1083 /**
1084  * struct hl_va_range - virtual addresses range.
1085  * @lock: protects the virtual addresses list.
1086  * @list: list of virtual addresses blocks available for mappings.
1087  * @start_addr: range start address.
1088  * @end_addr: range end address.
1089  * @page_size: page size of this va range.
1090  */
1091 struct hl_va_range {
1092         struct mutex            lock;
1093         struct list_head        list;
1094         u64                     start_addr;
1095         u64                     end_addr;
1096         u32                     page_size;
1097 };
1098
1099 /**
1100  * struct hl_cs_counters_atomic - command submission counters
1101  * @out_of_mem_drop_cnt: dropped due to memory allocation issue
1102  * @parsing_drop_cnt: dropped due to error in packet parsing
1103  * @queue_full_drop_cnt: dropped due to queue full
1104  * @device_in_reset_drop_cnt: dropped due to device in reset
1105  * @max_cs_in_flight_drop_cnt: dropped due to maximum CS in-flight
1106  * @validation_drop_cnt: dropped due to error in validation
1107  */
1108 struct hl_cs_counters_atomic {
1109         atomic64_t out_of_mem_drop_cnt;
1110         atomic64_t parsing_drop_cnt;
1111         atomic64_t queue_full_drop_cnt;
1112         atomic64_t device_in_reset_drop_cnt;
1113         atomic64_t max_cs_in_flight_drop_cnt;
1114         atomic64_t validation_drop_cnt;
1115 };
1116
1117 /**
1118  * struct hl_pending_cb - pending command buffer structure
1119  * @cb_node: cb node in pending cb list
1120  * @cb: command buffer to send in next submission
1121  * @cb_size: command buffer size
1122  * @hw_queue_id: destination queue id
1123  */
1124 struct hl_pending_cb {
1125         struct list_head        cb_node;
1126         struct hl_cb            *cb;
1127         u32                     cb_size;
1128         u32                     hw_queue_id;
1129 };
1130
1131 /**
1132  * struct hl_ctx - user/kernel context.
1133  * @mem_hash: holds mapping from virtual address to virtual memory area
1134  *              descriptor (hl_vm_phys_pg_list or hl_userptr).
1135  * @mmu_shadow_hash: holds a mapping from shadow address to pgt_info structure.
1136  * @hpriv: pointer to the private (Kernel Driver) data of the process (fd).
1137  * @hdev: pointer to the device structure.
1138  * @refcount: reference counter for the context. Context is released only when
1139  *              this hits 0l. It is incremented on CS and CS_WAIT.
1140  * @cs_pending: array of hl fence objects representing pending CS.
1141  * @va_range: holds available virtual addresses for host and dram mappings.
1142  * @mem_hash_lock: protects the mem_hash.
1143  * @mmu_lock: protects the MMU page tables. Any change to the PGT, modifying the
1144  *            MMU hash or walking the PGT requires talking this lock.
1145  * @hw_block_list_lock: protects the HW block memory list.
1146  * @debugfs_list: node in debugfs list of contexts.
1147  * pending_cb_list: list of pending command buffers waiting to be sent upon
1148  *                  next user command submission context.
1149  * @hw_block_mem_list: list of HW block virtual mapped addresses.
1150  * @cs_counters: context command submission counters.
1151  * @cb_va_pool: device VA pool for command buffers which are mapped to the
1152  *              device's MMU.
1153  * @cs_sequence: sequence number for CS. Value is assigned to a CS and passed
1154  *                      to user so user could inquire about CS. It is used as
1155  *                      index to cs_pending array.
1156  * @dram_default_hops: array that holds all hops addresses needed for default
1157  *                     DRAM mapping.
1158  * @pending_cb_lock: spinlock to protect pending cb list
1159  * @cs_lock: spinlock to protect cs_sequence.
1160  * @dram_phys_mem: amount of used physical DRAM memory by this context.
1161  * @thread_ctx_switch_token: token to prevent multiple threads of the same
1162  *                              context from running the context switch phase.
1163  *                              Only a single thread should run it.
1164  * @thread_pending_cb_token: token to prevent multiple threads from processing
1165  *                              the pending CB list. Only a single thread should
1166  *                              process the list since it is protected by a
1167  *                              spinlock and we don't want to halt the entire
1168  *                              command submission sequence.
1169  * @thread_ctx_switch_wait_token: token to prevent the threads that didn't run
1170  *                              the context switch phase from moving to their
1171  *                              execution phase before the context switch phase
1172  *                              has finished.
1173  * @asid: context's unique address space ID in the device's MMU.
1174  * @handle: context's opaque handle for user
1175  */
1176 struct hl_ctx {
1177         DECLARE_HASHTABLE(mem_hash, MEM_HASH_TABLE_BITS);
1178         DECLARE_HASHTABLE(mmu_shadow_hash, MMU_HASH_TABLE_BITS);
1179         struct hl_fpriv                 *hpriv;
1180         struct hl_device                *hdev;
1181         struct kref                     refcount;
1182         struct hl_fence                 **cs_pending;
1183         struct hl_va_range              *va_range[HL_VA_RANGE_TYPE_MAX];
1184         struct mutex                    mem_hash_lock;
1185         struct mutex                    mmu_lock;
1186         struct mutex                    hw_block_list_lock;
1187         struct list_head                debugfs_list;
1188         struct list_head                pending_cb_list;
1189         struct list_head                hw_block_mem_list;
1190         struct hl_cs_counters_atomic    cs_counters;
1191         struct gen_pool                 *cb_va_pool;
1192         u64                             cs_sequence;
1193         u64                             *dram_default_hops;
1194         spinlock_t                      pending_cb_lock;
1195         spinlock_t                      cs_lock;
1196         atomic64_t                      dram_phys_mem;
1197         atomic_t                        thread_ctx_switch_token;
1198         atomic_t                        thread_pending_cb_token;
1199         u32                             thread_ctx_switch_wait_token;
1200         u32                             asid;
1201         u32                             handle;
1202 };
1203
1204 /**
1205  * struct hl_ctx_mgr - for handling multiple contexts.
1206  * @ctx_lock: protects ctx_handles.
1207  * @ctx_handles: idr to hold all ctx handles.
1208  */
1209 struct hl_ctx_mgr {
1210         struct mutex            ctx_lock;
1211         struct idr              ctx_handles;
1212 };
1213
1214
1215
1216 /*
1217  * COMMAND SUBMISSIONS
1218  */
1219
1220 /**
1221  * struct hl_userptr - memory mapping chunk information
1222  * @vm_type: type of the VM.
1223  * @job_node: linked-list node for hanging the object on the Job's list.
1224  * @pages: pointer to struct page array
1225  * @npages: size of @pages array
1226  * @sgt: pointer to the scatter-gather table that holds the pages.
1227  * @dir: for DMA unmapping, the direction must be supplied, so save it.
1228  * @debugfs_list: node in debugfs list of command submissions.
1229  * @addr: user-space virtual address of the start of the memory area.
1230  * @size: size of the memory area to pin & map.
1231  * @dma_mapped: true if the SG was mapped to DMA addresses, false otherwise.
1232  */
1233 struct hl_userptr {
1234         enum vm_type_t          vm_type; /* must be first */
1235         struct list_head        job_node;
1236         struct page             **pages;
1237         unsigned int            npages;
1238         struct sg_table         *sgt;
1239         enum dma_data_direction dir;
1240         struct list_head        debugfs_list;
1241         u64                     addr;
1242         u32                     size;
1243         u8                      dma_mapped;
1244 };
1245
1246 /**
1247  * struct hl_cs - command submission.
1248  * @jobs_in_queue_cnt: per each queue, maintain counter of submitted jobs.
1249  * @ctx: the context this CS belongs to.
1250  * @job_list: list of the CS's jobs in the various queues.
1251  * @job_lock: spinlock for the CS's jobs list. Needed for free_job.
1252  * @refcount: reference counter for usage of the CS.
1253  * @fence: pointer to the fence object of this CS.
1254  * @signal_fence: pointer to the fence object of the signal CS (used by wait
1255  *                CS only).
1256  * @finish_work: workqueue object to run when CS is completed by H/W.
1257  * @work_tdr: delayed work node for TDR.
1258  * @mirror_node : node in device mirror list of command submissions.
1259  * @staged_cs_node: node in the staged cs list.
1260  * @debugfs_list: node in debugfs list of command submissions.
1261  * @sequence: the sequence number of this CS.
1262  * @staged_sequence: the sequence of the staged submission this CS is part of,
1263  *                   relevant only if staged_cs is set.
1264  * @timeout_jiffies: cs timeout in jiffies.
1265  * @type: CS_TYPE_*.
1266  * @submitted: true if CS was submitted to H/W.
1267  * @completed: true if CS was completed by device.
1268  * @timedout : true if CS was timedout.
1269  * @tdr_active: true if TDR was activated for this CS (to prevent
1270  *              double TDR activation).
1271  * @aborted: true if CS was aborted due to some device error.
1272  * @timestamp: true if a timestmap must be captured upon completion.
1273  * @staged_last: true if this is the last staged CS and needs completion.
1274  * @staged_first: true if this is the first staged CS and we need to receive
1275  *                timeout for this CS.
1276  * @staged_cs: true if this CS is part of a staged submission.
1277  */
1278 struct hl_cs {
1279         u16                     *jobs_in_queue_cnt;
1280         struct hl_ctx           *ctx;
1281         struct list_head        job_list;
1282         spinlock_t              job_lock;
1283         struct kref             refcount;
1284         struct hl_fence         *fence;
1285         struct hl_fence         *signal_fence;
1286         struct work_struct      finish_work;
1287         struct delayed_work     work_tdr;
1288         struct list_head        mirror_node;
1289         struct list_head        staged_cs_node;
1290         struct list_head        debugfs_list;
1291         u64                     sequence;
1292         u64                     staged_sequence;
1293         u64                     timeout_jiffies;
1294         enum hl_cs_type         type;
1295         u8                      submitted;
1296         u8                      completed;
1297         u8                      timedout;
1298         u8                      tdr_active;
1299         u8                      aborted;
1300         u8                      timestamp;
1301         u8                      staged_last;
1302         u8                      staged_first;
1303         u8                      staged_cs;
1304 };
1305
1306 /**
1307  * struct hl_cs_job - command submission job.
1308  * @cs_node: the node to hang on the CS jobs list.
1309  * @cs: the CS this job belongs to.
1310  * @user_cb: the CB we got from the user.
1311  * @patched_cb: in case of patching, this is internal CB which is submitted on
1312  *              the queue instead of the CB we got from the IOCTL.
1313  * @finish_work: workqueue object to run when job is completed.
1314  * @userptr_list: linked-list of userptr mappings that belong to this job and
1315  *                      wait for completion.
1316  * @debugfs_list: node in debugfs list of command submission jobs.
1317  * @refcount: reference counter for usage of the CS job.
1318  * @queue_type: the type of the H/W queue this job is submitted to.
1319  * @id: the id of this job inside a CS.
1320  * @hw_queue_id: the id of the H/W queue this job is submitted to.
1321  * @user_cb_size: the actual size of the CB we got from the user.
1322  * @job_cb_size: the actual size of the CB that we put on the queue.
1323  * @is_kernel_allocated_cb: true if the CB handle we got from the user holds a
1324  *                          handle to a kernel-allocated CB object, false
1325  *                          otherwise (SRAM/DRAM/host address).
1326  * @contains_dma_pkt: whether the JOB contains at least one DMA packet. This
1327  *                    info is needed later, when adding the 2xMSG_PROT at the
1328  *                    end of the JOB, to know which barriers to put in the
1329  *                    MSG_PROT packets. Relevant only for GAUDI as GOYA doesn't
1330  *                    have streams so the engine can't be busy by another
1331  *                    stream.
1332  */
1333 struct hl_cs_job {
1334         struct list_head        cs_node;
1335         struct hl_cs            *cs;
1336         struct hl_cb            *user_cb;
1337         struct hl_cb            *patched_cb;
1338         struct work_struct      finish_work;
1339         struct list_head        userptr_list;
1340         struct list_head        debugfs_list;
1341         struct kref             refcount;
1342         enum hl_queue_type      queue_type;
1343         u32                     id;
1344         u32                     hw_queue_id;
1345         u32                     user_cb_size;
1346         u32                     job_cb_size;
1347         u8                      is_kernel_allocated_cb;
1348         u8                      contains_dma_pkt;
1349 };
1350
1351 /**
1352  * struct hl_cs_parser - command submission parser properties.
1353  * @user_cb: the CB we got from the user.
1354  * @patched_cb: in case of patching, this is internal CB which is submitted on
1355  *              the queue instead of the CB we got from the IOCTL.
1356  * @job_userptr_list: linked-list of userptr mappings that belong to the related
1357  *                      job and wait for completion.
1358  * @cs_sequence: the sequence number of the related CS.
1359  * @queue_type: the type of the H/W queue this job is submitted to.
1360  * @ctx_id: the ID of the context the related CS belongs to.
1361  * @hw_queue_id: the id of the H/W queue this job is submitted to.
1362  * @user_cb_size: the actual size of the CB we got from the user.
1363  * @patched_cb_size: the size of the CB after parsing.
1364  * @job_id: the id of the related job inside the related CS.
1365  * @is_kernel_allocated_cb: true if the CB handle we got from the user holds a
1366  *                          handle to a kernel-allocated CB object, false
1367  *                          otherwise (SRAM/DRAM/host address).
1368  * @contains_dma_pkt: whether the JOB contains at least one DMA packet. This
1369  *                    info is needed later, when adding the 2xMSG_PROT at the
1370  *                    end of the JOB, to know which barriers to put in the
1371  *                    MSG_PROT packets. Relevant only for GAUDI as GOYA doesn't
1372  *                    have streams so the engine can't be busy by another
1373  *                    stream.
1374  * @completion: true if we need completion for this CS.
1375  */
1376 struct hl_cs_parser {
1377         struct hl_cb            *user_cb;
1378         struct hl_cb            *patched_cb;
1379         struct list_head        *job_userptr_list;
1380         u64                     cs_sequence;
1381         enum hl_queue_type      queue_type;
1382         u32                     ctx_id;
1383         u32                     hw_queue_id;
1384         u32                     user_cb_size;
1385         u32                     patched_cb_size;
1386         u8                      job_id;
1387         u8                      is_kernel_allocated_cb;
1388         u8                      contains_dma_pkt;
1389         u8                      completion;
1390 };
1391
1392 /*
1393  * MEMORY STRUCTURE
1394  */
1395
1396 /**
1397  * struct hl_vm_hash_node - hash element from virtual address to virtual
1398  *                              memory area descriptor (hl_vm_phys_pg_list or
1399  *                              hl_userptr).
1400  * @node: node to hang on the hash table in context object.
1401  * @vaddr: key virtual address.
1402  * @ptr: value pointer (hl_vm_phys_pg_list or hl_userptr).
1403  */
1404 struct hl_vm_hash_node {
1405         struct hlist_node       node;
1406         u64                     vaddr;
1407         void                    *ptr;
1408 };
1409
1410 /**
1411  * struct hl_vm_hw_block_list_node - list element from user virtual address to
1412  *                              HW block id.
1413  * @node: node to hang on the list in context object.
1414  * @ctx: the context this node belongs to.
1415  * @vaddr: virtual address of the HW block.
1416  * @size: size of the block.
1417  * @id: HW block id (handle).
1418  */
1419 struct hl_vm_hw_block_list_node {
1420         struct list_head        node;
1421         struct hl_ctx           *ctx;
1422         unsigned long           vaddr;
1423         u32                     size;
1424         u32                     id;
1425 };
1426
1427 /**
1428  * struct hl_vm_phys_pg_pack - physical page pack.
1429  * @vm_type: describes the type of the virtual area descriptor.
1430  * @pages: the physical page array.
1431  * @npages: num physical pages in the pack.
1432  * @total_size: total size of all the pages in this list.
1433  * @mapping_cnt: number of shared mappings.
1434  * @asid: the context related to this list.
1435  * @page_size: size of each page in the pack.
1436  * @flags: HL_MEM_* flags related to this list.
1437  * @handle: the provided handle related to this list.
1438  * @offset: offset from the first page.
1439  * @contiguous: is contiguous physical memory.
1440  * @created_from_userptr: is product of host virtual address.
1441  */
1442 struct hl_vm_phys_pg_pack {
1443         enum vm_type_t          vm_type; /* must be first */
1444         u64                     *pages;
1445         u64                     npages;
1446         u64                     total_size;
1447         atomic_t                mapping_cnt;
1448         u32                     asid;
1449         u32                     page_size;
1450         u32                     flags;
1451         u32                     handle;
1452         u32                     offset;
1453         u8                      contiguous;
1454         u8                      created_from_userptr;
1455 };
1456
1457 /**
1458  * struct hl_vm_va_block - virtual range block information.
1459  * @node: node to hang on the virtual range list in context object.
1460  * @start: virtual range start address.
1461  * @end: virtual range end address.
1462  * @size: virtual range size.
1463  */
1464 struct hl_vm_va_block {
1465         struct list_head        node;
1466         u64                     start;
1467         u64                     end;
1468         u64                     size;
1469 };
1470
1471 /**
1472  * struct hl_vm - virtual memory manager for MMU.
1473  * @dram_pg_pool: pool for DRAM physical pages of 2MB.
1474  * @dram_pg_pool_refcount: reference counter for the pool usage.
1475  * @idr_lock: protects the phys_pg_list_handles.
1476  * @phys_pg_pack_handles: idr to hold all device allocations handles.
1477  * @init_done: whether initialization was done. We need this because VM
1478  *              initialization might be skipped during device initialization.
1479  */
1480 struct hl_vm {
1481         struct gen_pool         *dram_pg_pool;
1482         struct kref             dram_pg_pool_refcount;
1483         spinlock_t              idr_lock;
1484         struct idr              phys_pg_pack_handles;
1485         u8                      init_done;
1486 };
1487
1488
1489 /*
1490  * DEBUG, PROFILING STRUCTURE
1491  */
1492
1493 /**
1494  * struct hl_debug_params - Coresight debug parameters.
1495  * @input: pointer to component specific input parameters.
1496  * @output: pointer to component specific output parameters.
1497  * @output_size: size of output buffer.
1498  * @reg_idx: relevant register ID.
1499  * @op: component operation to execute.
1500  * @enable: true if to enable component debugging, false otherwise.
1501  */
1502 struct hl_debug_params {
1503         void *input;
1504         void *output;
1505         u32 output_size;
1506         u32 reg_idx;
1507         u32 op;
1508         bool enable;
1509 };
1510
1511 /*
1512  * FILE PRIVATE STRUCTURE
1513  */
1514
1515 /**
1516  * struct hl_fpriv - process information stored in FD private data.
1517  * @hdev: habanalabs device structure.
1518  * @filp: pointer to the given file structure.
1519  * @taskpid: current process ID.
1520  * @ctx: current executing context. TODO: remove for multiple ctx per process
1521  * @ctx_mgr: context manager to handle multiple context for this FD.
1522  * @cb_mgr: command buffer manager to handle multiple buffers for this FD.
1523  * @debugfs_list: list of relevant ASIC debugfs.
1524  * @dev_node: node in the device list of file private data
1525  * @refcount: number of related contexts.
1526  * @restore_phase_mutex: lock for context switch and restore phase.
1527  * @is_control: true for control device, false otherwise
1528  */
1529 struct hl_fpriv {
1530         struct hl_device        *hdev;
1531         struct file             *filp;
1532         struct pid              *taskpid;
1533         struct hl_ctx           *ctx;
1534         struct hl_ctx_mgr       ctx_mgr;
1535         struct hl_cb_mgr        cb_mgr;
1536         struct list_head        debugfs_list;
1537         struct list_head        dev_node;
1538         struct kref             refcount;
1539         struct mutex            restore_phase_mutex;
1540         u8                      is_control;
1541 };
1542
1543
1544 /*
1545  * DebugFS
1546  */
1547
1548 /**
1549  * struct hl_info_list - debugfs file ops.
1550  * @name: file name.
1551  * @show: function to output information.
1552  * @write: function to write to the file.
1553  */
1554 struct hl_info_list {
1555         const char      *name;
1556         int             (*show)(struct seq_file *s, void *data);
1557         ssize_t         (*write)(struct file *file, const char __user *buf,
1558                                 size_t count, loff_t *f_pos);
1559 };
1560
1561 /**
1562  * struct hl_debugfs_entry - debugfs dentry wrapper.
1563  * @info_ent: dentry realted ops.
1564  * @dev_entry: ASIC specific debugfs manager.
1565  */
1566 struct hl_debugfs_entry {
1567         const struct hl_info_list       *info_ent;
1568         struct hl_dbg_device_entry      *dev_entry;
1569 };
1570
1571 /**
1572  * struct hl_dbg_device_entry - ASIC specific debugfs manager.
1573  * @root: root dentry.
1574  * @hdev: habanalabs device structure.
1575  * @entry_arr: array of available hl_debugfs_entry.
1576  * @file_list: list of available debugfs files.
1577  * @file_mutex: protects file_list.
1578  * @cb_list: list of available CBs.
1579  * @cb_spinlock: protects cb_list.
1580  * @cs_list: list of available CSs.
1581  * @cs_spinlock: protects cs_list.
1582  * @cs_job_list: list of available CB jobs.
1583  * @cs_job_spinlock: protects cs_job_list.
1584  * @userptr_list: list of available userptrs (virtual memory chunk descriptor).
1585  * @userptr_spinlock: protects userptr_list.
1586  * @ctx_mem_hash_list: list of available contexts with MMU mappings.
1587  * @ctx_mem_hash_spinlock: protects cb_list.
1588  * @blob_desc: descriptor of blob
1589  * @addr: next address to read/write from/to in read/write32.
1590  * @mmu_addr: next virtual address to translate to physical address in mmu_show.
1591  * @mmu_asid: ASID to use while translating in mmu_show.
1592  * @i2c_bus: generic u8 debugfs file for bus value to use in i2c_data_read.
1593  * @i2c_addr: generic u8 debugfs file for address value to use in i2c_data_read.
1594  * @i2c_reg: generic u8 debugfs file for register value to use in i2c_data_read.
1595  */
1596 struct hl_dbg_device_entry {
1597         struct dentry                   *root;
1598         struct hl_device                *hdev;
1599         struct hl_debugfs_entry         *entry_arr;
1600         struct list_head                file_list;
1601         struct mutex                    file_mutex;
1602         struct list_head                cb_list;
1603         spinlock_t                      cb_spinlock;
1604         struct list_head                cs_list;
1605         spinlock_t                      cs_spinlock;
1606         struct list_head                cs_job_list;
1607         spinlock_t                      cs_job_spinlock;
1608         struct list_head                userptr_list;
1609         spinlock_t                      userptr_spinlock;
1610         struct list_head                ctx_mem_hash_list;
1611         spinlock_t                      ctx_mem_hash_spinlock;
1612         struct debugfs_blob_wrapper     blob_desc;
1613         u64                             addr;
1614         u64                             mmu_addr;
1615         u32                             mmu_asid;
1616         u8                              i2c_bus;
1617         u8                              i2c_addr;
1618         u8                              i2c_reg;
1619 };
1620
1621
1622 /*
1623  * DEVICES
1624  */
1625
1626 #define HL_STR_MAX      32
1627
1628 #define HL_DEV_STS_MAX (HL_DEVICE_STATUS_NEEDS_RESET + 1)
1629
1630 /* Theoretical limit only. A single host can only contain up to 4 or 8 PCIe
1631  * x16 cards. In extreme cases, there are hosts that can accommodate 16 cards.
1632  */
1633 #define HL_MAX_MINORS   256
1634
1635 /*
1636  * Registers read & write functions.
1637  */
1638
1639 u32 hl_rreg(struct hl_device *hdev, u32 reg);
1640 void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
1641
1642 #define RREG32(reg) hdev->asic_funcs->rreg(hdev, (reg))
1643 #define WREG32(reg, v) hdev->asic_funcs->wreg(hdev, (reg), (v))
1644 #define DREG32(reg) pr_info("REGISTER: " #reg " : 0x%08X\n",    \
1645                         hdev->asic_funcs->rreg(hdev, (reg)))
1646
1647 #define WREG32_P(reg, val, mask)                                \
1648         do {                                                    \
1649                 u32 tmp_ = RREG32(reg);                         \
1650                 tmp_ &= (mask);                                 \
1651                 tmp_ |= ((val) & ~(mask));                      \
1652                 WREG32(reg, tmp_);                              \
1653         } while (0)
1654 #define WREG32_AND(reg, and) WREG32_P(reg, 0, and)
1655 #define WREG32_OR(reg, or) WREG32_P(reg, or, ~(or))
1656
1657 #define RMWREG32(reg, val, mask)                                \
1658         do {                                                    \
1659                 u32 tmp_ = RREG32(reg);                         \
1660                 tmp_ &= ~(mask);                                \
1661                 tmp_ |= ((val) << __ffs(mask));                 \
1662                 WREG32(reg, tmp_);                              \
1663         } while (0)
1664
1665 #define RREG32_MASK(reg, mask) ((RREG32(reg) & mask) >> __ffs(mask))
1666
1667 #define REG_FIELD_SHIFT(reg, field) reg##_##field##_SHIFT
1668 #define REG_FIELD_MASK(reg, field) reg##_##field##_MASK
1669 #define WREG32_FIELD(reg, offset, field, val)   \
1670         WREG32(mm##reg + offset, (RREG32(mm##reg + offset) & \
1671                                 ~REG_FIELD_MASK(reg, field)) | \
1672                                 (val) << REG_FIELD_SHIFT(reg, field))
1673
1674 /* Timeout should be longer when working with simulator but cap the
1675  * increased timeout to some maximum
1676  */
1677 #define hl_poll_timeout(hdev, addr, val, cond, sleep_us, timeout_us) \
1678 ({ \
1679         ktime_t __timeout; \
1680         if (hdev->pdev) \
1681                 __timeout = ktime_add_us(ktime_get(), timeout_us); \
1682         else \
1683                 __timeout = ktime_add_us(ktime_get(),\
1684                                 min((u64)(timeout_us * 10), \
1685                                         (u64) HL_SIM_MAX_TIMEOUT_US)); \
1686         might_sleep_if(sleep_us); \
1687         for (;;) { \
1688                 (val) = RREG32(addr); \
1689                 if (cond) \
1690                         break; \
1691                 if (timeout_us && ktime_compare(ktime_get(), __timeout) > 0) { \
1692                         (val) = RREG32(addr); \
1693                         break; \
1694                 } \
1695                 if (sleep_us) \
1696                         usleep_range((sleep_us >> 2) + 1, sleep_us); \
1697         } \
1698         (cond) ? 0 : -ETIMEDOUT; \
1699 })
1700
1701 /*
1702  * address in this macro points always to a memory location in the
1703  * host's (server's) memory. That location is updated asynchronously
1704  * either by the direct access of the device or by another core.
1705  *
1706  * To work both in LE and BE architectures, we need to distinguish between the
1707  * two states (device or another core updates the memory location). Therefore,
1708  * if mem_written_by_device is true, the host memory being polled will be
1709  * updated directly by the device. If false, the host memory being polled will
1710  * be updated by host CPU. Required so host knows whether or not the memory
1711  * might need to be byte-swapped before returning value to caller.
1712  */
1713 #define hl_poll_timeout_memory(hdev, addr, val, cond, sleep_us, timeout_us, \
1714                                 mem_written_by_device) \
1715 ({ \
1716         ktime_t __timeout; \
1717         if (hdev->pdev) \
1718                 __timeout = ktime_add_us(ktime_get(), timeout_us); \
1719         else \
1720                 __timeout = ktime_add_us(ktime_get(),\
1721                                 min((u64)(timeout_us * 10), \
1722                                         (u64) HL_SIM_MAX_TIMEOUT_US)); \
1723         might_sleep_if(sleep_us); \
1724         for (;;) { \
1725                 /* Verify we read updates done by other cores or by device */ \
1726                 mb(); \
1727                 (val) = *((u32 *)(addr)); \
1728                 if (mem_written_by_device) \
1729                         (val) = le32_to_cpu(*(__le32 *) &(val)); \
1730                 if (cond) \
1731                         break; \
1732                 if (timeout_us && ktime_compare(ktime_get(), __timeout) > 0) { \
1733                         (val) = *((u32 *)(addr)); \
1734                         if (mem_written_by_device) \
1735                                 (val) = le32_to_cpu(*(__le32 *) &(val)); \
1736                         break; \
1737                 } \
1738                 if (sleep_us) \
1739                         usleep_range((sleep_us >> 2) + 1, sleep_us); \
1740         } \
1741         (cond) ? 0 : -ETIMEDOUT; \
1742 })
1743
1744 #define hl_poll_timeout_device_memory(hdev, addr, val, cond, sleep_us, \
1745                                         timeout_us) \
1746 ({ \
1747         ktime_t __timeout; \
1748         if (hdev->pdev) \
1749                 __timeout = ktime_add_us(ktime_get(), timeout_us); \
1750         else \
1751                 __timeout = ktime_add_us(ktime_get(),\
1752                                 min((u64)(timeout_us * 10), \
1753                                         (u64) HL_SIM_MAX_TIMEOUT_US)); \
1754         might_sleep_if(sleep_us); \
1755         for (;;) { \
1756                 (val) = readl(addr); \
1757                 if (cond) \
1758                         break; \
1759                 if (timeout_us && ktime_compare(ktime_get(), __timeout) > 0) { \
1760                         (val) = readl(addr); \
1761                         break; \
1762                 } \
1763                 if (sleep_us) \
1764                         usleep_range((sleep_us >> 2) + 1, sleep_us); \
1765         } \
1766         (cond) ? 0 : -ETIMEDOUT; \
1767 })
1768
1769 struct hwmon_chip_info;
1770
1771 /**
1772  * struct hl_device_reset_work - reset workqueue task wrapper.
1773  * @wq: work queue for device reset procedure.
1774  * @reset_work: reset work to be done.
1775  * @hdev: habanalabs device structure.
1776  */
1777 struct hl_device_reset_work {
1778         struct workqueue_struct         *wq;
1779         struct delayed_work             reset_work;
1780         struct hl_device                *hdev;
1781 };
1782
1783 /**
1784  * struct hr_mmu_hop_addrs - used for holding per-device host-resident mmu hop
1785  * information.
1786  * @virt_addr: the virtual address of the hop.
1787  * @phys-addr: the physical address of the hop (used by the device-mmu).
1788  * @shadow_addr: The shadow of the hop used by the driver for walking the hops.
1789  */
1790 struct hr_mmu_hop_addrs {
1791         u64 virt_addr;
1792         u64 phys_addr;
1793         u64 shadow_addr;
1794 };
1795
1796 /**
1797  * struct hl_mmu_hr_pgt_priv - used for holding per-device mmu host-resident
1798  * page-table internal information.
1799  * @mmu_pgt_pool: pool of page tables used by MMU for allocating hops.
1800  * @mmu_shadow_hop0: shadow array of hop0 tables.
1801  */
1802 struct hl_mmu_hr_priv {
1803         struct gen_pool *mmu_pgt_pool;
1804         struct hr_mmu_hop_addrs *mmu_shadow_hop0;
1805 };
1806
1807 /**
1808  * struct hl_mmu_dr_pgt_priv - used for holding per-device mmu device-resident
1809  * page-table internal information.
1810  * @mmu_pgt_pool: pool of page tables used by MMU for allocating hops.
1811  * @mmu_shadow_hop0: shadow array of hop0 tables.
1812  */
1813 struct hl_mmu_dr_priv {
1814         struct gen_pool *mmu_pgt_pool;
1815         void *mmu_shadow_hop0;
1816 };
1817
1818 /**
1819  * struct hl_mmu_priv - used for holding per-device mmu internal information.
1820  * @dr: information on the device-resident MMU, when exists.
1821  * @hr: information on the host-resident MMU, when exists.
1822  */
1823 struct hl_mmu_priv {
1824         struct hl_mmu_dr_priv dr;
1825         struct hl_mmu_hr_priv hr;
1826 };
1827
1828 /**
1829  * struct hl_mmu_per_hop_info - A structure describing one TLB HOP and its entry
1830  *                that was created in order to translate a virtual address to a
1831  *                physical one.
1832  * @hop_addr: The address of the hop.
1833  * @hop_pte_addr: The address of the hop entry.
1834  * @hop_pte_val: The value in the hop entry.
1835  */
1836 struct hl_mmu_per_hop_info {
1837         u64 hop_addr;
1838         u64 hop_pte_addr;
1839         u64 hop_pte_val;
1840 };
1841
1842 /**
1843  * struct hl_mmu_hop_info - A structure describing the TLB hops and their
1844  * hop-entries that were created in order to translate a virtual address to a
1845  * physical one.
1846  * @scrambled_vaddr: The value of the virtual address after scrambling. This
1847  *                   address replaces the original virtual-address when mapped
1848  *                   in the MMU tables.
1849  * @unscrambled_paddr: The un-scrambled physical address.
1850  * @hop_info: Array holding the per-hop information used for the translation.
1851  * @used_hops: The number of hops used for the translation.
1852  * @range_type: virtual address range type.
1853  */
1854 struct hl_mmu_hop_info {
1855         u64 scrambled_vaddr;
1856         u64 unscrambled_paddr;
1857         struct hl_mmu_per_hop_info hop_info[MMU_ARCH_5_HOPS];
1858         u32 used_hops;
1859         enum hl_va_range_type range_type;
1860 };
1861
1862 /**
1863  * struct hl_mmu_funcs - Device related MMU functions.
1864  * @init: initialize the MMU module.
1865  * @fini: release the MMU module.
1866  * @ctx_init: Initialize a context for using the MMU module.
1867  * @ctx_fini: disable a ctx from using the mmu module.
1868  * @map: maps a virtual address to physical address for a context.
1869  * @unmap: unmap a virtual address of a context.
1870  * @flush: flush all writes from all cores to reach device MMU.
1871  * @swap_out: marks all mapping of the given context as swapped out.
1872  * @swap_in: marks all mapping of the given context as swapped in.
1873  * @get_tlb_info: returns the list of hops and hop-entries used that were
1874  *                created in order to translate the giver virtual address to a
1875  *                physical one.
1876  */
1877 struct hl_mmu_funcs {
1878         int (*init)(struct hl_device *hdev);
1879         void (*fini)(struct hl_device *hdev);
1880         int (*ctx_init)(struct hl_ctx *ctx);
1881         void (*ctx_fini)(struct hl_ctx *ctx);
1882         int (*map)(struct hl_ctx *ctx,
1883                         u64 virt_addr, u64 phys_addr, u32 page_size,
1884                         bool is_dram_addr);
1885         int (*unmap)(struct hl_ctx *ctx,
1886                         u64 virt_addr, bool is_dram_addr);
1887         void (*flush)(struct hl_ctx *ctx);
1888         void (*swap_out)(struct hl_ctx *ctx);
1889         void (*swap_in)(struct hl_ctx *ctx);
1890         int (*get_tlb_info)(struct hl_ctx *ctx,
1891                         u64 virt_addr, struct hl_mmu_hop_info *hops);
1892 };
1893
1894 /**
1895  * struct hl_device - habanalabs device structure.
1896  * @pdev: pointer to PCI device, can be NULL in case of simulator device.
1897  * @pcie_bar_phys: array of available PCIe bars physical addresses.
1898  *                 (required only for PCI address match mode)
1899  * @pcie_bar: array of available PCIe bars virtual addresses.
1900  * @rmmio: configuration area address on SRAM.
1901  * @cdev: related char device.
1902  * @cdev_ctrl: char device for control operations only (INFO IOCTL)
1903  * @dev: related kernel basic device structure.
1904  * @dev_ctrl: related kernel device structure for the control device
1905  * @work_freq: delayed work to lower device frequency if possible.
1906  * @work_heartbeat: delayed work for CPU-CP is-alive check.
1907  * @device_reset_work: delayed work which performs hard reset
1908  * @asic_name: ASIC specific name.
1909  * @asic_type: ASIC specific type.
1910  * @completion_queue: array of hl_cq.
1911  * @user_interrupt: array of hl_user_interrupt. upon the corresponding user
1912  *                  interrupt, driver will monitor the list of fences
1913  *                  registered to this interrupt.
1914  * @common_user_interrupt: common user interrupt for all user interrupts.
1915  *                         upon any user interrupt, driver will monitor the
1916  *                         list of fences registered to this common structure.
1917  * @cq_wq: work queues of completion queues for executing work in process
1918  *         context.
1919  * @eq_wq: work queue of event queue for executing work in process context.
1920  * @sob_reset_wq: work queue for sob reset executions.
1921  * @kernel_ctx: Kernel driver context structure.
1922  * @kernel_queues: array of hl_hw_queue.
1923  * @cs_mirror_list: CS mirror list for TDR.
1924  * @cs_mirror_lock: protects cs_mirror_list.
1925  * @kernel_cb_mgr: command buffer manager for creating/destroying/handling CGs.
1926  * @event_queue: event queue for IRQ from CPU-CP.
1927  * @dma_pool: DMA pool for small allocations.
1928  * @cpu_accessible_dma_mem: Host <-> CPU-CP shared memory CPU address.
1929  * @cpu_accessible_dma_address: Host <-> CPU-CP shared memory DMA address.
1930  * @cpu_accessible_dma_pool: Host <-> CPU-CP shared memory pool.
1931  * @asid_bitmap: holds used/available ASIDs.
1932  * @asid_mutex: protects asid_bitmap.
1933  * @send_cpu_message_lock: enforces only one message in Host <-> CPU-CP queue.
1934  * @debug_lock: protects critical section of setting debug mode for device
1935  * @asic_prop: ASIC specific immutable properties.
1936  * @asic_funcs: ASIC specific functions.
1937  * @asic_specific: ASIC specific information to use only from ASIC files.
1938  * @vm: virtual memory manager for MMU.
1939  * @hwmon_dev: H/W monitor device.
1940  * @pm_mng_profile: current power management profile.
1941  * @hl_chip_info: ASIC's sensors information.
1942  * @device_status_description: device status description.
1943  * @hl_debugfs: device's debugfs manager.
1944  * @cb_pool: list of preallocated CBs.
1945  * @cb_pool_lock: protects the CB pool.
1946  * @internal_cb_pool_virt_addr: internal command buffer pool virtual address.
1947  * @internal_cb_pool_dma_addr: internal command buffer pool dma address.
1948  * @internal_cb_pool: internal command buffer memory pool.
1949  * @internal_cb_va_base: internal cb pool mmu virtual address base
1950  * @fpriv_list: list of file private data structures. Each structure is created
1951  *              when a user opens the device
1952  * @fpriv_list_lock: protects the fpriv_list
1953  * @compute_ctx: current compute context executing.
1954  * @aggregated_cs_counters: aggregated cs counters among all contexts
1955  * @mmu_priv: device-specific MMU data.
1956  * @mmu_func: device-related MMU functions.
1957  * @dram_used_mem: current DRAM memory consumption.
1958  * @timeout_jiffies: device CS timeout value.
1959  * @max_power: the max power of the device, as configured by the sysadmin. This
1960  *             value is saved so in case of hard-reset, the driver will restore
1961  *             this value and update the F/W after the re-initialization
1962  * @clock_gating_mask: is clock gating enabled. bitmask that represents the
1963  *                     different engines. See debugfs-driver-habanalabs for
1964  *                     details.
1965  * @boot_error_status_mask: contains a mask of the device boot error status.
1966  *                          Each bit represents a different error, according to
1967  *                          the defines in hl_boot_if.h. If the bit is cleared,
1968  *                          the error will be ignored by the driver during
1969  *                          device initialization. Mainly used to debug and
1970  *                          workaround firmware bugs
1971  * @in_reset: is device in reset flow.
1972  * @curr_pll_profile: current PLL profile.
1973  * @card_type: Various ASICs have several card types. This indicates the card
1974  *             type of the current device.
1975  * @major: habanalabs kernel driver major.
1976  * @high_pll: high PLL profile frequency.
1977  * @soft_reset_cnt: number of soft reset since the driver was loaded.
1978  * @hard_reset_cnt: number of hard reset since the driver was loaded.
1979  * @clk_throttling_reason: bitmask represents the current clk throttling reasons
1980  * @id: device minor.
1981  * @id_control: minor of the control device
1982  * @cpu_pci_msb_addr: 50-bit extension bits for the device CPU's 40-bit
1983  *                    addresses.
1984  * @disabled: is device disabled.
1985  * @late_init_done: is late init stage was done during initialization.
1986  * @hwmon_initialized: is H/W monitor sensors was initialized.
1987  * @hard_reset_pending: is there a hard reset work pending.
1988  * @heartbeat: is heartbeat sanity check towards CPU-CP enabled.
1989  * @reset_on_lockup: true if a reset should be done in case of stuck CS, false
1990  *                   otherwise.
1991  * @dram_default_page_mapping: is DRAM default page mapping enabled.
1992  * @memory_scrub: true to perform device memory scrub in various locations,
1993  *                such as context-switch, context close, page free, etc.
1994  * @pmmu_huge_range: is a different virtual addresses range used for PMMU with
1995  *                   huge pages.
1996  * @init_done: is the initialization of the device done.
1997  * @device_cpu_disabled: is the device CPU disabled (due to timeouts)
1998  * @dma_mask: the dma mask that was set for this device
1999  * @in_debug: is device under debug. This, together with fpriv_list, enforces
2000  *            that only a single user is configuring the debug infrastructure.
2001  * @power9_64bit_dma_enable: true to enable 64-bit DMA mask support. Relevant
2002  *                           only to POWER9 machines.
2003  * @cdev_sysfs_created: were char devices and sysfs nodes created.
2004  * @stop_on_err: true if engines should stop on error.
2005  * @supports_sync_stream: is sync stream supported.
2006  * @sync_stream_queue_idx: helper index for sync stream queues initialization.
2007  * @collective_mon_idx: helper index for collective initialization
2008  * @supports_coresight: is CoreSight supported.
2009  * @supports_soft_reset: is soft reset supported.
2010  * @supports_cb_mapping: is mapping a CB to the device's MMU supported.
2011  * @needs_reset: true if reset_on_lockup is false and device should be reset
2012  *               due to lockup.
2013  * @process_kill_trial_cnt: number of trials reset thread tried killing
2014  *                          user processes
2015  * @device_fini_pending: true if device_fini was called and might be
2016  *                       waiting for the reset thread to finish
2017  * @supports_staged_submission: true if staged submissions are supported
2018  */
2019 struct hl_device {
2020         struct pci_dev                  *pdev;
2021         u64                             pcie_bar_phys[HL_PCI_NUM_BARS];
2022         void __iomem                    *pcie_bar[HL_PCI_NUM_BARS];
2023         void __iomem                    *rmmio;
2024         struct cdev                     cdev;
2025         struct cdev                     cdev_ctrl;
2026         struct device                   *dev;
2027         struct device                   *dev_ctrl;
2028         struct delayed_work             work_freq;
2029         struct delayed_work             work_heartbeat;
2030         struct hl_device_reset_work     device_reset_work;
2031         char                            asic_name[HL_STR_MAX];
2032         char                            status[HL_DEV_STS_MAX][HL_STR_MAX];
2033         enum hl_asic_type               asic_type;
2034         struct hl_cq                    *completion_queue;
2035         struct hl_user_interrupt        *user_interrupt;
2036         struct hl_user_interrupt        common_user_interrupt;
2037         struct workqueue_struct         **cq_wq;
2038         struct workqueue_struct         *eq_wq;
2039         struct workqueue_struct         *sob_reset_wq;
2040         struct hl_ctx                   *kernel_ctx;
2041         struct hl_hw_queue              *kernel_queues;
2042         struct list_head                cs_mirror_list;
2043         spinlock_t                      cs_mirror_lock;
2044         struct hl_cb_mgr                kernel_cb_mgr;
2045         struct hl_eq                    event_queue;
2046         struct dma_pool                 *dma_pool;
2047         void                            *cpu_accessible_dma_mem;
2048         dma_addr_t                      cpu_accessible_dma_address;
2049         struct gen_pool                 *cpu_accessible_dma_pool;
2050         unsigned long                   *asid_bitmap;
2051         struct mutex                    asid_mutex;
2052         struct mutex                    send_cpu_message_lock;
2053         struct mutex                    debug_lock;
2054         struct asic_fixed_properties    asic_prop;
2055         const struct hl_asic_funcs      *asic_funcs;
2056         void                            *asic_specific;
2057         struct hl_vm                    vm;
2058         struct device                   *hwmon_dev;
2059         enum hl_pm_mng_profile          pm_mng_profile;
2060         struct hwmon_chip_info          *hl_chip_info;
2061
2062         struct hl_dbg_device_entry      hl_debugfs;
2063
2064         struct list_head                cb_pool;
2065         spinlock_t                      cb_pool_lock;
2066
2067         void                            *internal_cb_pool_virt_addr;
2068         dma_addr_t                      internal_cb_pool_dma_addr;
2069         struct gen_pool                 *internal_cb_pool;
2070         u64                             internal_cb_va_base;
2071
2072         struct list_head                fpriv_list;
2073         struct mutex                    fpriv_list_lock;
2074
2075         struct hl_ctx                   *compute_ctx;
2076
2077         struct hl_cs_counters_atomic    aggregated_cs_counters;
2078
2079         struct hl_mmu_priv              mmu_priv;
2080         struct hl_mmu_funcs             mmu_func[MMU_NUM_PGT_LOCATIONS];
2081
2082         atomic64_t                      dram_used_mem;
2083         u64                             timeout_jiffies;
2084         u64                             max_power;
2085         u64                             clock_gating_mask;
2086         u64                             boot_error_status_mask;
2087         atomic_t                        in_reset;
2088         enum hl_pll_frequency           curr_pll_profile;
2089         enum cpucp_card_types           card_type;
2090         u32                             major;
2091         u32                             high_pll;
2092         u32                             soft_reset_cnt;
2093         u32                             hard_reset_cnt;
2094         u32                             clk_throttling_reason;
2095         u16                             id;
2096         u16                             id_control;
2097         u16                             cpu_pci_msb_addr;
2098         u8                              disabled;
2099         u8                              late_init_done;
2100         u8                              hwmon_initialized;
2101         u8                              hard_reset_pending;
2102         u8                              heartbeat;
2103         u8                              reset_on_lockup;
2104         u8                              dram_default_page_mapping;
2105         u8                              memory_scrub;
2106         u8                              pmmu_huge_range;
2107         u8                              init_done;
2108         u8                              device_cpu_disabled;
2109         u8                              dma_mask;
2110         u8                              in_debug;
2111         u8                              power9_64bit_dma_enable;
2112         u8                              cdev_sysfs_created;
2113         u8                              stop_on_err;
2114         u8                              supports_sync_stream;
2115         u8                              sync_stream_queue_idx;
2116         u8                              collective_mon_idx;
2117         u8                              supports_coresight;
2118         u8                              supports_soft_reset;
2119         u8                              supports_cb_mapping;
2120         u8                              needs_reset;
2121         u8                              process_kill_trial_cnt;
2122         u8                              device_fini_pending;
2123         u8                              supports_staged_submission;
2124
2125         /* Parameters for bring-up */
2126         u64                             nic_ports_mask;
2127         u64                             fw_components;
2128         u8                              mmu_enable;
2129         u8                              mmu_huge_page_opt;
2130         u8                              reset_pcilink;
2131         u8                              cpu_queues_enable;
2132         u8                              pldm;
2133         u8                              axi_drain;
2134         u8                              sram_scrambler_enable;
2135         u8                              dram_scrambler_enable;
2136         u8                              hard_reset_on_fw_events;
2137         u8                              bmc_enable;
2138         u8                              rl_enable;
2139         u8                              reset_on_preboot_fail;
2140         u8                              reset_upon_device_release;
2141 };
2142
2143
2144 /*
2145  * IOCTLs
2146  */
2147
2148 /**
2149  * typedef hl_ioctl_t - typedef for ioctl function in the driver
2150  * @hpriv: pointer to the FD's private data, which contains state of
2151  *              user process
2152  * @data: pointer to the input/output arguments structure of the IOCTL
2153  *
2154  * Return: 0 for success, negative value for error
2155  */
2156 typedef int hl_ioctl_t(struct hl_fpriv *hpriv, void *data);
2157
2158 /**
2159  * struct hl_ioctl_desc - describes an IOCTL entry of the driver.
2160  * @cmd: the IOCTL code as created by the kernel macros.
2161  * @func: pointer to the driver's function that should be called for this IOCTL.
2162  */
2163 struct hl_ioctl_desc {
2164         unsigned int cmd;
2165         hl_ioctl_t *func;
2166 };
2167
2168
2169 /*
2170  * Kernel module functions that can be accessed by entire module
2171  */
2172
2173 /**
2174  * hl_mem_area_inside_range() - Checks whether address+size are inside a range.
2175  * @address: The start address of the area we want to validate.
2176  * @size: The size in bytes of the area we want to validate.
2177  * @range_start_address: The start address of the valid range.
2178  * @range_end_address: The end address of the valid range.
2179  *
2180  * Return: true if the area is inside the valid range, false otherwise.
2181  */
2182 static inline bool hl_mem_area_inside_range(u64 address, u64 size,
2183                                 u64 range_start_address, u64 range_end_address)
2184 {
2185         u64 end_address = address + size;
2186
2187         if ((address >= range_start_address) &&
2188                         (end_address <= range_end_address) &&
2189                         (end_address > address))
2190                 return true;
2191
2192         return false;
2193 }
2194
2195 /**
2196  * hl_mem_area_crosses_range() - Checks whether address+size crossing a range.
2197  * @address: The start address of the area we want to validate.
2198  * @size: The size in bytes of the area we want to validate.
2199  * @range_start_address: The start address of the valid range.
2200  * @range_end_address: The end address of the valid range.
2201  *
2202  * Return: true if the area overlaps part or all of the valid range,
2203  *              false otherwise.
2204  */
2205 static inline bool hl_mem_area_crosses_range(u64 address, u32 size,
2206                                 u64 range_start_address, u64 range_end_address)
2207 {
2208         u64 end_address = address + size;
2209
2210         if ((address >= range_start_address) &&
2211                         (address < range_end_address))
2212                 return true;
2213
2214         if ((end_address >= range_start_address) &&
2215                         (end_address < range_end_address))
2216                 return true;
2217
2218         if ((address < range_start_address) &&
2219                         (end_address >= range_end_address))
2220                 return true;
2221
2222         return false;
2223 }
2224
2225 int hl_device_open(struct inode *inode, struct file *filp);
2226 int hl_device_open_ctrl(struct inode *inode, struct file *filp);
2227 bool hl_device_operational(struct hl_device *hdev,
2228                 enum hl_device_status *status);
2229 enum hl_device_status hl_device_status(struct hl_device *hdev);
2230 int hl_device_set_debug_mode(struct hl_device *hdev, bool enable);
2231 int create_hdev(struct hl_device **dev, struct pci_dev *pdev,
2232                 enum hl_asic_type asic_type, int minor);
2233 void destroy_hdev(struct hl_device *hdev);
2234 int hl_hw_queues_create(struct hl_device *hdev);
2235 void hl_hw_queues_destroy(struct hl_device *hdev);
2236 int hl_hw_queue_send_cb_no_cmpl(struct hl_device *hdev, u32 hw_queue_id,
2237                                 u32 cb_size, u64 cb_ptr);
2238 int hl_hw_queue_schedule_cs(struct hl_cs *cs);
2239 u32 hl_hw_queue_add_ptr(u32 ptr, u16 val);
2240 void hl_hw_queue_inc_ci_kernel(struct hl_device *hdev, u32 hw_queue_id);
2241 void hl_hw_queue_update_ci(struct hl_cs *cs);
2242 void hl_hw_queue_reset(struct hl_device *hdev, bool hard_reset);
2243
2244 #define hl_queue_inc_ptr(p)             hl_hw_queue_add_ptr(p, 1)
2245 #define hl_pi_2_offset(pi)              ((pi) & (HL_QUEUE_LENGTH - 1))
2246
2247 int hl_cq_init(struct hl_device *hdev, struct hl_cq *q, u32 hw_queue_id);
2248 void hl_cq_fini(struct hl_device *hdev, struct hl_cq *q);
2249 int hl_eq_init(struct hl_device *hdev, struct hl_eq *q);
2250 void hl_eq_fini(struct hl_device *hdev, struct hl_eq *q);
2251 void hl_cq_reset(struct hl_device *hdev, struct hl_cq *q);
2252 void hl_eq_reset(struct hl_device *hdev, struct hl_eq *q);
2253 irqreturn_t hl_irq_handler_cq(int irq, void *arg);
2254 irqreturn_t hl_irq_handler_eq(int irq, void *arg);
2255 irqreturn_t hl_irq_handler_user_cq(int irq, void *arg);
2256 irqreturn_t hl_irq_handler_default(int irq, void *arg);
2257 u32 hl_cq_inc_ptr(u32 ptr);
2258
2259 int hl_asid_init(struct hl_device *hdev);
2260 void hl_asid_fini(struct hl_device *hdev);
2261 unsigned long hl_asid_alloc(struct hl_device *hdev);
2262 void hl_asid_free(struct hl_device *hdev, unsigned long asid);
2263
2264 int hl_ctx_create(struct hl_device *hdev, struct hl_fpriv *hpriv);
2265 void hl_ctx_free(struct hl_device *hdev, struct hl_ctx *ctx);
2266 int hl_ctx_init(struct hl_device *hdev, struct hl_ctx *ctx, bool is_kernel_ctx);
2267 void hl_ctx_do_release(struct kref *ref);
2268 void hl_ctx_get(struct hl_device *hdev, struct hl_ctx *ctx);
2269 int hl_ctx_put(struct hl_ctx *ctx);
2270 struct hl_fence *hl_ctx_get_fence(struct hl_ctx *ctx, u64 seq);
2271 void hl_ctx_mgr_init(struct hl_ctx_mgr *mgr);
2272 void hl_ctx_mgr_fini(struct hl_device *hdev, struct hl_ctx_mgr *mgr);
2273
2274 int hl_device_init(struct hl_device *hdev, struct class *hclass);
2275 void hl_device_fini(struct hl_device *hdev);
2276 int hl_device_suspend(struct hl_device *hdev);
2277 int hl_device_resume(struct hl_device *hdev);
2278 int hl_device_reset(struct hl_device *hdev, u32 flags);
2279 void hl_hpriv_get(struct hl_fpriv *hpriv);
2280 int hl_hpriv_put(struct hl_fpriv *hpriv);
2281 int hl_device_set_frequency(struct hl_device *hdev, enum hl_pll_frequency freq);
2282 int hl_device_utilization(struct hl_device *hdev, u32 *utilization);
2283
2284 int hl_build_hwmon_channel_info(struct hl_device *hdev,
2285                 struct cpucp_sensor *sensors_arr);
2286
2287 int hl_sysfs_init(struct hl_device *hdev);
2288 void hl_sysfs_fini(struct hl_device *hdev);
2289
2290 int hl_hwmon_init(struct hl_device *hdev);
2291 void hl_hwmon_fini(struct hl_device *hdev);
2292
2293 int hl_cb_create(struct hl_device *hdev, struct hl_cb_mgr *mgr,
2294                         struct hl_ctx *ctx, u32 cb_size, bool internal_cb,
2295                         bool map_cb, u64 *handle);
2296 int hl_cb_destroy(struct hl_device *hdev, struct hl_cb_mgr *mgr, u64 cb_handle);
2297 int hl_cb_mmap(struct hl_fpriv *hpriv, struct vm_area_struct *vma);
2298 int hl_hw_block_mmap(struct hl_fpriv *hpriv, struct vm_area_struct *vma);
2299 struct hl_cb *hl_cb_get(struct hl_device *hdev, struct hl_cb_mgr *mgr,
2300                         u32 handle);
2301 void hl_cb_put(struct hl_cb *cb);
2302 void hl_cb_mgr_init(struct hl_cb_mgr *mgr);
2303 void hl_cb_mgr_fini(struct hl_device *hdev, struct hl_cb_mgr *mgr);
2304 struct hl_cb *hl_cb_kernel_create(struct hl_device *hdev, u32 cb_size,
2305                                         bool internal_cb);
2306 int hl_cb_pool_init(struct hl_device *hdev);
2307 int hl_cb_pool_fini(struct hl_device *hdev);
2308 int hl_cb_va_pool_init(struct hl_ctx *ctx);
2309 void hl_cb_va_pool_fini(struct hl_ctx *ctx);
2310
2311 void hl_cs_rollback_all(struct hl_device *hdev);
2312 void hl_pending_cb_list_flush(struct hl_ctx *ctx);
2313 struct hl_cs_job *hl_cs_allocate_job(struct hl_device *hdev,
2314                 enum hl_queue_type queue_type, bool is_kernel_allocated_cb);
2315 void hl_sob_reset_error(struct kref *ref);
2316 int hl_gen_sob_mask(u16 sob_base, u8 sob_mask, u8 *mask);
2317 void hl_fence_put(struct hl_fence *fence);
2318 void hl_fence_get(struct hl_fence *fence);
2319 void cs_get(struct hl_cs *cs);
2320 bool cs_needs_completion(struct hl_cs *cs);
2321 bool cs_needs_timeout(struct hl_cs *cs);
2322 bool is_staged_cs_last_exists(struct hl_device *hdev, struct hl_cs *cs);
2323 struct hl_cs *hl_staged_cs_find_first(struct hl_device *hdev, u64 cs_seq);
2324
2325 void goya_set_asic_funcs(struct hl_device *hdev);
2326 void gaudi_set_asic_funcs(struct hl_device *hdev);
2327
2328 int hl_vm_ctx_init(struct hl_ctx *ctx);
2329 void hl_vm_ctx_fini(struct hl_ctx *ctx);
2330
2331 int hl_vm_init(struct hl_device *hdev);
2332 void hl_vm_fini(struct hl_device *hdev);
2333
2334 void hl_hw_block_mem_init(struct hl_ctx *ctx);
2335 void hl_hw_block_mem_fini(struct hl_ctx *ctx);
2336
2337 u64 hl_reserve_va_block(struct hl_device *hdev, struct hl_ctx *ctx,
2338                 enum hl_va_range_type type, u32 size, u32 alignment);
2339 int hl_unreserve_va_block(struct hl_device *hdev, struct hl_ctx *ctx,
2340                 u64 start_addr, u64 size);
2341 int hl_pin_host_memory(struct hl_device *hdev, u64 addr, u64 size,
2342                         struct hl_userptr *userptr);
2343 void hl_unpin_host_memory(struct hl_device *hdev, struct hl_userptr *userptr);
2344 void hl_userptr_delete_list(struct hl_device *hdev,
2345                                 struct list_head *userptr_list);
2346 bool hl_userptr_is_pinned(struct hl_device *hdev, u64 addr, u32 size,
2347                                 struct list_head *userptr_list,
2348                                 struct hl_userptr **userptr);
2349
2350 int hl_mmu_init(struct hl_device *hdev);
2351 void hl_mmu_fini(struct hl_device *hdev);
2352 int hl_mmu_ctx_init(struct hl_ctx *ctx);
2353 void hl_mmu_ctx_fini(struct hl_ctx *ctx);
2354 int hl_mmu_map_page(struct hl_ctx *ctx, u64 virt_addr, u64 phys_addr,
2355                 u32 page_size, bool flush_pte);
2356 int hl_mmu_unmap_page(struct hl_ctx *ctx, u64 virt_addr, u32 page_size,
2357                 bool flush_pte);
2358 int hl_mmu_map_contiguous(struct hl_ctx *ctx, u64 virt_addr,
2359                                         u64 phys_addr, u32 size);
2360 int hl_mmu_unmap_contiguous(struct hl_ctx *ctx, u64 virt_addr, u32 size);
2361 void hl_mmu_swap_out(struct hl_ctx *ctx);
2362 void hl_mmu_swap_in(struct hl_ctx *ctx);
2363 int hl_mmu_if_set_funcs(struct hl_device *hdev);
2364 void hl_mmu_v1_set_funcs(struct hl_device *hdev, struct hl_mmu_funcs *mmu);
2365 int hl_mmu_va_to_pa(struct hl_ctx *ctx, u64 virt_addr, u64 *phys_addr);
2366 int hl_mmu_get_tlb_info(struct hl_ctx *ctx, u64 virt_addr,
2367                         struct hl_mmu_hop_info *hops);
2368 u64 hl_mmu_scramble_addr(struct hl_device *hdev, u64 addr);
2369 u64 hl_mmu_descramble_addr(struct hl_device *hdev, u64 addr);
2370 bool hl_is_dram_va(struct hl_device *hdev, u64 virt_addr);
2371
2372 int hl_fw_load_fw_to_device(struct hl_device *hdev, const char *fw_name,
2373                                 void __iomem *dst, u32 src_offset, u32 size);
2374 int hl_fw_send_pci_access_msg(struct hl_device *hdev, u32 opcode);
2375 int hl_fw_send_cpu_message(struct hl_device *hdev, u32 hw_queue_id, u32 *msg,
2376                                 u16 len, u32 timeout, u64 *result);
2377 int hl_fw_unmask_irq(struct hl_device *hdev, u16 event_type);
2378 int hl_fw_unmask_irq_arr(struct hl_device *hdev, const u32 *irq_arr,
2379                 size_t irq_arr_size);
2380 int hl_fw_test_cpu_queue(struct hl_device *hdev);
2381 void *hl_fw_cpu_accessible_dma_pool_alloc(struct hl_device *hdev, size_t size,
2382                                                 dma_addr_t *dma_handle);
2383 void hl_fw_cpu_accessible_dma_pool_free(struct hl_device *hdev, size_t size,
2384                                         void *vaddr);
2385 int hl_fw_send_heartbeat(struct hl_device *hdev);
2386 int hl_fw_cpucp_info_get(struct hl_device *hdev,
2387                         u32 cpu_security_boot_status_reg,
2388                         u32 boot_err0_reg);
2389 int hl_fw_cpucp_handshake(struct hl_device *hdev,
2390                         u32 cpu_security_boot_status_reg,
2391                         u32 boot_err0_reg);
2392 int hl_fw_get_eeprom_data(struct hl_device *hdev, void *data, size_t max_size);
2393 int hl_fw_cpucp_pci_counters_get(struct hl_device *hdev,
2394                 struct hl_info_pci_counters *counters);
2395 int hl_fw_cpucp_total_energy_get(struct hl_device *hdev,
2396                         u64 *total_energy);
2397 int get_used_pll_index(struct hl_device *hdev, u32 input_pll_index,
2398                                                 enum pll_index *pll_index);
2399 int hl_fw_cpucp_pll_info_get(struct hl_device *hdev, u32 pll_index,
2400                 u16 *pll_freq_arr);
2401 int hl_fw_cpucp_power_get(struct hl_device *hdev, u64 *power);
2402 int hl_fw_init_cpu(struct hl_device *hdev, u32 cpu_boot_status_reg,
2403                         u32 msg_to_cpu_reg, u32 cpu_msg_status_reg,
2404                         u32 cpu_security_boot_status_reg, u32 boot_err0_reg,
2405                         bool skip_bmc, u32 cpu_timeout, u32 boot_fit_timeout);
2406 int hl_fw_read_preboot_status(struct hl_device *hdev, u32 cpu_boot_status_reg,
2407                 u32 cpu_security_boot_status_reg, u32 boot_err0_reg,
2408                 u32 timeout);
2409
2410 int hl_pci_bars_map(struct hl_device *hdev, const char * const name[3],
2411                         bool is_wc[3]);
2412 int hl_pci_elbi_read(struct hl_device *hdev, u64 addr, u32 *data);
2413 int hl_pci_iatu_write(struct hl_device *hdev, u32 addr, u32 data);
2414 int hl_pci_set_inbound_region(struct hl_device *hdev, u8 region,
2415                 struct hl_inbound_pci_region *pci_region);
2416 int hl_pci_set_outbound_region(struct hl_device *hdev,
2417                 struct hl_outbound_pci_region *pci_region);
2418 int hl_pci_init(struct hl_device *hdev);
2419 void hl_pci_fini(struct hl_device *hdev);
2420
2421 long hl_get_frequency(struct hl_device *hdev, u32 pll_index,
2422                                                                 bool curr);
2423 void hl_set_frequency(struct hl_device *hdev, u32 pll_index,
2424                                                                 u64 freq);
2425 int hl_get_temperature(struct hl_device *hdev,
2426                        int sensor_index, u32 attr, long *value);
2427 int hl_set_temperature(struct hl_device *hdev,
2428                        int sensor_index, u32 attr, long value);
2429 int hl_get_voltage(struct hl_device *hdev,
2430                    int sensor_index, u32 attr, long *value);
2431 int hl_get_current(struct hl_device *hdev,
2432                    int sensor_index, u32 attr, long *value);
2433 int hl_get_fan_speed(struct hl_device *hdev,
2434                      int sensor_index, u32 attr, long *value);
2435 int hl_get_pwm_info(struct hl_device *hdev,
2436                     int sensor_index, u32 attr, long *value);
2437 void hl_set_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr,
2438                         long value);
2439 u64 hl_get_max_power(struct hl_device *hdev);
2440 void hl_set_max_power(struct hl_device *hdev);
2441 int hl_set_voltage(struct hl_device *hdev,
2442                         int sensor_index, u32 attr, long value);
2443 int hl_set_current(struct hl_device *hdev,
2444                         int sensor_index, u32 attr, long value);
2445 void hl_release_pending_user_interrupts(struct hl_device *hdev);
2446
2447 #ifdef CONFIG_DEBUG_FS
2448
2449 void hl_debugfs_init(void);
2450 void hl_debugfs_fini(void);
2451 void hl_debugfs_add_device(struct hl_device *hdev);
2452 void hl_debugfs_remove_device(struct hl_device *hdev);
2453 void hl_debugfs_add_file(struct hl_fpriv *hpriv);
2454 void hl_debugfs_remove_file(struct hl_fpriv *hpriv);
2455 void hl_debugfs_add_cb(struct hl_cb *cb);
2456 void hl_debugfs_remove_cb(struct hl_cb *cb);
2457 void hl_debugfs_add_cs(struct hl_cs *cs);
2458 void hl_debugfs_remove_cs(struct hl_cs *cs);
2459 void hl_debugfs_add_job(struct hl_device *hdev, struct hl_cs_job *job);
2460 void hl_debugfs_remove_job(struct hl_device *hdev, struct hl_cs_job *job);
2461 void hl_debugfs_add_userptr(struct hl_device *hdev, struct hl_userptr *userptr);
2462 void hl_debugfs_remove_userptr(struct hl_device *hdev,
2463                                 struct hl_userptr *userptr);
2464 void hl_debugfs_add_ctx_mem_hash(struct hl_device *hdev, struct hl_ctx *ctx);
2465 void hl_debugfs_remove_ctx_mem_hash(struct hl_device *hdev, struct hl_ctx *ctx);
2466
2467 #else
2468
2469 static inline void __init hl_debugfs_init(void)
2470 {
2471 }
2472
2473 static inline void hl_debugfs_fini(void)
2474 {
2475 }
2476
2477 static inline void hl_debugfs_add_device(struct hl_device *hdev)
2478 {
2479 }
2480
2481 static inline void hl_debugfs_remove_device(struct hl_device *hdev)
2482 {
2483 }
2484
2485 static inline void hl_debugfs_add_file(struct hl_fpriv *hpriv)
2486 {
2487 }
2488
2489 static inline void hl_debugfs_remove_file(struct hl_fpriv *hpriv)
2490 {
2491 }
2492
2493 static inline void hl_debugfs_add_cb(struct hl_cb *cb)
2494 {
2495 }
2496
2497 static inline void hl_debugfs_remove_cb(struct hl_cb *cb)
2498 {
2499 }
2500
2501 static inline void hl_debugfs_add_cs(struct hl_cs *cs)
2502 {
2503 }
2504
2505 static inline void hl_debugfs_remove_cs(struct hl_cs *cs)
2506 {
2507 }
2508
2509 static inline void hl_debugfs_add_job(struct hl_device *hdev,
2510                                         struct hl_cs_job *job)
2511 {
2512 }
2513
2514 static inline void hl_debugfs_remove_job(struct hl_device *hdev,
2515                                         struct hl_cs_job *job)
2516 {
2517 }
2518
2519 static inline void hl_debugfs_add_userptr(struct hl_device *hdev,
2520                                         struct hl_userptr *userptr)
2521 {
2522 }
2523
2524 static inline void hl_debugfs_remove_userptr(struct hl_device *hdev,
2525                                         struct hl_userptr *userptr)
2526 {
2527 }
2528
2529 static inline void hl_debugfs_add_ctx_mem_hash(struct hl_device *hdev,
2530                                         struct hl_ctx *ctx)
2531 {
2532 }
2533
2534 static inline void hl_debugfs_remove_ctx_mem_hash(struct hl_device *hdev,
2535                                         struct hl_ctx *ctx)
2536 {
2537 }
2538
2539 #endif
2540
2541 /* IOCTLs */
2542 long hl_ioctl(struct file *filep, unsigned int cmd, unsigned long arg);
2543 long hl_ioctl_control(struct file *filep, unsigned int cmd, unsigned long arg);
2544 int hl_cb_ioctl(struct hl_fpriv *hpriv, void *data);
2545 int hl_cs_ioctl(struct hl_fpriv *hpriv, void *data);
2546 int hl_wait_ioctl(struct hl_fpriv *hpriv, void *data);
2547 int hl_mem_ioctl(struct hl_fpriv *hpriv, void *data);
2548
2549 #endif /* HABANALABSP_H_ */