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