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