]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/misc/habanalabs/habanalabs.h
Merge tag 'scsi-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/jejb/scsi
[linux.git] / drivers / misc / habanalabs / 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/armcp_if.h"
12 #include "include/qman_if.h"
13
14 #include <linux/cdev.h>
15 #include <linux/iopoll.h>
16 #include <linux/irqreturn.h>
17 #include <linux/dma-fence.h>
18 #include <linux/dma-direction.h>
19 #include <linux/scatterlist.h>
20 #include <linux/hashtable.h>
21
22 #define HL_NAME                         "habanalabs"
23
24 #define HL_MMAP_CB_MASK                 (0x8000000000000000ull >> PAGE_SHIFT)
25
26 #define HL_PENDING_RESET_PER_SEC        5
27
28 #define HL_DEVICE_TIMEOUT_USEC          1000000 /* 1 s */
29
30 #define HL_HEARTBEAT_PER_USEC           5000000 /* 5 s */
31
32 #define HL_PLL_LOW_JOB_FREQ_USEC        5000000 /* 5 s */
33
34 #define HL_ARMCP_INFO_TIMEOUT_USEC      10000000 /* 10s */
35 #define HL_ARMCP_EEPROM_TIMEOUT_USEC    10000000 /* 10s */
36
37 #define HL_MAX_QUEUES                   128
38
39 #define HL_MAX_JOBS_PER_CS              64
40
41 /* MUST BE POWER OF 2 and larger than 1 */
42 #define HL_MAX_PENDING_CS               64
43
44 /* Memory */
45 #define MEM_HASH_TABLE_BITS             7 /* 1 << 7 buckets */
46
47 /* MMU */
48 #define MMU_HASH_TABLE_BITS             7 /* 1 << 7 buckets */
49
50 /**
51  * struct pgt_info - MMU hop page info.
52  * @node: hash linked-list node for the pgts shadow hash of pgts.
53  * @phys_addr: physical address of the pgt.
54  * @shadow_addr: shadow hop in the host.
55  * @ctx: pointer to the owner ctx.
56  * @num_of_ptes: indicates how many ptes are used in the pgt.
57  *
58  * The MMU page tables hierarchy is placed on the DRAM. When a new level (hop)
59  * is needed during mapping, a new page is allocated and this structure holds
60  * its essential information. During unmapping, if no valid PTEs remained in the
61  * page, it is freed with its pgt_info structure.
62  */
63 struct pgt_info {
64         struct hlist_node       node;
65         u64                     phys_addr;
66         u64                     shadow_addr;
67         struct hl_ctx           *ctx;
68         int                     num_of_ptes;
69 };
70
71 struct hl_device;
72 struct hl_fpriv;
73
74 /**
75  * enum hl_queue_type - Supported QUEUE types.
76  * @QUEUE_TYPE_NA: queue is not available.
77  * @QUEUE_TYPE_EXT: external queue which is a DMA channel that may access the
78  *                  host.
79  * @QUEUE_TYPE_INT: internal queue that performs DMA inside the device's
80  *                      memories and/or operates the compute engines.
81  * @QUEUE_TYPE_CPU: S/W queue for communication with the device's CPU.
82  */
83 enum hl_queue_type {
84         QUEUE_TYPE_NA,
85         QUEUE_TYPE_EXT,
86         QUEUE_TYPE_INT,
87         QUEUE_TYPE_CPU
88 };
89
90 /**
91  * struct hw_queue_properties - queue information.
92  * @type: queue type.
93  * @kmd_only: true if only KMD is allowed to send a job to this queue, false
94  *            otherwise.
95  */
96 struct hw_queue_properties {
97         enum hl_queue_type      type;
98         u8                      kmd_only;
99 };
100
101 /**
102  * enum vm_type_t - virtual memory mapping request information.
103  * @VM_TYPE_USERPTR: mapping of user memory to device virtual address.
104  * @VM_TYPE_PHYS_PACK: mapping of DRAM memory to device virtual address.
105  */
106 enum vm_type_t {
107         VM_TYPE_USERPTR,
108         VM_TYPE_PHYS_PACK
109 };
110
111 /**
112  * enum hl_device_hw_state - H/W device state. use this to understand whether
113  *                           to do reset before hw_init or not
114  * @HL_DEVICE_HW_STATE_CLEAN: H/W state is clean. i.e. after hard reset
115  * @HL_DEVICE_HW_STATE_DIRTY: H/W state is dirty. i.e. we started to execute
116  *                            hw_init
117  */
118 enum hl_device_hw_state {
119         HL_DEVICE_HW_STATE_CLEAN = 0,
120         HL_DEVICE_HW_STATE_DIRTY
121 };
122
123 /**
124  * struct asic_fixed_properties - ASIC specific immutable properties.
125  * @hw_queues_props: H/W queues properties.
126  * @armcp_info: received various information from ArmCP regarding the H/W. e.g.
127  *              available sensors.
128  * @uboot_ver: F/W U-boot version.
129  * @preboot_ver: F/W Preboot version.
130  * @sram_base_address: SRAM physical start address.
131  * @sram_end_address: SRAM physical end address.
132  * @sram_user_base_address - SRAM physical start address for user access.
133  * @dram_base_address: DRAM physical start address.
134  * @dram_end_address: DRAM physical end address.
135  * @dram_user_base_address: DRAM physical start address for user access.
136  * @dram_size: DRAM total size.
137  * @dram_pci_bar_size: size of PCI bar towards DRAM.
138  * @max_power_default: max power of the device after reset
139  * @va_space_host_start_address: base address of virtual memory range for
140  *                               mapping host memory.
141  * @va_space_host_end_address: end address of virtual memory range for
142  *                             mapping host memory.
143  * @va_space_dram_start_address: base address of virtual memory range for
144  *                               mapping DRAM memory.
145  * @va_space_dram_end_address: end address of virtual memory range for
146  *                             mapping DRAM memory.
147  * @dram_size_for_default_page_mapping: DRAM size needed to map to avoid page
148  *                                      fault.
149  * @pcie_dbi_base_address: Base address of the PCIE_DBI block.
150  * @pcie_aux_dbi_reg_addr: Address of the PCIE_AUX DBI register.
151  * @mmu_pgt_addr: base physical address in DRAM of MMU page tables.
152  * @mmu_dram_default_page_addr: DRAM default page physical address.
153  * @mmu_pgt_size: MMU page tables total size.
154  * @mmu_pte_size: PTE size in MMU page tables.
155  * @mmu_hop_table_size: MMU hop table size.
156  * @mmu_hop0_tables_total_size: total size of MMU hop0 tables.
157  * @dram_page_size: page size for MMU DRAM allocation.
158  * @cfg_size: configuration space size on SRAM.
159  * @sram_size: total size of SRAM.
160  * @max_asid: maximum number of open contexts (ASIDs).
161  * @num_of_events: number of possible internal H/W IRQs.
162  * @psoc_pci_pll_nr: PCI PLL NR value.
163  * @psoc_pci_pll_nf: PCI PLL NF value.
164  * @psoc_pci_pll_od: PCI PLL OD value.
165  * @psoc_pci_pll_div_factor: PCI PLL DIV FACTOR 1 value.
166  * @completion_queues_count: number of completion queues.
167  * @high_pll: high PLL frequency used by the device.
168  * @cb_pool_cb_cnt: number of CBs in the CB pool.
169  * @cb_pool_cb_size: size of each CB in the CB pool.
170  * @tpc_enabled_mask: which TPCs are enabled.
171  */
172 struct asic_fixed_properties {
173         struct hw_queue_properties      hw_queues_props[HL_MAX_QUEUES];
174         struct armcp_info       armcp_info;
175         char                    uboot_ver[VERSION_MAX_LEN];
176         char                    preboot_ver[VERSION_MAX_LEN];
177         u64                     sram_base_address;
178         u64                     sram_end_address;
179         u64                     sram_user_base_address;
180         u64                     dram_base_address;
181         u64                     dram_end_address;
182         u64                     dram_user_base_address;
183         u64                     dram_size;
184         u64                     dram_pci_bar_size;
185         u64                     max_power_default;
186         u64                     va_space_host_start_address;
187         u64                     va_space_host_end_address;
188         u64                     va_space_dram_start_address;
189         u64                     va_space_dram_end_address;
190         u64                     dram_size_for_default_page_mapping;
191         u64                     pcie_dbi_base_address;
192         u64                     pcie_aux_dbi_reg_addr;
193         u64                     mmu_pgt_addr;
194         u64                     mmu_dram_default_page_addr;
195         u32                     mmu_pgt_size;
196         u32                     mmu_pte_size;
197         u32                     mmu_hop_table_size;
198         u32                     mmu_hop0_tables_total_size;
199         u32                     dram_page_size;
200         u32                     cfg_size;
201         u32                     sram_size;
202         u32                     max_asid;
203         u32                     num_of_events;
204         u32                     psoc_pci_pll_nr;
205         u32                     psoc_pci_pll_nf;
206         u32                     psoc_pci_pll_od;
207         u32                     psoc_pci_pll_div_factor;
208         u32                     high_pll;
209         u32                     cb_pool_cb_cnt;
210         u32                     cb_pool_cb_size;
211         u8                      completion_queues_count;
212         u8                      tpc_enabled_mask;
213 };
214
215 /**
216  * struct hl_dma_fence - wrapper for fence object used by command submissions.
217  * @base_fence: kernel fence object.
218  * @lock: spinlock to protect fence.
219  * @hdev: habanalabs device structure.
220  * @cs_seq: command submission sequence number.
221  */
222 struct hl_dma_fence {
223         struct dma_fence        base_fence;
224         spinlock_t              lock;
225         struct hl_device        *hdev;
226         u64                     cs_seq;
227 };
228
229 /*
230  * Command Buffers
231  */
232
233 #define HL_MAX_CB_SIZE          0x200000        /* 2MB */
234
235 /**
236  * struct hl_cb_mgr - describes a Command Buffer Manager.
237  * @cb_lock: protects cb_handles.
238  * @cb_handles: an idr to hold all command buffer handles.
239  */
240 struct hl_cb_mgr {
241         spinlock_t              cb_lock;
242         struct idr              cb_handles; /* protected by cb_lock */
243 };
244
245 /**
246  * struct hl_cb - describes a Command Buffer.
247  * @refcount: reference counter for usage of the CB.
248  * @hdev: pointer to device this CB belongs to.
249  * @lock: spinlock to protect mmap/cs flows.
250  * @debugfs_list: node in debugfs list of command buffers.
251  * @pool_list: node in pool list of command buffers.
252  * @kernel_address: Holds the CB's kernel virtual address.
253  * @bus_address: Holds the CB's DMA address.
254  * @mmap_size: Holds the CB's size that was mmaped.
255  * @size: holds the CB's size.
256  * @id: the CB's ID.
257  * @cs_cnt: holds number of CS that this CB participates in.
258  * @ctx_id: holds the ID of the owner's context.
259  * @mmap: true if the CB is currently mmaped to user.
260  * @is_pool: true if CB was acquired from the pool, false otherwise.
261  */
262 struct hl_cb {
263         struct kref             refcount;
264         struct hl_device        *hdev;
265         spinlock_t              lock;
266         struct list_head        debugfs_list;
267         struct list_head        pool_list;
268         u64                     kernel_address;
269         dma_addr_t              bus_address;
270         u32                     mmap_size;
271         u32                     size;
272         u32                     id;
273         u32                     cs_cnt;
274         u32                     ctx_id;
275         u8                      mmap;
276         u8                      is_pool;
277 };
278
279
280 /*
281  * QUEUES
282  */
283
284 struct hl_cs_job;
285
286 /*
287  * Currently, there are two limitations on the maximum length of a queue:
288  *
289  * 1. The memory footprint of the queue. The current allocated space for the
290  *    queue is PAGE_SIZE. Because each entry in the queue is HL_BD_SIZE,
291  *    the maximum length of the queue can be PAGE_SIZE / HL_BD_SIZE,
292  *    which currently is 4096/16 = 256 entries.
293  *
294  *    To increase that, we need either to decrease the size of the
295  *    BD (difficult), or allocate more than a single page (easier).
296  *
297  * 2. Because the size of the JOB handle field in the BD CTL / completion queue
298  *    is 10-bit, we can have up to 1024 open jobs per hardware queue.
299  *    Therefore, each queue can hold up to 1024 entries.
300  *
301  * HL_QUEUE_LENGTH is in units of struct hl_bd.
302  * HL_QUEUE_LENGTH * sizeof(struct hl_bd) should be <= HL_PAGE_SIZE
303  */
304
305 #define HL_PAGE_SIZE                    4096 /* minimum page size */
306 /* Must be power of 2 (HL_PAGE_SIZE / HL_BD_SIZE) */
307 #define HL_QUEUE_LENGTH                 256
308 #define HL_QUEUE_SIZE_IN_BYTES          (HL_QUEUE_LENGTH * HL_BD_SIZE)
309
310 /*
311  * HL_CQ_LENGTH is in units of struct hl_cq_entry.
312  * HL_CQ_LENGTH should be <= HL_PAGE_SIZE
313  */
314 #define HL_CQ_LENGTH                    HL_QUEUE_LENGTH
315 #define HL_CQ_SIZE_IN_BYTES             (HL_CQ_LENGTH * HL_CQ_ENTRY_SIZE)
316
317 /* Must be power of 2 (HL_PAGE_SIZE / HL_EQ_ENTRY_SIZE) */
318 #define HL_EQ_LENGTH                    64
319 #define HL_EQ_SIZE_IN_BYTES             (HL_EQ_LENGTH * HL_EQ_ENTRY_SIZE)
320
321 #define HL_CPU_PKT_SHIFT                5
322 #define HL_CPU_PKT_SIZE                 (1 << HL_CPU_PKT_SHIFT)
323 #define HL_CPU_PKT_MASK                 (~((1 << HL_CPU_PKT_SHIFT) - 1))
324 #define HL_CPU_MAX_PKTS_IN_CB           32
325 #define HL_CPU_CB_SIZE                  (HL_CPU_PKT_SIZE * \
326                                          HL_CPU_MAX_PKTS_IN_CB)
327 #define HL_CPU_CB_QUEUE_SIZE            (HL_QUEUE_LENGTH * HL_CPU_CB_SIZE)
328
329 /* KMD <-> ArmCP shared memory size (EQ + PQ + CPU CB queue) */
330 #define HL_CPU_ACCESSIBLE_MEM_SIZE      (HL_EQ_SIZE_IN_BYTES + \
331                                          HL_QUEUE_SIZE_IN_BYTES + \
332                                          HL_CPU_CB_QUEUE_SIZE)
333
334 /**
335  * struct hl_hw_queue - describes a H/W transport queue.
336  * @shadow_queue: pointer to a shadow queue that holds pointers to jobs.
337  * @queue_type: type of queue.
338  * @kernel_address: holds the queue's kernel virtual address.
339  * @bus_address: holds the queue's DMA address.
340  * @pi: holds the queue's pi value.
341  * @ci: holds the queue's ci value, AS CALCULATED BY THE DRIVER (not real ci).
342  * @hw_queue_id: the id of the H/W queue.
343  * @int_queue_len: length of internal queue (number of entries).
344  * @valid: is the queue valid (we have array of 32 queues, not all of them
345  *              exists).
346  */
347 struct hl_hw_queue {
348         struct hl_cs_job        **shadow_queue;
349         enum hl_queue_type      queue_type;
350         u64                     kernel_address;
351         dma_addr_t              bus_address;
352         u32                     pi;
353         u32                     ci;
354         u32                     hw_queue_id;
355         u16                     int_queue_len;
356         u8                      valid;
357 };
358
359 /**
360  * struct hl_cq - describes a completion queue
361  * @hdev: pointer to the device structure
362  * @kernel_address: holds the queue's kernel virtual address
363  * @bus_address: holds the queue's DMA address
364  * @hw_queue_id: the id of the matching H/W queue
365  * @ci: ci inside the queue
366  * @pi: pi inside the queue
367  * @free_slots_cnt: counter of free slots in queue
368  */
369 struct hl_cq {
370         struct hl_device        *hdev;
371         u64                     kernel_address;
372         dma_addr_t              bus_address;
373         u32                     hw_queue_id;
374         u32                     ci;
375         u32                     pi;
376         atomic_t                free_slots_cnt;
377 };
378
379 /**
380  * struct hl_eq - describes the event queue (single one per device)
381  * @hdev: pointer to the device structure
382  * @kernel_address: holds the queue's kernel virtual address
383  * @bus_address: holds the queue's DMA address
384  * @ci: ci inside the queue
385  */
386 struct hl_eq {
387         struct hl_device        *hdev;
388         u64                     kernel_address;
389         dma_addr_t              bus_address;
390         u32                     ci;
391 };
392
393
394 /*
395  * ASICs
396  */
397
398 /**
399  * enum hl_asic_type - supported ASIC types.
400  * @ASIC_INVALID: Invalid ASIC type.
401  * @ASIC_GOYA: Goya device.
402  */
403 enum hl_asic_type {
404         ASIC_INVALID,
405         ASIC_GOYA
406 };
407
408 struct hl_cs_parser;
409
410 /**
411  * enum hl_pm_mng_profile - power management profile.
412  * @PM_AUTO: internal clock is set by KMD.
413  * @PM_MANUAL: internal clock is set by the user.
414  * @PM_LAST: last power management type.
415  */
416 enum hl_pm_mng_profile {
417         PM_AUTO = 1,
418         PM_MANUAL,
419         PM_LAST
420 };
421
422 /**
423  * enum hl_pll_frequency - PLL frequency.
424  * @PLL_HIGH: high frequency.
425  * @PLL_LOW: low frequency.
426  * @PLL_LAST: last frequency values that were configured by the user.
427  */
428 enum hl_pll_frequency {
429         PLL_HIGH = 1,
430         PLL_LOW,
431         PLL_LAST
432 };
433
434 /**
435  * struct hl_asic_funcs - ASIC specific functions that are can be called from
436  *                        common code.
437  * @early_init: sets up early driver state (pre sw_init), doesn't configure H/W.
438  * @early_fini: tears down what was done in early_init.
439  * @late_init: sets up late driver/hw state (post hw_init) - Optional.
440  * @late_fini: tears down what was done in late_init (pre hw_fini) - Optional.
441  * @sw_init: sets up driver state, does not configure H/W.
442  * @sw_fini: tears down driver state, does not configure H/W.
443  * @hw_init: sets up the H/W state.
444  * @hw_fini: tears down the H/W state.
445  * @halt_engines: halt engines, needed for reset sequence. This also disables
446  *                interrupts from the device. Should be called before
447  *                hw_fini and before CS rollback.
448  * @suspend: handles IP specific H/W or SW changes for suspend.
449  * @resume: handles IP specific H/W or SW changes for resume.
450  * @cb_mmap: maps a CB.
451  * @ring_doorbell: increment PI on a given QMAN.
452  * @flush_pq_write: flush PQ entry write if necessary, WARN if flushing failed.
453  * @asic_dma_alloc_coherent: Allocate coherent DMA memory by calling
454  *                           dma_alloc_coherent(). This is ASIC function because
455  *                           its implementation is not trivial when the driver
456  *                           is loaded in simulation mode (not upstreamed).
457  * @asic_dma_free_coherent:  Free coherent DMA memory by calling
458  *                           dma_free_coherent(). This is ASIC function because
459  *                           its implementation is not trivial when the driver
460  *                           is loaded in simulation mode (not upstreamed).
461  * @get_int_queue_base: get the internal queue base address.
462  * @test_queues: run simple test on all queues for sanity check.
463  * @asic_dma_pool_zalloc: small DMA allocation of coherent memory from DMA pool.
464  *                        size of allocation is HL_DMA_POOL_BLK_SIZE.
465  * @asic_dma_pool_free: free small DMA allocation from pool.
466  * @cpu_accessible_dma_pool_alloc: allocate CPU PQ packet from DMA pool.
467  * @cpu_accessible_dma_pool_free: free CPU PQ packet from DMA pool.
468  * @hl_dma_unmap_sg: DMA unmap scatter-gather list.
469  * @cs_parser: parse Command Submission.
470  * @asic_dma_map_sg: DMA map scatter-gather list.
471  * @get_dma_desc_list_size: get number of LIN_DMA packets required for CB.
472  * @add_end_of_cb_packets: Add packets to the end of CB, if device requires it.
473  * @update_eq_ci: update event queue CI.
474  * @context_switch: called upon ASID context switch.
475  * @restore_phase_topology: clear all SOBs amd MONs.
476  * @debugfs_read32: debug interface for reading u32 from DRAM/SRAM.
477  * @debugfs_write32: debug interface for writing u32 to DRAM/SRAM.
478  * @add_device_attr: add ASIC specific device attributes.
479  * @handle_eqe: handle event queue entry (IRQ) from ArmCP.
480  * @set_pll_profile: change PLL profile (manual/automatic).
481  * @get_events_stat: retrieve event queue entries histogram.
482  * @read_pte: read MMU page table entry from DRAM.
483  * @write_pte: write MMU page table entry to DRAM.
484  * @mmu_invalidate_cache: flush MMU STLB cache, either with soft (L1 only) or
485  *                        hard (L0 & L1) flush.
486  * @mmu_invalidate_cache_range: flush specific MMU STLB cache lines with
487  *                              ASID-VA-size mask.
488  * @send_heartbeat: send is-alive packet to ArmCP and verify response.
489  * @debug_coresight: perform certain actions on Coresight for debugging.
490  * @is_device_idle: return true if device is idle, false otherwise.
491  * @soft_reset_late_init: perform certain actions needed after soft reset.
492  * @hw_queues_lock: acquire H/W queues lock.
493  * @hw_queues_unlock: release H/W queues lock.
494  * @get_pci_id: retrieve PCI ID.
495  * @get_eeprom_data: retrieve EEPROM data from F/W.
496  * @send_cpu_message: send buffer to ArmCP.
497  * @get_hw_state: retrieve the H/W state
498  * @pci_bars_map: Map PCI BARs.
499  * @set_dram_bar_base: Set DRAM BAR to map specific device address. Returns
500  *                     old address the bar pointed to or U64_MAX for failure
501  * @init_iatu: Initialize the iATU unit inside the PCI controller.
502  * @rreg: Read a register. Needed for simulator support.
503  * @wreg: Write a register. Needed for simulator support.
504  */
505 struct hl_asic_funcs {
506         int (*early_init)(struct hl_device *hdev);
507         int (*early_fini)(struct hl_device *hdev);
508         int (*late_init)(struct hl_device *hdev);
509         void (*late_fini)(struct hl_device *hdev);
510         int (*sw_init)(struct hl_device *hdev);
511         int (*sw_fini)(struct hl_device *hdev);
512         int (*hw_init)(struct hl_device *hdev);
513         void (*hw_fini)(struct hl_device *hdev, bool hard_reset);
514         void (*halt_engines)(struct hl_device *hdev, bool hard_reset);
515         int (*suspend)(struct hl_device *hdev);
516         int (*resume)(struct hl_device *hdev);
517         int (*cb_mmap)(struct hl_device *hdev, struct vm_area_struct *vma,
518                         u64 kaddress, phys_addr_t paddress, u32 size);
519         void (*ring_doorbell)(struct hl_device *hdev, u32 hw_queue_id, u32 pi);
520         void (*flush_pq_write)(struct hl_device *hdev, u64 *pq, u64 exp_val);
521         void* (*asic_dma_alloc_coherent)(struct hl_device *hdev, size_t size,
522                                         dma_addr_t *dma_handle, gfp_t flag);
523         void (*asic_dma_free_coherent)(struct hl_device *hdev, size_t size,
524                                         void *cpu_addr, dma_addr_t dma_handle);
525         void* (*get_int_queue_base)(struct hl_device *hdev, u32 queue_id,
526                                 dma_addr_t *dma_handle, u16 *queue_len);
527         int (*test_queues)(struct hl_device *hdev);
528         void* (*asic_dma_pool_zalloc)(struct hl_device *hdev, size_t size,
529                                 gfp_t mem_flags, dma_addr_t *dma_handle);
530         void (*asic_dma_pool_free)(struct hl_device *hdev, void *vaddr,
531                                 dma_addr_t dma_addr);
532         void* (*cpu_accessible_dma_pool_alloc)(struct hl_device *hdev,
533                                 size_t size, dma_addr_t *dma_handle);
534         void (*cpu_accessible_dma_pool_free)(struct hl_device *hdev,
535                                 size_t size, void *vaddr);
536         void (*hl_dma_unmap_sg)(struct hl_device *hdev,
537                                 struct scatterlist *sgl, int nents,
538                                 enum dma_data_direction dir);
539         int (*cs_parser)(struct hl_device *hdev, struct hl_cs_parser *parser);
540         int (*asic_dma_map_sg)(struct hl_device *hdev,
541                                 struct scatterlist *sgl, int nents,
542                                 enum dma_data_direction dir);
543         u32 (*get_dma_desc_list_size)(struct hl_device *hdev,
544                                         struct sg_table *sgt);
545         void (*add_end_of_cb_packets)(u64 kernel_address, u32 len, u64 cq_addr,
546                                         u32 cq_val, u32 msix_num);
547         void (*update_eq_ci)(struct hl_device *hdev, u32 val);
548         int (*context_switch)(struct hl_device *hdev, u32 asid);
549         void (*restore_phase_topology)(struct hl_device *hdev);
550         int (*debugfs_read32)(struct hl_device *hdev, u64 addr, u32 *val);
551         int (*debugfs_write32)(struct hl_device *hdev, u64 addr, u32 val);
552         void (*add_device_attr)(struct hl_device *hdev,
553                                 struct attribute_group *dev_attr_grp);
554         void (*handle_eqe)(struct hl_device *hdev,
555                                 struct hl_eq_entry *eq_entry);
556         void (*set_pll_profile)(struct hl_device *hdev,
557                         enum hl_pll_frequency freq);
558         void* (*get_events_stat)(struct hl_device *hdev, u32 *size);
559         u64 (*read_pte)(struct hl_device *hdev, u64 addr);
560         void (*write_pte)(struct hl_device *hdev, u64 addr, u64 val);
561         void (*mmu_invalidate_cache)(struct hl_device *hdev, bool is_hard);
562         void (*mmu_invalidate_cache_range)(struct hl_device *hdev, bool is_hard,
563                         u32 asid, u64 va, u64 size);
564         int (*send_heartbeat)(struct hl_device *hdev);
565         int (*debug_coresight)(struct hl_device *hdev, void *data);
566         bool (*is_device_idle)(struct hl_device *hdev, char *buf, size_t size);
567         int (*soft_reset_late_init)(struct hl_device *hdev);
568         void (*hw_queues_lock)(struct hl_device *hdev);
569         void (*hw_queues_unlock)(struct hl_device *hdev);
570         u32 (*get_pci_id)(struct hl_device *hdev);
571         int (*get_eeprom_data)(struct hl_device *hdev, void *data,
572                                 size_t max_size);
573         int (*send_cpu_message)(struct hl_device *hdev, u32 *msg,
574                                 u16 len, u32 timeout, long *result);
575         enum hl_device_hw_state (*get_hw_state)(struct hl_device *hdev);
576         int (*pci_bars_map)(struct hl_device *hdev);
577         u64 (*set_dram_bar_base)(struct hl_device *hdev, u64 addr);
578         int (*init_iatu)(struct hl_device *hdev);
579         u32 (*rreg)(struct hl_device *hdev, u32 reg);
580         void (*wreg)(struct hl_device *hdev, u32 reg, u32 val);
581 };
582
583
584 /*
585  * CONTEXTS
586  */
587
588 #define HL_KERNEL_ASID_ID       0
589
590 /**
591  * struct hl_va_range - virtual addresses range.
592  * @lock: protects the virtual addresses list.
593  * @list: list of virtual addresses blocks available for mappings.
594  * @start_addr: range start address.
595  * @end_addr: range end address.
596  */
597 struct hl_va_range {
598         struct mutex            lock;
599         struct list_head        list;
600         u64                     start_addr;
601         u64                     end_addr;
602 };
603
604 /**
605  * struct hl_ctx - user/kernel context.
606  * @mem_hash: holds mapping from virtual address to virtual memory area
607  *              descriptor (hl_vm_phys_pg_list or hl_userptr).
608  * @mmu_phys_hash: holds a mapping from physical address to pgt_info structure.
609  * @mmu_shadow_hash: holds a mapping from shadow address to pgt_info structure.
610  * @hpriv: pointer to the private (KMD) data of the process (fd).
611  * @hdev: pointer to the device structure.
612  * @refcount: reference counter for the context. Context is released only when
613  *              this hits 0l. It is incremented on CS and CS_WAIT.
614  * @cs_pending: array of DMA fence objects representing pending CS.
615  * @host_va_range: holds available virtual addresses for host mappings.
616  * @dram_va_range: holds available virtual addresses for DRAM mappings.
617  * @mem_hash_lock: protects the mem_hash.
618  * @mmu_lock: protects the MMU page tables. Any change to the PGT, modifing the
619  *            MMU hash or walking the PGT requires talking this lock
620  * @debugfs_list: node in debugfs list of contexts.
621  * @cs_sequence: sequence number for CS. Value is assigned to a CS and passed
622  *                      to user so user could inquire about CS. It is used as
623  *                      index to cs_pending array.
624  * @dram_default_hops: array that holds all hops addresses needed for default
625  *                     DRAM mapping.
626  * @cs_lock: spinlock to protect cs_sequence.
627  * @dram_phys_mem: amount of used physical DRAM memory by this context.
628  * @thread_ctx_switch_token: token to prevent multiple threads of the same
629  *                              context from running the context switch phase.
630  *                              Only a single thread should run it.
631  * @thread_ctx_switch_wait_token: token to prevent the threads that didn't run
632  *                              the context switch phase from moving to their
633  *                              execution phase before the context switch phase
634  *                              has finished.
635  * @asid: context's unique address space ID in the device's MMU.
636  */
637 struct hl_ctx {
638         DECLARE_HASHTABLE(mem_hash, MEM_HASH_TABLE_BITS);
639         DECLARE_HASHTABLE(mmu_phys_hash, MMU_HASH_TABLE_BITS);
640         DECLARE_HASHTABLE(mmu_shadow_hash, MMU_HASH_TABLE_BITS);
641         struct hl_fpriv         *hpriv;
642         struct hl_device        *hdev;
643         struct kref             refcount;
644         struct dma_fence        *cs_pending[HL_MAX_PENDING_CS];
645         struct hl_va_range      host_va_range;
646         struct hl_va_range      dram_va_range;
647         struct mutex            mem_hash_lock;
648         struct mutex            mmu_lock;
649         struct list_head        debugfs_list;
650         u64                     cs_sequence;
651         u64                     *dram_default_hops;
652         spinlock_t              cs_lock;
653         atomic64_t              dram_phys_mem;
654         atomic_t                thread_ctx_switch_token;
655         u32                     thread_ctx_switch_wait_token;
656         u32                     asid;
657 };
658
659 /**
660  * struct hl_ctx_mgr - for handling multiple contexts.
661  * @ctx_lock: protects ctx_handles.
662  * @ctx_handles: idr to hold all ctx handles.
663  */
664 struct hl_ctx_mgr {
665         struct mutex            ctx_lock;
666         struct idr              ctx_handles;
667 };
668
669
670
671 /*
672  * COMMAND SUBMISSIONS
673  */
674
675 /**
676  * struct hl_userptr - memory mapping chunk information
677  * @vm_type: type of the VM.
678  * @job_node: linked-list node for hanging the object on the Job's list.
679  * @vec: pointer to the frame vector.
680  * @sgt: pointer to the scatter-gather table that holds the pages.
681  * @dir: for DMA unmapping, the direction must be supplied, so save it.
682  * @debugfs_list: node in debugfs list of command submissions.
683  * @addr: user-space virtual pointer to the start of the memory area.
684  * @size: size of the memory area to pin & map.
685  * @dma_mapped: true if the SG was mapped to DMA addresses, false otherwise.
686  */
687 struct hl_userptr {
688         enum vm_type_t          vm_type; /* must be first */
689         struct list_head        job_node;
690         struct frame_vector     *vec;
691         struct sg_table         *sgt;
692         enum dma_data_direction dir;
693         struct list_head        debugfs_list;
694         u64                     addr;
695         u32                     size;
696         u8                      dma_mapped;
697 };
698
699 /**
700  * struct hl_cs - command submission.
701  * @jobs_in_queue_cnt: per each queue, maintain counter of submitted jobs.
702  * @ctx: the context this CS belongs to.
703  * @job_list: list of the CS's jobs in the various queues.
704  * @job_lock: spinlock for the CS's jobs list. Needed for free_job.
705  * @refcount: reference counter for usage of the CS.
706  * @fence: pointer to the fence object of this CS.
707  * @work_tdr: delayed work node for TDR.
708  * @mirror_node : node in device mirror list of command submissions.
709  * @debugfs_list: node in debugfs list of command submissions.
710  * @sequence: the sequence number of this CS.
711  * @submitted: true if CS was submitted to H/W.
712  * @completed: true if CS was completed by device.
713  * @timedout : true if CS was timedout.
714  * @tdr_active: true if TDR was activated for this CS (to prevent
715  *              double TDR activation).
716  * @aborted: true if CS was aborted due to some device error.
717  */
718 struct hl_cs {
719         u8                      jobs_in_queue_cnt[HL_MAX_QUEUES];
720         struct hl_ctx           *ctx;
721         struct list_head        job_list;
722         spinlock_t              job_lock;
723         struct kref             refcount;
724         struct dma_fence        *fence;
725         struct delayed_work     work_tdr;
726         struct list_head        mirror_node;
727         struct list_head        debugfs_list;
728         u64                     sequence;
729         u8                      submitted;
730         u8                      completed;
731         u8                      timedout;
732         u8                      tdr_active;
733         u8                      aborted;
734 };
735
736 /**
737  * struct hl_cs_job - command submission job.
738  * @cs_node: the node to hang on the CS jobs list.
739  * @cs: the CS this job belongs to.
740  * @user_cb: the CB we got from the user.
741  * @patched_cb: in case of patching, this is internal CB which is submitted on
742  *              the queue instead of the CB we got from the IOCTL.
743  * @finish_work: workqueue object to run when job is completed.
744  * @userptr_list: linked-list of userptr mappings that belong to this job and
745  *                      wait for completion.
746  * @debugfs_list: node in debugfs list of command submission jobs.
747  * @id: the id of this job inside a CS.
748  * @hw_queue_id: the id of the H/W queue this job is submitted to.
749  * @user_cb_size: the actual size of the CB we got from the user.
750  * @job_cb_size: the actual size of the CB that we put on the queue.
751  * @ext_queue: whether the job is for external queue or internal queue.
752  */
753 struct hl_cs_job {
754         struct list_head        cs_node;
755         struct hl_cs            *cs;
756         struct hl_cb            *user_cb;
757         struct hl_cb            *patched_cb;
758         struct work_struct      finish_work;
759         struct list_head        userptr_list;
760         struct list_head        debugfs_list;
761         u32                     id;
762         u32                     hw_queue_id;
763         u32                     user_cb_size;
764         u32                     job_cb_size;
765         u8                      ext_queue;
766 };
767
768 /**
769  * struct hl_cs_parser - command submission paerser properties.
770  * @user_cb: the CB we got from the user.
771  * @patched_cb: in case of patching, this is internal CB which is submitted on
772  *              the queue instead of the CB we got from the IOCTL.
773  * @job_userptr_list: linked-list of userptr mappings that belong to the related
774  *                      job and wait for completion.
775  * @cs_sequence: the sequence number of the related CS.
776  * @ctx_id: the ID of the context the related CS belongs to.
777  * @hw_queue_id: the id of the H/W queue this job is submitted to.
778  * @user_cb_size: the actual size of the CB we got from the user.
779  * @patched_cb_size: the size of the CB after parsing.
780  * @ext_queue: whether the job is for external queue or internal queue.
781  * @job_id: the id of the related job inside the related CS.
782  */
783 struct hl_cs_parser {
784         struct hl_cb            *user_cb;
785         struct hl_cb            *patched_cb;
786         struct list_head        *job_userptr_list;
787         u64                     cs_sequence;
788         u32                     ctx_id;
789         u32                     hw_queue_id;
790         u32                     user_cb_size;
791         u32                     patched_cb_size;
792         u8                      ext_queue;
793         u8                      job_id;
794 };
795
796
797 /*
798  * MEMORY STRUCTURE
799  */
800
801 /**
802  * struct hl_vm_hash_node - hash element from virtual address to virtual
803  *                              memory area descriptor (hl_vm_phys_pg_list or
804  *                              hl_userptr).
805  * @node: node to hang on the hash table in context object.
806  * @vaddr: key virtual address.
807  * @ptr: value pointer (hl_vm_phys_pg_list or hl_userptr).
808  */
809 struct hl_vm_hash_node {
810         struct hlist_node       node;
811         u64                     vaddr;
812         void                    *ptr;
813 };
814
815 /**
816  * struct hl_vm_phys_pg_pack - physical page pack.
817  * @vm_type: describes the type of the virtual area descriptor.
818  * @pages: the physical page array.
819  * @npages: num physical pages in the pack.
820  * @total_size: total size of all the pages in this list.
821  * @mapping_cnt: number of shared mappings.
822  * @asid: the context related to this list.
823  * @page_size: size of each page in the pack.
824  * @flags: HL_MEM_* flags related to this list.
825  * @handle: the provided handle related to this list.
826  * @offset: offset from the first page.
827  * @contiguous: is contiguous physical memory.
828  * @created_from_userptr: is product of host virtual address.
829  */
830 struct hl_vm_phys_pg_pack {
831         enum vm_type_t          vm_type; /* must be first */
832         u64                     *pages;
833         u64                     npages;
834         u64                     total_size;
835         atomic_t                mapping_cnt;
836         u32                     asid;
837         u32                     page_size;
838         u32                     flags;
839         u32                     handle;
840         u32                     offset;
841         u8                      contiguous;
842         u8                      created_from_userptr;
843 };
844
845 /**
846  * struct hl_vm_va_block - virtual range block information.
847  * @node: node to hang on the virtual range list in context object.
848  * @start: virtual range start address.
849  * @end: virtual range end address.
850  * @size: virtual range size.
851  */
852 struct hl_vm_va_block {
853         struct list_head        node;
854         u64                     start;
855         u64                     end;
856         u64                     size;
857 };
858
859 /**
860  * struct hl_vm - virtual memory manager for MMU.
861  * @dram_pg_pool: pool for DRAM physical pages of 2MB.
862  * @dram_pg_pool_refcount: reference counter for the pool usage.
863  * @idr_lock: protects the phys_pg_list_handles.
864  * @phys_pg_pack_handles: idr to hold all device allocations handles.
865  * @init_done: whether initialization was done. We need this because VM
866  *              initialization might be skipped during device initialization.
867  */
868 struct hl_vm {
869         struct gen_pool         *dram_pg_pool;
870         struct kref             dram_pg_pool_refcount;
871         spinlock_t              idr_lock;
872         struct idr              phys_pg_pack_handles;
873         u8                      init_done;
874 };
875
876
877 /*
878  * DEBUG, PROFILING STRUCTURE
879  */
880
881 /**
882  * struct hl_debug_params - Coresight debug parameters.
883  * @input: pointer to component specific input parameters.
884  * @output: pointer to component specific output parameters.
885  * @output_size: size of output buffer.
886  * @reg_idx: relevant register ID.
887  * @op: component operation to execute.
888  * @enable: true if to enable component debugging, false otherwise.
889  */
890 struct hl_debug_params {
891         void *input;
892         void *output;
893         u32 output_size;
894         u32 reg_idx;
895         u32 op;
896         bool enable;
897 };
898
899 /*
900  * FILE PRIVATE STRUCTURE
901  */
902
903 /**
904  * struct hl_fpriv - process information stored in FD private data.
905  * @hdev: habanalabs device structure.
906  * @filp: pointer to the given file structure.
907  * @taskpid: current process ID.
908  * @ctx: current executing context.
909  * @ctx_mgr: context manager to handle multiple context for this FD.
910  * @cb_mgr: command buffer manager to handle multiple buffers for this FD.
911  * @debugfs_list: list of relevant ASIC debugfs.
912  * @refcount: number of related contexts.
913  * @restore_phase_mutex: lock for context switch and restore phase.
914  */
915 struct hl_fpriv {
916         struct hl_device        *hdev;
917         struct file             *filp;
918         struct pid              *taskpid;
919         struct hl_ctx           *ctx; /* TODO: remove for multiple ctx */
920         struct hl_ctx_mgr       ctx_mgr;
921         struct hl_cb_mgr        cb_mgr;
922         struct list_head        debugfs_list;
923         struct kref             refcount;
924         struct mutex            restore_phase_mutex;
925 };
926
927
928 /*
929  * DebugFS
930  */
931
932 /**
933  * struct hl_info_list - debugfs file ops.
934  * @name: file name.
935  * @show: function to output information.
936  * @write: function to write to the file.
937  */
938 struct hl_info_list {
939         const char      *name;
940         int             (*show)(struct seq_file *s, void *data);
941         ssize_t         (*write)(struct file *file, const char __user *buf,
942                                 size_t count, loff_t *f_pos);
943 };
944
945 /**
946  * struct hl_debugfs_entry - debugfs dentry wrapper.
947  * @dent: base debugfs entry structure.
948  * @info_ent: dentry realted ops.
949  * @dev_entry: ASIC specific debugfs manager.
950  */
951 struct hl_debugfs_entry {
952         struct dentry                   *dent;
953         const struct hl_info_list       *info_ent;
954         struct hl_dbg_device_entry      *dev_entry;
955 };
956
957 /**
958  * struct hl_dbg_device_entry - ASIC specific debugfs manager.
959  * @root: root dentry.
960  * @hdev: habanalabs device structure.
961  * @entry_arr: array of available hl_debugfs_entry.
962  * @file_list: list of available debugfs files.
963  * @file_mutex: protects file_list.
964  * @cb_list: list of available CBs.
965  * @cb_spinlock: protects cb_list.
966  * @cs_list: list of available CSs.
967  * @cs_spinlock: protects cs_list.
968  * @cs_job_list: list of available CB jobs.
969  * @cs_job_spinlock: protects cs_job_list.
970  * @userptr_list: list of available userptrs (virtual memory chunk descriptor).
971  * @userptr_spinlock: protects userptr_list.
972  * @ctx_mem_hash_list: list of available contexts with MMU mappings.
973  * @ctx_mem_hash_spinlock: protects cb_list.
974  * @addr: next address to read/write from/to in read/write32.
975  * @mmu_addr: next virtual address to translate to physical address in mmu_show.
976  * @mmu_asid: ASID to use while translating in mmu_show.
977  * @i2c_bus: generic u8 debugfs file for bus value to use in i2c_data_read.
978  * @i2c_bus: generic u8 debugfs file for address value to use in i2c_data_read.
979  * @i2c_bus: generic u8 debugfs file for register value to use in i2c_data_read.
980  */
981 struct hl_dbg_device_entry {
982         struct dentry                   *root;
983         struct hl_device                *hdev;
984         struct hl_debugfs_entry         *entry_arr;
985         struct list_head                file_list;
986         struct mutex                    file_mutex;
987         struct list_head                cb_list;
988         spinlock_t                      cb_spinlock;
989         struct list_head                cs_list;
990         spinlock_t                      cs_spinlock;
991         struct list_head                cs_job_list;
992         spinlock_t                      cs_job_spinlock;
993         struct list_head                userptr_list;
994         spinlock_t                      userptr_spinlock;
995         struct list_head                ctx_mem_hash_list;
996         spinlock_t                      ctx_mem_hash_spinlock;
997         u64                             addr;
998         u64                             mmu_addr;
999         u32                             mmu_asid;
1000         u8                              i2c_bus;
1001         u8                              i2c_addr;
1002         u8                              i2c_reg;
1003 };
1004
1005
1006 /*
1007  * DEVICES
1008  */
1009
1010 /* Theoretical limit only. A single host can only contain up to 4 or 8 PCIe
1011  * x16 cards. In extereme cases, there are hosts that can accommodate 16 cards
1012  */
1013 #define HL_MAX_MINORS   256
1014
1015 /*
1016  * Registers read & write functions.
1017  */
1018
1019 u32 hl_rreg(struct hl_device *hdev, u32 reg);
1020 void hl_wreg(struct hl_device *hdev, u32 reg, u32 val);
1021
1022 #define RREG32(reg) hdev->asic_funcs->rreg(hdev, (reg))
1023 #define WREG32(reg, v) hdev->asic_funcs->wreg(hdev, (reg), (v))
1024 #define DREG32(reg) pr_info("REGISTER: " #reg " : 0x%08X\n",    \
1025                         hdev->asic_funcs->rreg(hdev, (reg)))
1026
1027 #define WREG32_P(reg, val, mask)                                \
1028         do {                                                    \
1029                 u32 tmp_ = RREG32(reg);                         \
1030                 tmp_ &= (mask);                                 \
1031                 tmp_ |= ((val) & ~(mask));                      \
1032                 WREG32(reg, tmp_);                              \
1033         } while (0)
1034 #define WREG32_AND(reg, and) WREG32_P(reg, 0, and)
1035 #define WREG32_OR(reg, or) WREG32_P(reg, or, ~(or))
1036
1037 #define REG_FIELD_SHIFT(reg, field) reg##_##field##_SHIFT
1038 #define REG_FIELD_MASK(reg, field) reg##_##field##_MASK
1039 #define WREG32_FIELD(reg, field, val)   \
1040         WREG32(mm##reg, (RREG32(mm##reg) & ~REG_FIELD_MASK(reg, field)) | \
1041                         (val) << REG_FIELD_SHIFT(reg, field))
1042
1043 #define hl_poll_timeout(hdev, addr, val, cond, sleep_us, timeout_us) \
1044 ({ \
1045         ktime_t __timeout; \
1046         /* timeout should be longer when working with simulator */ \
1047         if (hdev->pdev) \
1048                 __timeout = ktime_add_us(ktime_get(), timeout_us); \
1049         else \
1050                 __timeout = ktime_add_us(ktime_get(), (timeout_us * 10)); \
1051         might_sleep_if(sleep_us); \
1052         for (;;) { \
1053                 (val) = RREG32(addr); \
1054                 if (cond) \
1055                         break; \
1056                 if (timeout_us && ktime_compare(ktime_get(), __timeout) > 0) { \
1057                         (val) = RREG32(addr); \
1058                         break; \
1059                 } \
1060                 if (sleep_us) \
1061                         usleep_range((sleep_us >> 2) + 1, sleep_us); \
1062         } \
1063         (cond) ? 0 : -ETIMEDOUT; \
1064 })
1065
1066
1067 #define HL_ENG_BUSY(buf, size, fmt, ...) ({ \
1068                 if (buf) \
1069                         snprintf(buf, size, fmt, ##__VA_ARGS__); \
1070                 false; \
1071         })
1072
1073 struct hwmon_chip_info;
1074
1075 /**
1076  * struct hl_device_reset_work - reset workqueue task wrapper.
1077  * @reset_work: reset work to be done.
1078  * @hdev: habanalabs device structure.
1079  */
1080 struct hl_device_reset_work {
1081         struct work_struct              reset_work;
1082         struct hl_device                *hdev;
1083 };
1084
1085 /**
1086  * struct hl_device - habanalabs device structure.
1087  * @pdev: pointer to PCI device, can be NULL in case of simulator device.
1088  * @pcie_bar: array of available PCIe bars.
1089  * @rmmio: configuration area address on SRAM.
1090  * @cdev: related char device.
1091  * @dev: realted kernel basic device structure.
1092  * @work_freq: delayed work to lower device frequency if possible.
1093  * @work_heartbeat: delayed work for ArmCP is-alive check.
1094  * @asic_name: ASIC specific nmae.
1095  * @asic_type: ASIC specific type.
1096  * @completion_queue: array of hl_cq.
1097  * @cq_wq: work queue of completion queues for executing work in process context
1098  * @eq_wq: work queue of event queue for executing work in process context.
1099  * @kernel_ctx: KMD context structure.
1100  * @kernel_queues: array of hl_hw_queue.
1101  * @hw_queues_mirror_list: CS mirror list for TDR.
1102  * @hw_queues_mirror_lock: protects hw_queues_mirror_list.
1103  * @kernel_cb_mgr: command buffer manager for creating/destroying/handling CGs.
1104  * @event_queue: event queue for IRQ from ArmCP.
1105  * @dma_pool: DMA pool for small allocations.
1106  * @cpu_accessible_dma_mem: KMD <-> ArmCP shared memory CPU address.
1107  * @cpu_accessible_dma_address: KMD <-> ArmCP shared memory DMA address.
1108  * @cpu_accessible_dma_pool: KMD <-> ArmCP shared memory pool.
1109  * @asid_bitmap: holds used/available ASIDs.
1110  * @asid_mutex: protects asid_bitmap.
1111  * @fd_open_cnt_lock: lock for updating fd_open_cnt in hl_device_open. Although
1112  *                    fd_open_cnt is atomic, we need this lock to serialize
1113  *                    the open function because the driver currently supports
1114  *                    only a single process at a time. In addition, we need a
1115  *                    lock here so we can flush user processes which are opening
1116  *                    the device while we are trying to hard reset it
1117  * @send_cpu_message_lock: enforces only one message in KMD <-> ArmCP queue.
1118  * @asic_prop: ASIC specific immutable properties.
1119  * @asic_funcs: ASIC specific functions.
1120  * @asic_specific: ASIC specific information to use only from ASIC files.
1121  * @mmu_pgt_pool: pool of available MMU hops.
1122  * @vm: virtual memory manager for MMU.
1123  * @mmu_cache_lock: protects MMU cache invalidation as it can serve one context.
1124  * @mmu_shadow_hop0: shadow mapping of the MMU hop 0 zone.
1125  * @hwmon_dev: H/W monitor device.
1126  * @pm_mng_profile: current power management profile.
1127  * @hl_chip_info: ASIC's sensors information.
1128  * @hl_debugfs: device's debugfs manager.
1129  * @cb_pool: list of preallocated CBs.
1130  * @cb_pool_lock: protects the CB pool.
1131  * @user_ctx: current user context executing.
1132  * @dram_used_mem: current DRAM memory consumption.
1133  * @timeout_jiffies: device CS timeout value.
1134  * @max_power: the max power of the device, as configured by the sysadmin. This
1135  *             value is saved so in case of hard-reset, KMD will restore this
1136  *             value and update the F/W after the re-initialization
1137  * @in_reset: is device in reset flow.
1138  * @curr_pll_profile: current PLL profile.
1139  * @fd_open_cnt: number of open user processes.
1140  * @cs_active_cnt: number of active command submissions on this device (active
1141  *                 means already in H/W queues)
1142  * @major: habanalabs KMD major.
1143  * @high_pll: high PLL profile frequency.
1144  * @soft_reset_cnt: number of soft reset since KMD loading.
1145  * @hard_reset_cnt: number of hard reset since KMD loading.
1146  * @id: device minor.
1147  * @disabled: is device disabled.
1148  * @late_init_done: is late init stage was done during initialization.
1149  * @hwmon_initialized: is H/W monitor sensors was initialized.
1150  * @hard_reset_pending: is there a hard reset work pending.
1151  * @heartbeat: is heartbeat sanity check towards ArmCP enabled.
1152  * @reset_on_lockup: true if a reset should be done in case of stuck CS, false
1153  *                   otherwise.
1154  * @dram_supports_virtual_memory: is MMU enabled towards DRAM.
1155  * @dram_default_page_mapping: is DRAM default page mapping enabled.
1156  * @init_done: is the initialization of the device done.
1157  * @mmu_enable: is MMU enabled.
1158  * @device_cpu_disabled: is the device CPU disabled (due to timeouts)
1159  * @dma_mask: the dma mask that was set for this device
1160  */
1161 struct hl_device {
1162         struct pci_dev                  *pdev;
1163         void __iomem                    *pcie_bar[6];
1164         void __iomem                    *rmmio;
1165         struct cdev                     cdev;
1166         struct device                   *dev;
1167         struct delayed_work             work_freq;
1168         struct delayed_work             work_heartbeat;
1169         char                            asic_name[16];
1170         enum hl_asic_type               asic_type;
1171         struct hl_cq                    *completion_queue;
1172         struct workqueue_struct         *cq_wq;
1173         struct workqueue_struct         *eq_wq;
1174         struct hl_ctx                   *kernel_ctx;
1175         struct hl_hw_queue              *kernel_queues;
1176         struct list_head                hw_queues_mirror_list;
1177         spinlock_t                      hw_queues_mirror_lock;
1178         struct hl_cb_mgr                kernel_cb_mgr;
1179         struct hl_eq                    event_queue;
1180         struct dma_pool                 *dma_pool;
1181         void                            *cpu_accessible_dma_mem;
1182         dma_addr_t                      cpu_accessible_dma_address;
1183         struct gen_pool                 *cpu_accessible_dma_pool;
1184         unsigned long                   *asid_bitmap;
1185         struct mutex                    asid_mutex;
1186         /* TODO: remove fd_open_cnt_lock for multiple process support */
1187         struct mutex                    fd_open_cnt_lock;
1188         struct mutex                    send_cpu_message_lock;
1189         struct asic_fixed_properties    asic_prop;
1190         const struct hl_asic_funcs      *asic_funcs;
1191         void                            *asic_specific;
1192         struct gen_pool                 *mmu_pgt_pool;
1193         struct hl_vm                    vm;
1194         struct mutex                    mmu_cache_lock;
1195         void                            *mmu_shadow_hop0;
1196         struct device                   *hwmon_dev;
1197         enum hl_pm_mng_profile          pm_mng_profile;
1198         struct hwmon_chip_info          *hl_chip_info;
1199
1200         struct hl_dbg_device_entry      hl_debugfs;
1201
1202         struct list_head                cb_pool;
1203         spinlock_t                      cb_pool_lock;
1204
1205         /* TODO: remove user_ctx for multiple process support */
1206         struct hl_ctx                   *user_ctx;
1207
1208         atomic64_t                      dram_used_mem;
1209         u64                             timeout_jiffies;
1210         u64                             max_power;
1211         atomic_t                        in_reset;
1212         atomic_t                        curr_pll_profile;
1213         atomic_t                        fd_open_cnt;
1214         atomic_t                        cs_active_cnt;
1215         u32                             major;
1216         u32                             high_pll;
1217         u32                             soft_reset_cnt;
1218         u32                             hard_reset_cnt;
1219         u16                             id;
1220         u8                              disabled;
1221         u8                              late_init_done;
1222         u8                              hwmon_initialized;
1223         u8                              hard_reset_pending;
1224         u8                              heartbeat;
1225         u8                              reset_on_lockup;
1226         u8                              dram_supports_virtual_memory;
1227         u8                              dram_default_page_mapping;
1228         u8                              init_done;
1229         u8                              device_cpu_disabled;
1230         u8                              dma_mask;
1231
1232         /* Parameters for bring-up */
1233         u8                              mmu_enable;
1234         u8                              cpu_enable;
1235         u8                              reset_pcilink;
1236         u8                              cpu_queues_enable;
1237         u8                              fw_loading;
1238         u8                              pldm;
1239 };
1240
1241
1242 /*
1243  * IOCTLs
1244  */
1245
1246 /**
1247  * typedef hl_ioctl_t - typedef for ioctl function in the driver
1248  * @hpriv: pointer to the FD's private data, which contains state of
1249  *              user process
1250  * @data: pointer to the input/output arguments structure of the IOCTL
1251  *
1252  * Return: 0 for success, negative value for error
1253  */
1254 typedef int hl_ioctl_t(struct hl_fpriv *hpriv, void *data);
1255
1256 /**
1257  * struct hl_ioctl_desc - describes an IOCTL entry of the driver.
1258  * @cmd: the IOCTL code as created by the kernel macros.
1259  * @func: pointer to the driver's function that should be called for this IOCTL.
1260  */
1261 struct hl_ioctl_desc {
1262         unsigned int cmd;
1263         hl_ioctl_t *func;
1264 };
1265
1266
1267 /*
1268  * Kernel module functions that can be accessed by entire module
1269  */
1270
1271 /**
1272  * hl_mem_area_inside_range() - Checks whether address+size are inside a range.
1273  * @address: The start address of the area we want to validate.
1274  * @size: The size in bytes of the area we want to validate.
1275  * @range_start_address: The start address of the valid range.
1276  * @range_end_address: The end address of the valid range.
1277  *
1278  * Return: true if the area is inside the valid range, false otherwise.
1279  */
1280 static inline bool hl_mem_area_inside_range(u64 address, u32 size,
1281                                 u64 range_start_address, u64 range_end_address)
1282 {
1283         u64 end_address = address + size;
1284
1285         if ((address >= range_start_address) &&
1286                         (end_address <= range_end_address) &&
1287                         (end_address > address))
1288                 return true;
1289
1290         return false;
1291 }
1292
1293 /**
1294  * hl_mem_area_crosses_range() - Checks whether address+size crossing a range.
1295  * @address: The start address of the area we want to validate.
1296  * @size: The size in bytes of the area we want to validate.
1297  * @range_start_address: The start address of the valid range.
1298  * @range_end_address: The end address of the valid range.
1299  *
1300  * Return: true if the area overlaps part or all of the valid range,
1301  *              false otherwise.
1302  */
1303 static inline bool hl_mem_area_crosses_range(u64 address, u32 size,
1304                                 u64 range_start_address, u64 range_end_address)
1305 {
1306         u64 end_address = address + size;
1307
1308         if ((address >= range_start_address) &&
1309                         (address < range_end_address))
1310                 return true;
1311
1312         if ((end_address >= range_start_address) &&
1313                         (end_address < range_end_address))
1314                 return true;
1315
1316         if ((address < range_start_address) &&
1317                         (end_address >= range_end_address))
1318                 return true;
1319
1320         return false;
1321 }
1322
1323 int hl_device_open(struct inode *inode, struct file *filp);
1324 bool hl_device_disabled_or_in_reset(struct hl_device *hdev);
1325 enum hl_device_status hl_device_status(struct hl_device *hdev);
1326 int create_hdev(struct hl_device **dev, struct pci_dev *pdev,
1327                 enum hl_asic_type asic_type, int minor);
1328 void destroy_hdev(struct hl_device *hdev);
1329 int hl_poll_timeout_memory(struct hl_device *hdev, u64 addr, u32 timeout_us,
1330                                 u32 *val);
1331 int hl_poll_timeout_device_memory(struct hl_device *hdev, void __iomem *addr,
1332                                 u32 timeout_us, u32 *val);
1333 int hl_hw_queues_create(struct hl_device *hdev);
1334 void hl_hw_queues_destroy(struct hl_device *hdev);
1335 int hl_hw_queue_send_cb_no_cmpl(struct hl_device *hdev, u32 hw_queue_id,
1336                                 u32 cb_size, u64 cb_ptr);
1337 int hl_hw_queue_schedule_cs(struct hl_cs *cs);
1338 u32 hl_hw_queue_add_ptr(u32 ptr, u16 val);
1339 void hl_hw_queue_inc_ci_kernel(struct hl_device *hdev, u32 hw_queue_id);
1340 void hl_int_hw_queue_update_ci(struct hl_cs *cs);
1341 void hl_hw_queue_reset(struct hl_device *hdev, bool hard_reset);
1342
1343 #define hl_queue_inc_ptr(p)             hl_hw_queue_add_ptr(p, 1)
1344 #define hl_pi_2_offset(pi)              ((pi) & (HL_QUEUE_LENGTH - 1))
1345
1346 int hl_cq_init(struct hl_device *hdev, struct hl_cq *q, u32 hw_queue_id);
1347 void hl_cq_fini(struct hl_device *hdev, struct hl_cq *q);
1348 int hl_eq_init(struct hl_device *hdev, struct hl_eq *q);
1349 void hl_eq_fini(struct hl_device *hdev, struct hl_eq *q);
1350 void hl_cq_reset(struct hl_device *hdev, struct hl_cq *q);
1351 void hl_eq_reset(struct hl_device *hdev, struct hl_eq *q);
1352 irqreturn_t hl_irq_handler_cq(int irq, void *arg);
1353 irqreturn_t hl_irq_handler_eq(int irq, void *arg);
1354 u32 hl_cq_inc_ptr(u32 ptr);
1355
1356 int hl_asid_init(struct hl_device *hdev);
1357 void hl_asid_fini(struct hl_device *hdev);
1358 unsigned long hl_asid_alloc(struct hl_device *hdev);
1359 void hl_asid_free(struct hl_device *hdev, unsigned long asid);
1360
1361 int hl_ctx_create(struct hl_device *hdev, struct hl_fpriv *hpriv);
1362 void hl_ctx_free(struct hl_device *hdev, struct hl_ctx *ctx);
1363 int hl_ctx_init(struct hl_device *hdev, struct hl_ctx *ctx, bool is_kernel_ctx);
1364 void hl_ctx_do_release(struct kref *ref);
1365 void hl_ctx_get(struct hl_device *hdev, struct hl_ctx *ctx);
1366 int hl_ctx_put(struct hl_ctx *ctx);
1367 struct dma_fence *hl_ctx_get_fence(struct hl_ctx *ctx, u64 seq);
1368 void hl_ctx_mgr_init(struct hl_ctx_mgr *mgr);
1369 void hl_ctx_mgr_fini(struct hl_device *hdev, struct hl_ctx_mgr *mgr);
1370
1371 int hl_device_init(struct hl_device *hdev, struct class *hclass);
1372 void hl_device_fini(struct hl_device *hdev);
1373 int hl_device_suspend(struct hl_device *hdev);
1374 int hl_device_resume(struct hl_device *hdev);
1375 int hl_device_reset(struct hl_device *hdev, bool hard_reset,
1376                         bool from_hard_reset_thread);
1377 void hl_hpriv_get(struct hl_fpriv *hpriv);
1378 void hl_hpriv_put(struct hl_fpriv *hpriv);
1379 int hl_device_set_frequency(struct hl_device *hdev, enum hl_pll_frequency freq);
1380
1381 int hl_build_hwmon_channel_info(struct hl_device *hdev,
1382                 struct armcp_sensor *sensors_arr);
1383
1384 int hl_sysfs_init(struct hl_device *hdev);
1385 void hl_sysfs_fini(struct hl_device *hdev);
1386
1387 int hl_hwmon_init(struct hl_device *hdev);
1388 void hl_hwmon_fini(struct hl_device *hdev);
1389
1390 int hl_cb_create(struct hl_device *hdev, struct hl_cb_mgr *mgr, u32 cb_size,
1391                 u64 *handle, int ctx_id);
1392 int hl_cb_destroy(struct hl_device *hdev, struct hl_cb_mgr *mgr, u64 cb_handle);
1393 int hl_cb_mmap(struct hl_fpriv *hpriv, struct vm_area_struct *vma);
1394 struct hl_cb *hl_cb_get(struct hl_device *hdev, struct hl_cb_mgr *mgr,
1395                         u32 handle);
1396 void hl_cb_put(struct hl_cb *cb);
1397 void hl_cb_mgr_init(struct hl_cb_mgr *mgr);
1398 void hl_cb_mgr_fini(struct hl_device *hdev, struct hl_cb_mgr *mgr);
1399 struct hl_cb *hl_cb_kernel_create(struct hl_device *hdev, u32 cb_size);
1400 int hl_cb_pool_init(struct hl_device *hdev);
1401 int hl_cb_pool_fini(struct hl_device *hdev);
1402
1403 void hl_cs_rollback_all(struct hl_device *hdev);
1404 struct hl_cs_job *hl_cs_allocate_job(struct hl_device *hdev, bool ext_queue);
1405
1406 void goya_set_asic_funcs(struct hl_device *hdev);
1407
1408 int hl_vm_ctx_init(struct hl_ctx *ctx);
1409 void hl_vm_ctx_fini(struct hl_ctx *ctx);
1410
1411 int hl_vm_init(struct hl_device *hdev);
1412 void hl_vm_fini(struct hl_device *hdev);
1413
1414 int hl_pin_host_memory(struct hl_device *hdev, u64 addr, u64 size,
1415                         struct hl_userptr *userptr);
1416 int hl_unpin_host_memory(struct hl_device *hdev, struct hl_userptr *userptr);
1417 void hl_userptr_delete_list(struct hl_device *hdev,
1418                                 struct list_head *userptr_list);
1419 bool hl_userptr_is_pinned(struct hl_device *hdev, u64 addr, u32 size,
1420                                 struct list_head *userptr_list,
1421                                 struct hl_userptr **userptr);
1422
1423 int hl_mmu_init(struct hl_device *hdev);
1424 void hl_mmu_fini(struct hl_device *hdev);
1425 int hl_mmu_ctx_init(struct hl_ctx *ctx);
1426 void hl_mmu_ctx_fini(struct hl_ctx *ctx);
1427 int hl_mmu_map(struct hl_ctx *ctx, u64 virt_addr, u64 phys_addr, u32 page_size);
1428 int hl_mmu_unmap(struct hl_ctx *ctx, u64 virt_addr, u32 page_size);
1429 void hl_mmu_swap_out(struct hl_ctx *ctx);
1430 void hl_mmu_swap_in(struct hl_ctx *ctx);
1431
1432 int hl_fw_push_fw_to_device(struct hl_device *hdev, const char *fw_name,
1433                                 void __iomem *dst);
1434 int hl_fw_send_pci_access_msg(struct hl_device *hdev, u32 opcode);
1435 int hl_fw_send_cpu_message(struct hl_device *hdev, u32 hw_queue_id, u32 *msg,
1436                                 u16 len, u32 timeout, long *result);
1437 int hl_fw_test_cpu_queue(struct hl_device *hdev);
1438 void *hl_fw_cpu_accessible_dma_pool_alloc(struct hl_device *hdev, size_t size,
1439                                                 dma_addr_t *dma_handle);
1440 void hl_fw_cpu_accessible_dma_pool_free(struct hl_device *hdev, size_t size,
1441                                         void *vaddr);
1442 int hl_fw_send_heartbeat(struct hl_device *hdev);
1443 int hl_fw_armcp_info_get(struct hl_device *hdev);
1444 int hl_fw_get_eeprom_data(struct hl_device *hdev, void *data, size_t max_size);
1445
1446 int hl_pci_bars_map(struct hl_device *hdev, const char * const name[3],
1447                         bool is_wc[3]);
1448 int hl_pci_iatu_write(struct hl_device *hdev, u32 addr, u32 data);
1449 int hl_pci_set_dram_bar_base(struct hl_device *hdev, u8 inbound_region, u8 bar,
1450                                 u64 addr);
1451 int hl_pci_init_iatu(struct hl_device *hdev, u64 sram_base_address,
1452                         u64 dram_base_address, u64 host_phys_base_address,
1453                         u64 host_phys_size);
1454 int hl_pci_init(struct hl_device *hdev, u8 dma_mask);
1455 void hl_pci_fini(struct hl_device *hdev);
1456 int hl_pci_set_dma_mask(struct hl_device *hdev, u8 dma_mask);
1457
1458 long hl_get_frequency(struct hl_device *hdev, u32 pll_index, bool curr);
1459 void hl_set_frequency(struct hl_device *hdev, u32 pll_index, u64 freq);
1460 long hl_get_temperature(struct hl_device *hdev, int sensor_index, u32 attr);
1461 long hl_get_voltage(struct hl_device *hdev, int sensor_index, u32 attr);
1462 long hl_get_current(struct hl_device *hdev, int sensor_index, u32 attr);
1463 long hl_get_fan_speed(struct hl_device *hdev, int sensor_index, u32 attr);
1464 long hl_get_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr);
1465 void hl_set_pwm_info(struct hl_device *hdev, int sensor_index, u32 attr,
1466                         long value);
1467 u64 hl_get_max_power(struct hl_device *hdev);
1468 void hl_set_max_power(struct hl_device *hdev, u64 value);
1469
1470 #ifdef CONFIG_DEBUG_FS
1471
1472 void hl_debugfs_init(void);
1473 void hl_debugfs_fini(void);
1474 void hl_debugfs_add_device(struct hl_device *hdev);
1475 void hl_debugfs_remove_device(struct hl_device *hdev);
1476 void hl_debugfs_add_file(struct hl_fpriv *hpriv);
1477 void hl_debugfs_remove_file(struct hl_fpriv *hpriv);
1478 void hl_debugfs_add_cb(struct hl_cb *cb);
1479 void hl_debugfs_remove_cb(struct hl_cb *cb);
1480 void hl_debugfs_add_cs(struct hl_cs *cs);
1481 void hl_debugfs_remove_cs(struct hl_cs *cs);
1482 void hl_debugfs_add_job(struct hl_device *hdev, struct hl_cs_job *job);
1483 void hl_debugfs_remove_job(struct hl_device *hdev, struct hl_cs_job *job);
1484 void hl_debugfs_add_userptr(struct hl_device *hdev, struct hl_userptr *userptr);
1485 void hl_debugfs_remove_userptr(struct hl_device *hdev,
1486                                 struct hl_userptr *userptr);
1487 void hl_debugfs_add_ctx_mem_hash(struct hl_device *hdev, struct hl_ctx *ctx);
1488 void hl_debugfs_remove_ctx_mem_hash(struct hl_device *hdev, struct hl_ctx *ctx);
1489
1490 #else
1491
1492 static inline void __init hl_debugfs_init(void)
1493 {
1494 }
1495
1496 static inline void hl_debugfs_fini(void)
1497 {
1498 }
1499
1500 static inline void hl_debugfs_add_device(struct hl_device *hdev)
1501 {
1502 }
1503
1504 static inline void hl_debugfs_remove_device(struct hl_device *hdev)
1505 {
1506 }
1507
1508 static inline void hl_debugfs_add_file(struct hl_fpriv *hpriv)
1509 {
1510 }
1511
1512 static inline void hl_debugfs_remove_file(struct hl_fpriv *hpriv)
1513 {
1514 }
1515
1516 static inline void hl_debugfs_add_cb(struct hl_cb *cb)
1517 {
1518 }
1519
1520 static inline void hl_debugfs_remove_cb(struct hl_cb *cb)
1521 {
1522 }
1523
1524 static inline void hl_debugfs_add_cs(struct hl_cs *cs)
1525 {
1526 }
1527
1528 static inline void hl_debugfs_remove_cs(struct hl_cs *cs)
1529 {
1530 }
1531
1532 static inline void hl_debugfs_add_job(struct hl_device *hdev,
1533                                         struct hl_cs_job *job)
1534 {
1535 }
1536
1537 static inline void hl_debugfs_remove_job(struct hl_device *hdev,
1538                                         struct hl_cs_job *job)
1539 {
1540 }
1541
1542 static inline void hl_debugfs_add_userptr(struct hl_device *hdev,
1543                                         struct hl_userptr *userptr)
1544 {
1545 }
1546
1547 static inline void hl_debugfs_remove_userptr(struct hl_device *hdev,
1548                                         struct hl_userptr *userptr)
1549 {
1550 }
1551
1552 static inline void hl_debugfs_add_ctx_mem_hash(struct hl_device *hdev,
1553                                         struct hl_ctx *ctx)
1554 {
1555 }
1556
1557 static inline void hl_debugfs_remove_ctx_mem_hash(struct hl_device *hdev,
1558                                         struct hl_ctx *ctx)
1559 {
1560 }
1561
1562 #endif
1563
1564 /* IOCTLs */
1565 long hl_ioctl(struct file *filep, unsigned int cmd, unsigned long arg);
1566 int hl_cb_ioctl(struct hl_fpriv *hpriv, void *data);
1567 int hl_cs_ioctl(struct hl_fpriv *hpriv, void *data);
1568 int hl_cs_wait_ioctl(struct hl_fpriv *hpriv, void *data);
1569 int hl_mem_ioctl(struct hl_fpriv *hpriv, void *data);
1570
1571 #endif /* HABANALABSP_H_ */