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