Merge tag 'lsk-v4.4-16.05-android'
[firefly-linux-kernel-4.4.55.git] / drivers / gpu / arm / midgard / mali_base_kernel.h
1 /*
2  *
3  * (C) COPYRIGHT 2010-2015 ARM Limited. All rights reserved.
4  *
5  * This program is free software and is provided to you under the terms of the
6  * GNU General Public License version 2 as published by the Free Software
7  * Foundation, and any use by you of this program is subject to the terms
8  * of such GNU licence.
9  *
10  * A copy of the licence is included with the program, and can also be obtained
11  * from Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
12  * Boston, MA  02110-1301, USA.
13  *
14  */
15
16
17
18
19
20 /**
21  * @file
22  * Base structures shared with the kernel.
23  */
24
25 #ifndef _BASE_KERNEL_H_
26 #define _BASE_KERNEL_H_
27
28 #ifndef __user
29 #define __user
30 #endif
31
32 /* Support UK6 IOCTLS */
33 #define BASE_LEGACY_UK6_SUPPORT 1
34
35 /* Support UK7 IOCTLS */
36 /* NB: To support UK6 we also need to support UK7 */
37 #define BASE_LEGACY_UK7_SUPPORT 1
38
39 /* Support UK8 IOCTLS */
40 #define BASE_LEGACY_UK8_SUPPORT 1
41
42 /* Support UK9 IOCTLS */
43 #define BASE_LEGACY_UK9_SUPPORT 1
44
45 typedef u64 base_mem_handle;
46
47 #include "mali_base_mem_priv.h"
48 #include "mali_kbase_profiling_gator_api.h"
49 #include "mali_midg_coherency.h"
50 #include "mali_kbase_gpu_id.h"
51
52 /*
53  * Dependency stuff, keep it private for now. May want to expose it if
54  * we decide to make the number of semaphores a configurable
55  * option.
56  */
57 #define BASE_JD_ATOM_COUNT              256
58
59 #define BASEP_JD_SEM_PER_WORD_LOG2      5
60 #define BASEP_JD_SEM_PER_WORD           (1 << BASEP_JD_SEM_PER_WORD_LOG2)
61 #define BASEP_JD_SEM_WORD_NR(x)         ((x) >> BASEP_JD_SEM_PER_WORD_LOG2)
62 #define BASEP_JD_SEM_MASK_IN_WORD(x)    (1 << ((x) & (BASEP_JD_SEM_PER_WORD - 1)))
63 #define BASEP_JD_SEM_ARRAY_SIZE         BASEP_JD_SEM_WORD_NR(BASE_JD_ATOM_COUNT)
64
65 #define BASE_GPU_NUM_TEXTURE_FEATURES_REGISTERS 3
66
67 #define BASE_MAX_COHERENT_GROUPS 16
68
69 #if defined CDBG_ASSERT
70 #define LOCAL_ASSERT CDBG_ASSERT
71 #elif defined KBASE_DEBUG_ASSERT
72 #define LOCAL_ASSERT KBASE_DEBUG_ASSERT
73 #else
74 #error assert macro not defined!
75 #endif
76
77 #if defined PAGE_MASK
78 #define LOCAL_PAGE_LSB ~PAGE_MASK
79 #else
80 #include <osu/mali_osu.h>
81
82 #if defined OSU_CONFIG_CPU_PAGE_SIZE_LOG2
83 #define LOCAL_PAGE_LSB ((1ul << OSU_CONFIG_CPU_PAGE_SIZE_LOG2) - 1)
84 #else
85 #error Failed to find page size
86 #endif
87 #endif
88
89 /** 32/64-bit neutral way to represent pointers */
90 typedef union kbase_pointer {
91         void __user *value;       /**< client should store their pointers here */
92         u32 compat_value; /**< 64-bit kernels should fetch value here when handling 32-bit clients */
93         u64 sizer;        /**< Force 64-bit storage for all clients regardless */
94 } kbase_pointer;
95
96 /**
97  * @addtogroup base_user_api User-side Base APIs
98  * @{
99  */
100
101 /**
102  * @addtogroup base_user_api_memory User-side Base Memory APIs
103  * @{
104  */
105
106 /**
107  * @brief Memory allocation, access/hint flags
108  *
109  * A combination of MEM_PROT/MEM_HINT flags must be passed to each allocator
110  * in order to determine the best cache policy. Some combinations are
111  * of course invalid (eg @c MEM_PROT_CPU_WR | @c MEM_HINT_CPU_RD),
112  * which defines a @a write-only region on the CPU side, which is
113  * heavily read by the CPU...
114  * Other flags are only meaningful to a particular allocator.
115  * More flags can be added to this list, as long as they don't clash
116  * (see ::BASE_MEM_FLAGS_NR_BITS for the number of the first free bit).
117  */
118 typedef u32 base_mem_alloc_flags;
119
120 /**
121  * @brief Memory allocation, access/hint flags
122  *
123  * See ::base_mem_alloc_flags.
124  *
125  */
126 enum {
127 /* IN */
128         BASE_MEM_PROT_CPU_RD = (1U << 0),      /**< Read access CPU side */
129         BASE_MEM_PROT_CPU_WR = (1U << 1),      /**< Write access CPU side */
130         BASE_MEM_PROT_GPU_RD = (1U << 2),      /**< Read access GPU side */
131         BASE_MEM_PROT_GPU_WR = (1U << 3),      /**< Write access GPU side */
132         BASE_MEM_PROT_GPU_EX = (1U << 4),      /**< Execute allowed on the GPU
133                                                     side */
134
135         /* BASE_MEM_HINT flags have been removed, but their values are reserved
136          * for backwards compatibility with older user-space drivers. The values
137          * can be re-used once support for r5p0 user-space drivers is removed,
138          * presumably in r7p0.
139          *
140          * RESERVED: (1U << 5)
141          * RESERVED: (1U << 6)
142          * RESERVED: (1U << 7)
143          * RESERVED: (1U << 8)
144          */
145
146         BASE_MEM_GROW_ON_GPF = (1U << 9),      /**< Grow backing store on GPU
147                                                     Page Fault */
148
149         BASE_MEM_COHERENT_SYSTEM = (1U << 10), /**< Page coherence Outer
150                                                     shareable, if available */
151         BASE_MEM_COHERENT_LOCAL = (1U << 11),  /**< Page coherence Inner
152                                                     shareable */
153         BASE_MEM_CACHED_CPU = (1U << 12),      /**< Should be cached on the
154                                                     CPU */
155
156 /* IN/OUT */
157         BASE_MEM_SAME_VA = (1U << 13), /**< Must have same VA on both the GPU
158                                             and the CPU */
159 /* OUT */
160         BASE_MEM_NEED_MMAP = (1U << 14), /**< Must call mmap to aquire a GPU
161                                              address for the alloc */
162 /* IN */
163         BASE_MEM_COHERENT_SYSTEM_REQUIRED = (1U << 15), /**< Page coherence
164                                              Outer shareable, required. */
165         BASE_MEM_SECURE = (1U << 16)           /**< Secure memory */
166
167 };
168
169 /**
170  * @brief Number of bits used as flags for base memory management
171  *
172  * Must be kept in sync with the ::base_mem_alloc_flags flags
173  */
174 #define BASE_MEM_FLAGS_NR_BITS 17
175
176 /**
177   * A mask for all output bits, excluding IN/OUT bits.
178   */
179 #define BASE_MEM_FLAGS_OUTPUT_MASK BASE_MEM_NEED_MMAP
180
181 /**
182   * A mask for all input bits, including IN/OUT bits.
183   */
184 #define BASE_MEM_FLAGS_INPUT_MASK \
185         (((1 << BASE_MEM_FLAGS_NR_BITS) - 1) & ~BASE_MEM_FLAGS_OUTPUT_MASK)
186
187
188 /**
189  * enum base_mem_import_type - Memory types supported by @a base_mem_import
190  *
191  * @BASE_MEM_IMPORT_TYPE_INVALID: Invalid type
192  * @BASE_MEM_IMPORT_TYPE_UMP: UMP import. Handle type is ump_secure_id.
193  * @BASE_MEM_IMPORT_TYPE_UMM: UMM import. Handle type is a file descriptor (int)
194  * @BASE_MEM_IMPORT_TYPE_USER_BUFFER: User buffer import. Handle is a
195  * base_mem_import_user_buffer
196  *
197  * Each type defines what the supported handle type is.
198  *
199  * If any new type is added here ARM must be contacted
200  * to allocate a numeric value for it.
201  * Do not just add a new type without synchronizing with ARM
202  * as future releases from ARM might include other new types
203  * which could clash with your custom types.
204  */
205 typedef enum base_mem_import_type {
206         BASE_MEM_IMPORT_TYPE_INVALID = 0,
207         BASE_MEM_IMPORT_TYPE_UMP = 1,
208         BASE_MEM_IMPORT_TYPE_UMM = 2,
209         BASE_MEM_IMPORT_TYPE_USER_BUFFER = 3
210 } base_mem_import_type;
211
212 /**
213  * struct base_mem_import_user_buffer - Handle of an imported user buffer
214  *
215  * @ptr:        kbase_pointer to imported user buffer
216  * @length:     length of imported user buffer in bytes
217  *
218  * This structure is used to represent a handle of an imported user buffer.
219  */
220
221 struct base_mem_import_user_buffer {
222         kbase_pointer ptr;
223         u64 length;
224 };
225
226 /**
227  * @brief Invalid memory handle type.
228  * Return value from functions returning @a base_mem_handle on error.
229  */
230 #define BASE_MEM_INVALID_HANDLE                (0ull  << 12)
231 #define BASE_MEM_MMU_DUMP_HANDLE               (1ull  << 12)
232 #define BASE_MEM_TRACE_BUFFER_HANDLE           (2ull  << 12)
233 #define BASE_MEM_MAP_TRACKING_HANDLE           (3ull  << 12)
234 #define BASE_MEM_WRITE_ALLOC_PAGES_HANDLE      (4ull  << 12)
235 /* reserved handles ..-64<<PAGE_SHIFT> for future special handles */
236 #define BASE_MEM_COOKIE_BASE                   (64ul  << 12)
237 #define BASE_MEM_FIRST_FREE_ADDRESS            ((BITS_PER_LONG << 12) + \
238                                                 BASE_MEM_COOKIE_BASE)
239
240 /* Mask to detect 4GB boundary alignment */
241 #define BASE_MEM_MASK_4GB  0xfffff000UL
242
243 /* Bit mask of cookies used for for memory allocation setup */
244 #define KBASE_COOKIE_MASK  ~1UL /* bit 0 is reserved */
245
246
247 /**
248  * @brief Result codes of changing the size of the backing store allocated to a tmem region
249  */
250 typedef enum base_backing_threshold_status {
251         BASE_BACKING_THRESHOLD_OK = 0,                      /**< Resize successful */
252         BASE_BACKING_THRESHOLD_ERROR_NOT_GROWABLE = -1,     /**< Not a growable tmem object */
253         BASE_BACKING_THRESHOLD_ERROR_OOM = -2,              /**< Increase failed due to an out-of-memory condition */
254         BASE_BACKING_THRESHOLD_ERROR_MAPPED = -3,           /**< Resize attempted on buffer while it was mapped, which is not permitted */
255         BASE_BACKING_THRESHOLD_ERROR_INVALID_ARGUMENTS = -4 /**< Invalid arguments (not tmem, illegal size request, etc.) */
256 } base_backing_threshold_status;
257
258 /**
259  * @addtogroup base_user_api_memory_defered User-side Base Defered Memory Coherency APIs
260  * @{
261  */
262
263 /**
264  * @brief a basic memory operation (sync-set).
265  *
266  * The content of this structure is private, and should only be used
267  * by the accessors.
268  */
269 typedef struct base_syncset {
270         struct basep_syncset basep_sset;
271 } base_syncset;
272
273 /** @} end group base_user_api_memory_defered */
274
275 /**
276  * Handle to represent imported memory object.
277  * Simple opague handle to imported memory, can't be used
278  * with anything but base_external_resource_init to bind to an atom.
279  */
280 typedef struct base_import_handle {
281         struct {
282                 u64 handle;
283         } basep;
284 } base_import_handle;
285
286 /** @} end group base_user_api_memory */
287
288 /**
289  * @addtogroup base_user_api_job_dispatch User-side Base Job Dispatcher APIs
290  * @{
291  */
292
293 typedef int platform_fence_type;
294 #define INVALID_PLATFORM_FENCE ((platform_fence_type)-1)
295
296 /**
297  * Base stream handle.
298  *
299  * References an underlying base stream object.
300  */
301 typedef struct base_stream {
302         struct {
303                 int fd;
304         } basep;
305 } base_stream;
306
307 /**
308  * Base fence handle.
309  *
310  * References an underlying base fence object.
311  */
312 typedef struct base_fence {
313         struct {
314                 int fd;
315                 int stream_fd;
316         } basep;
317 } base_fence;
318
319 /**
320  * @brief Per-job data
321  *
322  * This structure is used to store per-job data, and is completly unused
323  * by the Base driver. It can be used to store things such as callback
324  * function pointer, data to handle job completion. It is guaranteed to be
325  * untouched by the Base driver.
326  */
327 typedef struct base_jd_udata {
328         u64 blob[2];     /**< per-job data array */
329 } base_jd_udata;
330
331 /**
332  * @brief Memory aliasing info
333  *
334  * Describes a memory handle to be aliased.
335  * A subset of the handle can be chosen for aliasing, given an offset and a
336  * length.
337  * A special handle BASE_MEM_WRITE_ALLOC_PAGES_HANDLE is used to represent a
338  * region where a special page is mapped with a write-alloc cache setup,
339  * typically used when the write result of the GPU isn't needed, but the GPU
340  * must write anyway.
341  *
342  * Offset and length are specified in pages.
343  * Offset must be within the size of the handle.
344  * Offset+length must not overrun the size of the handle.
345  *
346  * @handle Handle to alias, can be BASE_MEM_WRITE_ALLOC_PAGES_HANDLE
347  * @offset Offset within the handle to start aliasing from, in pages.
348  *         Not used with BASE_MEM_WRITE_ALLOC_PAGES_HANDLE.
349  * @length Length to alias, in pages. For BASE_MEM_WRITE_ALLOC_PAGES_HANDLE
350  *         specifies the number of times the special page is needed.
351  */
352 struct base_mem_aliasing_info {
353         base_mem_handle handle;
354         u64 offset;
355         u64 length;
356 };
357
358 /**
359  * @brief Job dependency type.
360  *
361  * A flags field will be inserted into the atom structure to specify whether a dependency is a data or
362  * ordering dependency (by putting it before/after 'core_req' in the structure it should be possible to add without
363  * changing the structure size).
364  * When the flag is set for a particular dependency to signal that it is an ordering only dependency then
365  * errors will not be propagated.
366  */
367 typedef u8 base_jd_dep_type;
368
369
370 #define BASE_JD_DEP_TYPE_INVALID  (0)       /**< Invalid dependency */
371 #define BASE_JD_DEP_TYPE_DATA     (1U << 0) /**< Data dependency */
372 #define BASE_JD_DEP_TYPE_ORDER    (1U << 1) /**< Order dependency */
373
374 /**
375  * @brief Job chain hardware requirements.
376  *
377  * A job chain must specify what GPU features it needs to allow the
378  * driver to schedule the job correctly.  By not specifying the
379  * correct settings can/will cause an early job termination.  Multiple
380  * values can be ORed together to specify multiple requirements.
381  * Special case is ::BASE_JD_REQ_DEP, which is used to express complex
382  * dependencies, and that doesn't execute anything on the hardware.
383  */
384 typedef u16 base_jd_core_req;
385
386 /* Requirements that come from the HW */
387 #define BASE_JD_REQ_DEP 0           /**< No requirement, dependency only */
388 #define BASE_JD_REQ_FS  (1U << 0)   /**< Requires fragment shaders */
389 /**
390  * Requires compute shaders
391  * This covers any of the following Midgard Job types:
392  * - Vertex Shader Job
393  * - Geometry Shader Job
394  * - An actual Compute Shader Job
395  *
396  * Compare this with @ref BASE_JD_REQ_ONLY_COMPUTE, which specifies that the
397  * job is specifically just the "Compute Shader" job type, and not the "Vertex
398  * Shader" nor the "Geometry Shader" job type.
399  */
400 #define BASE_JD_REQ_CS  (1U << 1)
401 #define BASE_JD_REQ_T   (1U << 2)   /**< Requires tiling */
402 #define BASE_JD_REQ_CF  (1U << 3)   /**< Requires cache flushes */
403 #define BASE_JD_REQ_V   (1U << 4)   /**< Requires value writeback */
404
405 /* SW-only requirements - the HW does not expose these as part of the job slot capabilities */
406
407 /* Requires fragment job with AFBC encoding */
408 #define BASE_JD_REQ_FS_AFBC  (1U << 13)
409
410 /**
411  * SW Only requirement: the job chain requires a coherent core group. We don't
412  * mind which coherent core group is used.
413  */
414 #define BASE_JD_REQ_COHERENT_GROUP  (1U << 6)
415
416 /**
417  * SW Only requirement: The performance counters should be enabled only when
418  * they are needed, to reduce power consumption.
419  */
420
421 #define BASE_JD_REQ_PERMON               (1U << 7)
422
423 /**
424  * SW Only requirement: External resources are referenced by this atom.
425  * When external resources are referenced no syncsets can be bundled with the atom
426  * but should instead be part of a NULL jobs inserted into the dependency tree.
427  * The first pre_dep object must be configured for the external resouces to use,
428  * the second pre_dep object can be used to create other dependencies.
429  */
430 #define BASE_JD_REQ_EXTERNAL_RESOURCES   (1U << 8)
431
432 /**
433  * SW Only requirement: Software defined job. Jobs with this bit set will not be submitted
434  * to the hardware but will cause some action to happen within the driver
435  */
436 #define BASE_JD_REQ_SOFT_JOB        (1U << 9)
437
438 #define BASE_JD_REQ_SOFT_DUMP_CPU_GPU_TIME      (BASE_JD_REQ_SOFT_JOB | 0x1)
439 #define BASE_JD_REQ_SOFT_FENCE_TRIGGER          (BASE_JD_REQ_SOFT_JOB | 0x2)
440 #define BASE_JD_REQ_SOFT_FENCE_WAIT             (BASE_JD_REQ_SOFT_JOB | 0x3)
441
442 /**
443  * SW Only requirement : Replay job.
444  *
445  * If the preceeding job fails, the replay job will cause the jobs specified in
446  * the list of base_jd_replay_payload pointed to by the jc pointer to be
447  * replayed.
448  *
449  * A replay job will only cause jobs to be replayed up to BASEP_JD_REPLAY_LIMIT
450  * times. If a job fails more than BASEP_JD_REPLAY_LIMIT times then the replay
451  * job is failed, as well as any following dependencies.
452  *
453  * The replayed jobs will require a number of atom IDs. If there are not enough
454  * free atom IDs then the replay job will fail.
455  *
456  * If the preceeding job does not fail, then the replay job is returned as
457  * completed.
458  *
459  * The replayed jobs will never be returned to userspace. The preceeding failed
460  * job will be returned to userspace as failed; the status of this job should
461  * be ignored. Completion should be determined by the status of the replay soft
462  * job.
463  *
464  * In order for the jobs to be replayed, the job headers will have to be
465  * modified. The Status field will be reset to NOT_STARTED. If the Job Type
466  * field indicates a Vertex Shader Job then it will be changed to Null Job.
467  *
468  * The replayed jobs have the following assumptions :
469  *
470  * - No external resources. Any required external resources will be held by the
471  *   replay atom.
472  * - Pre-dependencies are created based on job order.
473  * - Atom numbers are automatically assigned.
474  * - device_nr is set to 0. This is not relevant as
475  *   BASE_JD_REQ_SPECIFIC_COHERENT_GROUP should not be set.
476  * - Priority is inherited from the replay job.
477  */
478 #define BASE_JD_REQ_SOFT_REPLAY                 (BASE_JD_REQ_SOFT_JOB | 0x4)
479
480 /**
481  * HW Requirement: Requires Compute shaders (but not Vertex or Geometry Shaders)
482  *
483  * This indicates that the Job Chain contains Midgard Jobs of the 'Compute Shaders' type.
484  *
485  * In contrast to @ref BASE_JD_REQ_CS, this does \b not indicate that the Job
486  * Chain contains 'Geometry Shader' or 'Vertex Shader' jobs.
487  */
488 #define BASE_JD_REQ_ONLY_COMPUTE    (1U << 10)
489
490 /**
491  * HW Requirement: Use the base_jd_atom::device_nr field to specify a
492  * particular core group
493  *
494  * If both BASE_JD_REQ_COHERENT_GROUP and this flag are set, this flag takes priority
495  *
496  * This is only guaranteed to work for BASE_JD_REQ_ONLY_COMPUTE atoms.
497  *
498  * If the core availability policy is keeping the required core group turned off, then
499  * the job will fail with a BASE_JD_EVENT_PM_EVENT error code.
500  */
501 #define BASE_JD_REQ_SPECIFIC_COHERENT_GROUP (1U << 11)
502
503 /**
504  * SW Flag: If this bit is set then the successful completion of this atom
505  * will not cause an event to be sent to userspace
506  */
507 #define BASE_JD_REQ_EVENT_ONLY_ON_FAILURE   (1U << 12)
508
509 /**
510  * SW Flag: If this bit is set then completion of this atom will not cause an
511  * event to be sent to userspace, whether successful or not.
512  */
513 #define BASEP_JD_REQ_EVENT_NEVER (1U << 14)
514
515 /**
516 * These requirement bits are currently unused in base_jd_core_req (currently a u16)
517 */
518
519 #define BASEP_JD_REQ_RESERVED_BIT5 (1U << 5)
520 #define BASEP_JD_REQ_RESERVED_BIT15 (1U << 15)
521
522 /**
523 * Mask of all the currently unused requirement bits in base_jd_core_req.
524 */
525
526 #define BASEP_JD_REQ_RESERVED (BASEP_JD_REQ_RESERVED_BIT5 | \
527                                 BASEP_JD_REQ_RESERVED_BIT15)
528
529 /**
530  * Mask of all bits in base_jd_core_req that control the type of the atom.
531  *
532  * This allows dependency only atoms to have flags set
533  */
534 #define BASEP_JD_REQ_ATOM_TYPE (~(BASEP_JD_REQ_RESERVED | BASE_JD_REQ_EVENT_ONLY_ON_FAILURE |\
535                                 BASE_JD_REQ_EXTERNAL_RESOURCES | BASEP_JD_REQ_EVENT_NEVER))
536
537 /**
538  * @brief States to model state machine processed by kbasep_js_job_check_ref_cores(), which
539  * handles retaining cores for power management and affinity management.
540  *
541  * The state @ref KBASE_ATOM_COREREF_STATE_RECHECK_AFFINITY prevents an attack
542  * where lots of atoms could be submitted before powerup, and each has an
543  * affinity chosen that causes other atoms to have an affinity
544  * violation. Whilst the affinity was not causing violations at the time it
545  * was chosen, it could cause violations thereafter. For example, 1000 jobs
546  * could have had their affinity chosen during the powerup time, so any of
547  * those 1000 jobs could cause an affinity violation later on.
548  *
549  * The attack would otherwise occur because other atoms/contexts have to wait for:
550  * -# the currently running atoms (which are causing the violation) to
551  * finish
552  * -# and, the atoms that had their affinity chosen during powerup to
553  * finish. These are run preferrentially because they don't cause a
554  * violation, but instead continue to cause the violation in others.
555  * -# or, the attacker is scheduled out (which might not happen for just 2
556  * contexts)
557  *
558  * By re-choosing the affinity (which is designed to avoid violations at the
559  * time it's chosen), we break condition (2) of the wait, which minimizes the
560  * problem to just waiting for current jobs to finish (which can be bounded if
561  * the Job Scheduling Policy has a timer).
562  */
563 enum kbase_atom_coreref_state {
564         /** Starting state: No affinity chosen, and cores must be requested. kbase_jd_atom::affinity==0 */
565         KBASE_ATOM_COREREF_STATE_NO_CORES_REQUESTED,
566         /** Cores requested, but waiting for them to be powered. Requested cores given by kbase_jd_atom::affinity */
567         KBASE_ATOM_COREREF_STATE_WAITING_FOR_REQUESTED_CORES,
568         /** Cores given by kbase_jd_atom::affinity are powered, but affinity might be out-of-date, so must recheck */
569         KBASE_ATOM_COREREF_STATE_RECHECK_AFFINITY,
570         /** Cores given by kbase_jd_atom::affinity are powered, and affinity is up-to-date, but must check for violations */
571         KBASE_ATOM_COREREF_STATE_CHECK_AFFINITY_VIOLATIONS,
572         /** Cores are powered, kbase_jd_atom::affinity up-to-date, no affinity violations: atom can be submitted to HW */
573         KBASE_ATOM_COREREF_STATE_READY
574 };
575
576 /*
577  * Base Atom priority
578  *
579  * Only certain priority levels are actually implemented, as specified by the
580  * BASE_JD_PRIO_<...> definitions below. It is undefined to use a priority
581  * level that is not one of those defined below.
582  *
583  * Priority levels only affect scheduling between atoms of the same type within
584  * a base context, and only after the atoms have had dependencies resolved.
585  * Fragment atoms does not affect non-frament atoms with lower priorities, and
586  * the other way around. For example, a low priority atom that has had its
587  * dependencies resolved might run before a higher priority atom that has not
588  * had its dependencies resolved.
589  *
590  * The scheduling between base contexts/processes and between atoms from
591  * different base contexts/processes is unaffected by atom priority.
592  *
593  * The atoms are scheduled as follows with respect to their priorities:
594  * - Let atoms 'X' and 'Y' be for the same job slot who have dependencies
595  *   resolved, and atom 'X' has a higher priority than atom 'Y'
596  * - If atom 'Y' is currently running on the HW, then it is interrupted to
597  *   allow atom 'X' to run soon after
598  * - If instead neither atom 'Y' nor atom 'X' are running, then when choosing
599  *   the next atom to run, atom 'X' will always be chosen instead of atom 'Y'
600  * - Any two atoms that have the same priority could run in any order with
601  *   respect to each other. That is, there is no ordering constraint between
602  *   atoms of the same priority.
603  */
604 typedef u8 base_jd_prio;
605
606 /* Medium atom priority. This is a priority higher than BASE_JD_PRIO_LOW */
607 #define BASE_JD_PRIO_MEDIUM  ((base_jd_prio)0)
608 /* High atom priority. This is a priority higher than BASE_JD_PRIO_MEDIUM and
609  * BASE_JD_PRIO_LOW */
610 #define BASE_JD_PRIO_HIGH    ((base_jd_prio)1)
611 /* Low atom priority. */
612 #define BASE_JD_PRIO_LOW     ((base_jd_prio)2)
613
614 /* Count of the number of priority levels. This itself is not a valid
615  * base_jd_prio setting */
616 #define BASE_JD_NR_PRIO_LEVELS 3
617
618 enum kbase_jd_atom_state {
619         /** Atom is not used */
620         KBASE_JD_ATOM_STATE_UNUSED,
621         /** Atom is queued in JD */
622         KBASE_JD_ATOM_STATE_QUEUED,
623         /** Atom has been given to JS (is runnable/running) */
624         KBASE_JD_ATOM_STATE_IN_JS,
625         /** Atom has been completed, but not yet handed back to job dispatcher
626          *  for dependency resolution */
627         KBASE_JD_ATOM_STATE_HW_COMPLETED,
628         /** Atom has been completed, but not yet handed back to userspace */
629         KBASE_JD_ATOM_STATE_COMPLETED
630 };
631
632 typedef u8 base_atom_id; /**< Type big enough to store an atom number in */
633
634 struct base_dependency {
635         base_atom_id  atom_id;               /**< An atom number */
636         base_jd_dep_type dependency_type;    /**< Dependency type */
637 };
638
639 typedef struct base_jd_atom_v2 {
640         u64 jc;                     /**< job-chain GPU address */
641         struct base_jd_udata udata;                 /**< user data */
642         kbase_pointer extres_list;          /**< list of external resources */
643         u16 nr_extres;                      /**< nr of external resources */
644         base_jd_core_req core_req;          /**< core requirements */
645         struct base_dependency pre_dep[2];  /**< pre-dependencies, one need to use SETTER function to assign this field,
646         this is done in order to reduce possibility of improper assigment of a dependency field */
647         base_atom_id atom_number;           /**< unique number to identify the atom */
648         base_jd_prio prio;                  /**< Atom priority. Refer to @ref base_jd_prio for more details */
649         u8 device_nr;                       /**< coregroup when BASE_JD_REQ_SPECIFIC_COHERENT_GROUP specified */
650         u8 padding[5];
651 } base_jd_atom_v2;
652
653 #ifdef BASE_LEGACY_UK6_SUPPORT
654 struct base_jd_atom_v2_uk6 {
655         u64 jc;                     /**< job-chain GPU address */
656         struct base_jd_udata udata;                 /**< user data */
657         kbase_pointer extres_list;          /**< list of external resources */
658         u16 nr_extres;                      /**< nr of external resources */
659         base_jd_core_req core_req;          /**< core requirements */
660         base_atom_id pre_dep[2]; /**< pre-dependencies */
661         base_atom_id atom_number;           /**< unique number to identify the atom */
662         base_jd_prio prio;                  /**< priority - smaller is higher priority */
663         u8 device_nr;                       /**< coregroup when BASE_JD_REQ_SPECIFIC_COHERENT_GROUP specified */
664         u8 padding[7];
665 };
666 #endif
667
668 typedef enum base_external_resource_access {
669         BASE_EXT_RES_ACCESS_SHARED,
670         BASE_EXT_RES_ACCESS_EXCLUSIVE
671 } base_external_resource_access;
672
673 typedef struct base_external_resource {
674         u64 ext_resource;
675 } base_external_resource;
676
677 /**
678  * @brief Setter for a dependency structure
679  *
680  * @param[in] dep          The kbase jd atom dependency to be initialized.
681  * @param     id           The atom_id to be assigned.
682  * @param     dep_type     The dep_type to be assigned.
683  *
684  */
685 static inline void base_jd_atom_dep_set(struct base_dependency *dep,
686                 base_atom_id id, base_jd_dep_type dep_type)
687 {
688         LOCAL_ASSERT(dep != NULL);
689
690         /*
691          * make sure we don't set not allowed combinations
692          * of atom_id/dependency_type.
693          */
694         LOCAL_ASSERT((id == 0 && dep_type == BASE_JD_DEP_TYPE_INVALID) ||
695                         (id > 0 && dep_type != BASE_JD_DEP_TYPE_INVALID));
696
697         dep->atom_id = id;
698         dep->dependency_type = dep_type;
699 }
700
701 /**
702  * @brief Make a copy of a dependency structure
703  *
704  * @param[in,out] dep          The kbase jd atom dependency to be written.
705  * @param[in]     from         The dependency to make a copy from.
706  *
707  */
708 static inline void base_jd_atom_dep_copy(struct base_dependency *dep,
709                 const struct base_dependency *from)
710 {
711         LOCAL_ASSERT(dep != NULL);
712
713         base_jd_atom_dep_set(dep, from->atom_id, from->dependency_type);
714 }
715
716 /**
717  * @brief Soft-atom fence trigger setup.
718  *
719  * Sets up an atom to be a SW-only atom signaling a fence
720  * when it reaches the run state.
721  *
722  * Using the existing base dependency system the fence can
723  * be set to trigger when a GPU job has finished.
724  *
725  * The base fence object must not be terminated until the atom
726  * has been submitted to @a base_jd_submit_bag and @a base_jd_submit_bag has returned.
727  *
728  * @a fence must be a valid fence set up with @a base_fence_init.
729  * Calling this function with a uninitialized fence results in undefined behavior.
730  *
731  * @param[out] atom A pre-allocated atom to configure as a fence trigger SW atom
732  * @param[in] fence The base fence object to trigger.
733  */
734 static inline void base_jd_fence_trigger_setup_v2(struct base_jd_atom_v2 *atom, struct base_fence *fence)
735 {
736         LOCAL_ASSERT(atom);
737         LOCAL_ASSERT(fence);
738         LOCAL_ASSERT(fence->basep.fd == INVALID_PLATFORM_FENCE);
739         LOCAL_ASSERT(fence->basep.stream_fd >= 0);
740         atom->jc = (uintptr_t) fence;
741         atom->core_req = BASE_JD_REQ_SOFT_FENCE_TRIGGER;
742 }
743
744 /**
745  * @brief Soft-atom fence wait setup.
746  *
747  * Sets up an atom to be a SW-only atom waiting on a fence.
748  * When the fence becomes triggered the atom becomes runnable
749  * and completes immediately.
750  *
751  * Using the existing base dependency system the fence can
752  * be set to block a GPU job until it has been triggered.
753  *
754  * The base fence object must not be terminated until the atom
755  * has been submitted to @a base_jd_submit_bag and @a base_jd_submit_bag has returned.
756  *
757  * @a fence must be a valid fence set up with @a base_fence_init or @a base_fence_import.
758  * Calling this function with a uninitialized fence results in undefined behavior.
759  *
760  * @param[out] atom A pre-allocated atom to configure as a fence wait SW atom
761  * @param[in] fence The base fence object to wait on
762  */
763 static inline void base_jd_fence_wait_setup_v2(struct base_jd_atom_v2 *atom, struct base_fence *fence)
764 {
765         LOCAL_ASSERT(atom);
766         LOCAL_ASSERT(fence);
767         LOCAL_ASSERT(fence->basep.fd >= 0);
768         atom->jc = (uintptr_t) fence;
769         atom->core_req = BASE_JD_REQ_SOFT_FENCE_WAIT;
770 }
771
772 /**
773  * @brief External resource info initialization.
774  *
775  * Sets up a external resource object to reference
776  * a memory allocation and the type of access requested.
777  *
778  * @param[in] res     The resource object to initialize
779  * @param     handle  The handle to the imported memory object
780  * @param     access  The type of access requested
781  */
782 static inline void base_external_resource_init(struct base_external_resource *res, struct base_import_handle handle, base_external_resource_access access)
783 {
784         u64 address;
785
786         address = handle.basep.handle;
787
788         LOCAL_ASSERT(res != NULL);
789         LOCAL_ASSERT(0 == (address & LOCAL_PAGE_LSB));
790         LOCAL_ASSERT(access == BASE_EXT_RES_ACCESS_SHARED || access == BASE_EXT_RES_ACCESS_EXCLUSIVE);
791
792         res->ext_resource = address | (access & LOCAL_PAGE_LSB);
793 }
794
795 /**
796  * @brief Job chain event code bits
797  * Defines the bits used to create ::base_jd_event_code
798  */
799 enum {
800         BASE_JD_SW_EVENT_KERNEL = (1u << 15), /**< Kernel side event */
801         BASE_JD_SW_EVENT = (1u << 14), /**< SW defined event */
802         BASE_JD_SW_EVENT_SUCCESS = (1u << 13), /**< Event idicates success (SW events only) */
803         BASE_JD_SW_EVENT_JOB = (0u << 11), /**< Job related event */
804         BASE_JD_SW_EVENT_BAG = (1u << 11), /**< Bag related event */
805         BASE_JD_SW_EVENT_INFO = (2u << 11), /**< Misc/info event */
806         BASE_JD_SW_EVENT_RESERVED = (3u << 11), /**< Reserved event type */
807         BASE_JD_SW_EVENT_TYPE_MASK = (3u << 11)     /**< Mask to extract the type from an event code */
808 };
809
810 /**
811  * @brief Job chain event codes
812  *
813  * HW and low-level SW events are represented by event codes.
814  * The status of jobs which succeeded are also represented by
815  * an event code (see ::BASE_JD_EVENT_DONE).
816  * Events are usually reported as part of a ::base_jd_event.
817  *
818  * The event codes are encoded in the following way:
819  * @li 10:0  - subtype
820  * @li 12:11 - type
821  * @li 13    - SW success (only valid if the SW bit is set)
822  * @li 14    - SW event (HW event if not set)
823  * @li 15    - Kernel event (should never be seen in userspace)
824  *
825  * Events are split up into ranges as follows:
826  * - BASE_JD_EVENT_RANGE_\<description\>_START
827  * - BASE_JD_EVENT_RANGE_\<description\>_END
828  *
829  * \a code is in \<description\>'s range when:
830  * - <tt>BASE_JD_EVENT_RANGE_\<description\>_START <= code < BASE_JD_EVENT_RANGE_\<description\>_END </tt>
831  *
832  * Ranges can be asserted for adjacency by testing that the END of the previous
833  * is equal to the START of the next. This is useful for optimizing some tests
834  * for range.
835  *
836  * A limitation is that the last member of this enum must explicitly be handled
837  * (with an assert-unreachable statement) in switch statements that use
838  * variables of this type. Otherwise, the compiler warns that we have not
839  * handled that enum value.
840  */
841 typedef enum base_jd_event_code {
842         /* HW defined exceptions */
843
844         /** Start of HW Non-fault status codes
845          *
846          * @note Obscurely, BASE_JD_EVENT_TERMINATED indicates a real fault,
847          * because the job was hard-stopped
848          */
849         BASE_JD_EVENT_RANGE_HW_NONFAULT_START = 0,
850
851         /* non-fatal exceptions */
852         BASE_JD_EVENT_NOT_STARTED = 0x00, /**< Can't be seen by userspace, treated as 'previous job done' */
853         BASE_JD_EVENT_DONE = 0x01,
854         BASE_JD_EVENT_STOPPED = 0x03,     /**< Can't be seen by userspace, becomes TERMINATED, DONE or JOB_CANCELLED */
855         BASE_JD_EVENT_TERMINATED = 0x04,  /**< This is actually a fault status code - the job was hard stopped */
856         BASE_JD_EVENT_ACTIVE = 0x08,      /**< Can't be seen by userspace, jobs only returned on complete/fail/cancel */
857
858         /** End of HW Non-fault status codes
859          *
860          * @note Obscurely, BASE_JD_EVENT_TERMINATED indicates a real fault,
861          * because the job was hard-stopped
862          */
863         BASE_JD_EVENT_RANGE_HW_NONFAULT_END = 0x40,
864
865         /** Start of HW fault and SW Error status codes */
866         BASE_JD_EVENT_RANGE_HW_FAULT_OR_SW_ERROR_START = 0x40,
867
868         /* job exceptions */
869         BASE_JD_EVENT_JOB_CONFIG_FAULT = 0x40,
870         BASE_JD_EVENT_JOB_POWER_FAULT = 0x41,
871         BASE_JD_EVENT_JOB_READ_FAULT = 0x42,
872         BASE_JD_EVENT_JOB_WRITE_FAULT = 0x43,
873         BASE_JD_EVENT_JOB_AFFINITY_FAULT = 0x44,
874         BASE_JD_EVENT_JOB_BUS_FAULT = 0x48,
875         BASE_JD_EVENT_INSTR_INVALID_PC = 0x50,
876         BASE_JD_EVENT_INSTR_INVALID_ENC = 0x51,
877         BASE_JD_EVENT_INSTR_TYPE_MISMATCH = 0x52,
878         BASE_JD_EVENT_INSTR_OPERAND_FAULT = 0x53,
879         BASE_JD_EVENT_INSTR_TLS_FAULT = 0x54,
880         BASE_JD_EVENT_INSTR_BARRIER_FAULT = 0x55,
881         BASE_JD_EVENT_INSTR_ALIGN_FAULT = 0x56,
882         BASE_JD_EVENT_DATA_INVALID_FAULT = 0x58,
883         BASE_JD_EVENT_TILE_RANGE_FAULT = 0x59,
884         BASE_JD_EVENT_STATE_FAULT = 0x5A,
885         BASE_JD_EVENT_OUT_OF_MEMORY = 0x60,
886         BASE_JD_EVENT_UNKNOWN = 0x7F,
887
888         /* GPU exceptions */
889         BASE_JD_EVENT_DELAYED_BUS_FAULT = 0x80,
890         BASE_JD_EVENT_SHAREABILITY_FAULT = 0x88,
891
892         /* MMU exceptions */
893         BASE_JD_EVENT_TRANSLATION_FAULT_LEVEL1 = 0xC1,
894         BASE_JD_EVENT_TRANSLATION_FAULT_LEVEL2 = 0xC2,
895         BASE_JD_EVENT_TRANSLATION_FAULT_LEVEL3 = 0xC3,
896         BASE_JD_EVENT_TRANSLATION_FAULT_LEVEL4 = 0xC4,
897         BASE_JD_EVENT_PERMISSION_FAULT = 0xC8,
898         BASE_JD_EVENT_TRANSTAB_BUS_FAULT_LEVEL1 = 0xD1,
899         BASE_JD_EVENT_TRANSTAB_BUS_FAULT_LEVEL2 = 0xD2,
900         BASE_JD_EVENT_TRANSTAB_BUS_FAULT_LEVEL3 = 0xD3,
901         BASE_JD_EVENT_TRANSTAB_BUS_FAULT_LEVEL4 = 0xD4,
902         BASE_JD_EVENT_ACCESS_FLAG = 0xD8,
903
904         /* SW defined exceptions */
905         BASE_JD_EVENT_MEM_GROWTH_FAILED = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_JOB | 0x000,
906         BASE_JD_EVENT_TIMED_OUT         = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_JOB | 0x001,
907         BASE_JD_EVENT_JOB_CANCELLED     = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_JOB | 0x002,
908         BASE_JD_EVENT_JOB_INVALID       = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_JOB | 0x003,
909         BASE_JD_EVENT_PM_EVENT          = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_JOB | 0x004,
910         BASE_JD_EVENT_FORCE_REPLAY      = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_JOB | 0x005,
911
912         BASE_JD_EVENT_BAG_INVALID       = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_BAG | 0x003,
913
914         /** End of HW fault and SW Error status codes */
915         BASE_JD_EVENT_RANGE_HW_FAULT_OR_SW_ERROR_END = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_RESERVED | 0x3FF,
916
917         /** Start of SW Success status codes */
918         BASE_JD_EVENT_RANGE_SW_SUCCESS_START = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_SUCCESS | 0x000,
919
920         BASE_JD_EVENT_PROGRESS_REPORT = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_SUCCESS | BASE_JD_SW_EVENT_JOB | 0x000,
921         BASE_JD_EVENT_BAG_DONE = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_SUCCESS | BASE_JD_SW_EVENT_BAG | 0x000,
922         BASE_JD_EVENT_DRV_TERMINATED = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_SUCCESS | BASE_JD_SW_EVENT_INFO | 0x000,
923
924         /** End of SW Success status codes */
925         BASE_JD_EVENT_RANGE_SW_SUCCESS_END = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_SUCCESS | BASE_JD_SW_EVENT_RESERVED | 0x3FF,
926
927         /** Start of Kernel-only status codes. Such codes are never returned to user-space */
928         BASE_JD_EVENT_RANGE_KERNEL_ONLY_START = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_KERNEL | 0x000,
929         BASE_JD_EVENT_REMOVED_FROM_NEXT = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_KERNEL | BASE_JD_SW_EVENT_JOB | 0x000,
930
931         /** End of Kernel-only status codes. */
932         BASE_JD_EVENT_RANGE_KERNEL_ONLY_END = BASE_JD_SW_EVENT | BASE_JD_SW_EVENT_KERNEL | BASE_JD_SW_EVENT_RESERVED | 0x3FF
933 } base_jd_event_code;
934
935 /**
936  * @brief Event reporting structure
937  *
938  * This structure is used by the kernel driver to report information
939  * about GPU events. The can either be HW-specific events or low-level
940  * SW events, such as job-chain completion.
941  *
942  * The event code contains an event type field which can be extracted
943  * by ANDing with ::BASE_JD_SW_EVENT_TYPE_MASK.
944  *
945  * Based on the event type base_jd_event::data holds:
946  * @li ::BASE_JD_SW_EVENT_JOB : the offset in the ring-buffer for the completed
947  * job-chain
948  * @li ::BASE_JD_SW_EVENT_BAG : The address of the ::base_jd_bag that has
949  * been completed (ie all contained job-chains have been completed).
950  * @li ::BASE_JD_SW_EVENT_INFO : base_jd_event::data not used
951  */
952 typedef struct base_jd_event_v2 {
953         base_jd_event_code event_code;  /**< event code */
954         base_atom_id atom_number;       /**< the atom number that has completed */
955         struct base_jd_udata udata;     /**< user data */
956 } base_jd_event_v2;
957
958 /**
959  * Padding required to ensure that the @ref struct base_dump_cpu_gpu_counters structure fills
960  * a full cache line.
961  */
962
963 #define BASE_CPU_GPU_CACHE_LINE_PADDING (36)
964
965
966 /**
967  * @brief Structure for BASE_JD_REQ_SOFT_DUMP_CPU_GPU_COUNTERS jobs.
968  *
969  * This structure is stored into the memory pointed to by the @c jc field of @ref base_jd_atom.
970  *
971  * This structure must be padded to ensure that it will occupy whole cache lines. This is to avoid
972  * cases where access to pages containing the structure is shared between cached and un-cached
973  * memory regions, which would cause memory corruption.  Here we set the structure size to be 64 bytes
974  * which is the cache line for ARM A15 processors.
975  */
976
977 typedef struct base_dump_cpu_gpu_counters {
978         u64 system_time;
979         u64 cycle_counter;
980         u64 sec;
981         u32 usec;
982         u8 padding[BASE_CPU_GPU_CACHE_LINE_PADDING];
983 } base_dump_cpu_gpu_counters;
984
985
986
987 /** @} end group base_user_api_job_dispatch */
988
989 #define GPU_MAX_JOB_SLOTS 16
990
991 /**
992  * @page page_base_user_api_gpuprops User-side Base GPU Property Query API
993  *
994  * The User-side Base GPU Property Query API encapsulates two
995  * sub-modules:
996  *
997  * - @ref base_user_api_gpuprops_dyn "Dynamic GPU Properties"
998  * - @ref base_plat_config_gpuprops "Base Platform Config GPU Properties"
999  *
1000  * There is a related third module outside of Base, which is owned by the MIDG
1001  * module:
1002  * - @ref gpu_props_static "Midgard Compile-time GPU Properties"
1003  *
1004  * Base only deals with properties that vary between different Midgard
1005  * implementations - the Dynamic GPU properties and the Platform Config
1006  * properties.
1007  *
1008  * For properties that are constant for the Midgard Architecture, refer to the
1009  * MIDG module. However, we will discuss their relevance here <b>just to
1010  * provide background information.</b>
1011  *
1012  * @section sec_base_user_api_gpuprops_about About the GPU Properties in Base and MIDG modules
1013  *
1014  * The compile-time properties (Platform Config, Midgard Compile-time
1015  * properties) are exposed as pre-processor macros.
1016  *
1017  * Complementing the compile-time properties are the Dynamic GPU
1018  * Properties, which act as a conduit for the Midgard Configuration
1019  * Discovery.
1020  *
1021  * In general, the dynamic properties are present to verify that the platform
1022  * has been configured correctly with the right set of Platform Config
1023  * Compile-time Properties.
1024  *
1025  * As a consistant guide across the entire DDK, the choice for dynamic or
1026  * compile-time should consider the following, in order:
1027  * -# Can the code be written so that it doesn't need to know the
1028  * implementation limits at all?
1029  * -# If you need the limits, get the information from the Dynamic Property
1030  * lookup. This should be done once as you fetch the context, and then cached
1031  * as part of the context data structure, so it's cheap to access.
1032  * -# If there's a clear and arguable inefficiency in using Dynamic Properties,
1033  * then use a Compile-Time Property (Platform Config, or Midgard Compile-time
1034  * property). Examples of where this might be sensible follow:
1035  *  - Part of a critical inner-loop
1036  *  - Frequent re-use throughout the driver, causing significant extra load
1037  * instructions or control flow that would be worthwhile optimizing out.
1038  *
1039  * We cannot provide an exhaustive set of examples, neither can we provide a
1040  * rule for every possible situation. Use common sense, and think about: what
1041  * the rest of the driver will be doing; how the compiler might represent the
1042  * value if it is a compile-time constant; whether an OEM shipping multiple
1043  * devices would benefit much more from a single DDK binary, instead of
1044  * insignificant micro-optimizations.
1045  *
1046  * @section sec_base_user_api_gpuprops_dyn Dynamic GPU Properties
1047  *
1048  * Dynamic GPU properties are presented in two sets:
1049  * -# the commonly used properties in @ref base_gpu_props, which have been
1050  * unpacked from GPU register bitfields.
1051  * -# The full set of raw, unprocessed properties in @ref gpu_raw_gpu_props
1052  * (also a member of @ref base_gpu_props). All of these are presented in
1053  * the packed form, as presented by the GPU  registers themselves.
1054  *
1055  * @usecase The raw properties in @ref gpu_raw_gpu_props are necessary to
1056  * allow a user of the Mali Tools (e.g. PAT) to determine "Why is this device
1057  * behaving differently?". In this case, all information about the
1058  * configuration is potentially useful, but it <b>does not need to be processed
1059  * by the driver</b>. Instead, the raw registers can be processed by the Mali
1060  * Tools software on the host PC.
1061  *
1062  * The properties returned extend the Midgard Configuration Discovery
1063  * registers. For example, GPU clock speed is not specified in the Midgard
1064  * Architecture, but is <b>necessary for OpenCL's clGetDeviceInfo() function</b>.
1065  *
1066  * The GPU properties are obtained by a call to
1067  * _mali_base_get_gpu_props(). This simply returns a pointer to a const
1068  * base_gpu_props structure. It is constant for the life of a base
1069  * context. Multiple calls to _mali_base_get_gpu_props() to a base context
1070  * return the same pointer to a constant structure. This avoids cache pollution
1071  * of the common data.
1072  *
1073  * This pointer must not be freed, because it does not point to the start of a
1074  * region allocated by the memory allocator; instead, just close the @ref
1075  * base_context.
1076  *
1077  *
1078  * @section sec_base_user_api_gpuprops_config Platform Config Compile-time Properties
1079  *
1080  * The Platform Config File sets up gpu properties that are specific to a
1081  * certain platform. Properties that are 'Implementation Defined' in the
1082  * Midgard Architecture spec are placed here.
1083  *
1084  * @note Reference configurations are provided for Midgard Implementations, such as
1085  * the Mali-T600 family. The customer need not repeat this information, and can select one of
1086  * these reference configurations. For example, VA_BITS, PA_BITS and the
1087  * maximum number of samples per pixel might vary between Midgard Implementations, but
1088  * \b not for platforms using the Mali-T604. This information is placed in
1089  * the reference configuration files.
1090  *
1091  * The System Integrator creates the following structure:
1092  * - platform_XYZ
1093  * - platform_XYZ/plat
1094  * - platform_XYZ/plat/plat_config.h
1095  *
1096  * They then edit plat_config.h, using the example plat_config.h files as a
1097  * guide.
1098  *
1099  * At the very least, the customer must set @ref CONFIG_GPU_CORE_TYPE, and will
1100  * receive a helpful \#error message if they do not do this correctly. This
1101  * selects the Reference Configuration for the Midgard Implementation. The rationale
1102  * behind this decision (against asking the customer to write \#include
1103  * <gpus/mali_t600.h> in their plat_config.h) is as follows:
1104  * - This mechanism 'looks' like a regular config file (such as Linux's
1105  * .config)
1106  * - It is difficult to get wrong in a way that will produce strange build
1107  * errors:
1108  *  - They need not know where the mali_t600.h, other_midg_gpu.h etc. files are stored - and
1109  *  so they won't accidentally pick another file with 'mali_t600' in its name
1110  *  - When the build doesn't work, the System Integrator may think the DDK is
1111  *  doesn't work, and attempt to fix it themselves:
1112  *   - For the @ref CONFIG_GPU_CORE_TYPE mechanism, the only way to get past the
1113  *   error is to set @ref CONFIG_GPU_CORE_TYPE, and this is what the \#error tells
1114  *   you.
1115  *   - For a \#include mechanism, checks must still be made elsewhere, which the
1116  *   System Integrator may try working around by setting \#defines (such as
1117  *   VA_BITS) themselves in their plat_config.h. In the  worst case, they may
1118  *   set the prevention-mechanism \#define of
1119  *   "A_CORRECT_MIDGARD_CORE_WAS_CHOSEN".
1120  *   - In this case, they would believe they are on the right track, because
1121  *   the build progresses with their fix, but with errors elsewhere.
1122  *
1123  * However, there is nothing to prevent the customer using \#include to organize
1124  * their own configurations files hierarchically.
1125  *
1126  * The mechanism for the header file processing is as follows:
1127  *
1128  * @dot
1129    digraph plat_config_mechanism {
1130            rankdir=BT
1131            size="6,6"
1132
1133        "mali_base.h";
1134            "gpu/mali_gpu.h";
1135
1136            node [ shape=box ];
1137            {
1138                rank = same; ordering = out;
1139
1140                    "gpu/mali_gpu_props.h";
1141                    "base/midg_gpus/mali_t600.h";
1142                    "base/midg_gpus/other_midg_gpu.h";
1143            }
1144            { rank = same; "plat/plat_config.h"; }
1145            {
1146                rank = same;
1147                    "gpu/mali_gpu.h" [ shape=box ];
1148                    gpu_chooser [ label="" style="invisible" width=0 height=0 fixedsize=true ];
1149                    select_gpu [ label="Mali-T600 | Other\n(select_gpu.h)" shape=polygon,sides=4,distortion=0.25 width=3.3 height=0.99 fixedsize=true ] ;
1150            }
1151            node [ shape=box ];
1152            { rank = same; "plat/plat_config.h"; }
1153            { rank = same; "mali_base.h"; }
1154
1155            "mali_base.h" -> "gpu/mali_gpu.h" -> "gpu/mali_gpu_props.h";
1156            "mali_base.h" -> "plat/plat_config.h" ;
1157            "mali_base.h" -> select_gpu ;
1158
1159            "plat/plat_config.h" -> gpu_chooser [style="dotted,bold" dir=none weight=4] ;
1160            gpu_chooser -> select_gpu [style="dotted,bold"] ;
1161
1162            select_gpu -> "base/midg_gpus/mali_t600.h" ;
1163            select_gpu -> "base/midg_gpus/other_midg_gpu.h" ;
1164    }
1165    @enddot
1166  *
1167  *
1168  * @section sec_base_user_api_gpuprops_kernel Kernel Operation
1169  *
1170  * During Base Context Create time, user-side makes a single kernel call:
1171  * - A call to fill user memory with GPU information structures
1172  *
1173  * The kernel-side will fill the provided the entire processed @ref base_gpu_props
1174  * structure, because this information is required in both
1175  * user and kernel side; it does not make sense to decode it twice.
1176  *
1177  * Coherency groups must be derived from the bitmasks, but this can be done
1178  * kernel side, and just once at kernel startup: Coherency groups must already
1179  * be known kernel-side, to support chains that specify a 'Only Coherent Group'
1180  * SW requirement, or 'Only Coherent Group with Tiler' SW requirement.
1181  *
1182  * @section sec_base_user_api_gpuprops_cocalc Coherency Group calculation
1183  * Creation of the coherent group data is done at device-driver startup, and so
1184  * is one-time. This will most likely involve a loop with CLZ, shifting, and
1185  * bit clearing on the L2_PRESENT mask, depending on whether the
1186  * system is L2 Coherent. The number of shader cores is done by a
1187  * population count, since faulty cores may be disabled during production,
1188  * producing a non-contiguous mask.
1189  *
1190  * The memory requirements for this algoirthm can be determined either by a u64
1191  * population count on the L2_PRESENT mask (a LUT helper already is
1192  * requried for the above), or simple assumption that there can be no more than
1193  * 16 coherent groups, since core groups are typically 4 cores.
1194  */
1195
1196 /**
1197  * @addtogroup base_user_api_gpuprops User-side Base GPU Property Query APIs
1198  * @{
1199  */
1200
1201 /**
1202  * @addtogroup base_user_api_gpuprops_dyn Dynamic HW Properties
1203  * @{
1204  */
1205
1206 #define BASE_GPU_NUM_TEXTURE_FEATURES_REGISTERS 3
1207
1208 #define BASE_MAX_COHERENT_GROUPS 16
1209
1210 struct mali_base_gpu_core_props {
1211         /**
1212          * Product specific value.
1213          */
1214         u32 product_id;
1215
1216         /**
1217          * Status of the GPU release.
1218      * No defined values, but starts at 0 and increases by one for each release
1219      * status (alpha, beta, EAC, etc.).
1220      * 4 bit values (0-15).
1221          */
1222         u16 version_status;
1223
1224         /**
1225          * Minor release number of the GPU. "P" part of an "RnPn" release number.
1226      * 8 bit values (0-255).
1227          */
1228         u16 minor_revision;
1229
1230         /**
1231          * Major release number of the GPU. "R" part of an "RnPn" release number.
1232      * 4 bit values (0-15).
1233          */
1234         u16 major_revision;
1235
1236         u16 padding;
1237
1238         /**
1239          * @usecase GPU clock speed is not specified in the Midgard Architecture, but is
1240          * <b>necessary for OpenCL's clGetDeviceInfo() function</b>.
1241          */
1242         u32 gpu_speed_mhz;
1243
1244         /**
1245          * @usecase GPU clock max/min speed is required for computing best/worst case
1246          * in tasks as job scheduling ant irq_throttling. (It is not specified in the
1247          *  Midgard Architecture).
1248          */
1249         u32 gpu_freq_khz_max;
1250         u32 gpu_freq_khz_min;
1251
1252         /**
1253          * Size of the shader program counter, in bits.
1254          */
1255         u32 log2_program_counter_size;
1256
1257         /**
1258          * TEXTURE_FEATURES_x registers, as exposed by the GPU. This is a
1259          * bitpattern where a set bit indicates that the format is supported.
1260          *
1261          * Before using a texture format, it is recommended that the corresponding
1262          * bit be checked.
1263          */
1264         u32 texture_features[BASE_GPU_NUM_TEXTURE_FEATURES_REGISTERS];
1265
1266         /**
1267          * Theoretical maximum memory available to the GPU. It is unlikely that a
1268          * client will be able to allocate all of this memory for their own
1269          * purposes, but this at least provides an upper bound on the memory
1270          * available to the GPU.
1271          *
1272          * This is required for OpenCL's clGetDeviceInfo() call when
1273          * CL_DEVICE_GLOBAL_MEM_SIZE is requested, for OpenCL GPU devices. The
1274          * client will not be expecting to allocate anywhere near this value.
1275          */
1276         u64 gpu_available_memory_size;
1277 };
1278
1279 /**
1280  *
1281  * More information is possible - but associativity and bus width are not
1282  * required by upper-level apis.
1283  */
1284 struct mali_base_gpu_l2_cache_props {
1285         u8 log2_line_size;
1286         u8 log2_cache_size;
1287         u8 num_l2_slices; /* Number of L2C slices. 1 or higher */
1288         u8 padding[5];
1289 };
1290
1291 struct mali_base_gpu_tiler_props {
1292         u32 bin_size_bytes;     /* Max is 4*2^15 */
1293         u32 max_active_levels;  /* Max is 2^15 */
1294 };
1295
1296 /**
1297  * GPU threading system details.
1298  */
1299 struct mali_base_gpu_thread_props {
1300         u32 max_threads;            /* Max. number of threads per core */
1301         u32 max_workgroup_size;     /* Max. number of threads per workgroup */
1302         u32 max_barrier_size;       /* Max. number of threads that can synchronize on a simple barrier */
1303         u16 max_registers;          /* Total size [1..65535] of the register file available per core. */
1304         u8  max_task_queue;         /* Max. tasks [1..255] which may be sent to a core before it becomes blocked. */
1305         u8  max_thread_group_split; /* Max. allowed value [1..15] of the Thread Group Split field. */
1306         u8  impl_tech;              /* 0 = Not specified, 1 = Silicon, 2 = FPGA, 3 = SW Model/Emulation */
1307         u8  padding[7];
1308 };
1309
1310 /**
1311  * @brief descriptor for a coherent group
1312  *
1313  * \c core_mask exposes all cores in that coherent group, and \c num_cores
1314  * provides a cached population-count for that mask.
1315  *
1316  * @note Whilst all cores are exposed in the mask, not all may be available to
1317  * the application, depending on the Kernel Power policy.
1318  *
1319  * @note if u64s must be 8-byte aligned, then this structure has 32-bits of wastage.
1320  */
1321 struct mali_base_gpu_coherent_group {
1322         u64 core_mask;         /**< Core restriction mask required for the group */
1323         u16 num_cores;         /**< Number of cores in the group */
1324         u16 padding[3];
1325 };
1326
1327 /**
1328  * @brief Coherency group information
1329  *
1330  * Note that the sizes of the members could be reduced. However, the \c group
1331  * member might be 8-byte aligned to ensure the u64 core_mask is 8-byte
1332  * aligned, thus leading to wastage if the other members sizes were reduced.
1333  *
1334  * The groups are sorted by core mask. The core masks are non-repeating and do
1335  * not intersect.
1336  */
1337 struct mali_base_gpu_coherent_group_info {
1338         u32 num_groups;
1339
1340         /**
1341          * Number of core groups (coherent or not) in the GPU. Equivalent to the number of L2 Caches.
1342          *
1343          * The GPU Counter dumping writes 2048 bytes per core group, regardless of
1344          * whether the core groups are coherent or not. Hence this member is needed
1345          * to calculate how much memory is required for dumping.
1346          *
1347          * @note Do not use it to work out how many valid elements are in the
1348          * group[] member. Use num_groups instead.
1349          */
1350         u32 num_core_groups;
1351
1352         /**
1353          * Coherency features of the memory, accessed by @ref gpu_mem_features
1354          * methods
1355          */
1356         u32 coherency;
1357
1358         u32 padding;
1359
1360         /**
1361          * Descriptors of coherent groups
1362          */
1363         struct mali_base_gpu_coherent_group group[BASE_MAX_COHERENT_GROUPS];
1364 };
1365
1366 /**
1367  * A complete description of the GPU's Hardware Configuration Discovery
1368  * registers.
1369  *
1370  * The information is presented inefficiently for access. For frequent access,
1371  * the values should be better expressed in an unpacked form in the
1372  * base_gpu_props structure.
1373  *
1374  * @usecase The raw properties in @ref gpu_raw_gpu_props are necessary to
1375  * allow a user of the Mali Tools (e.g. PAT) to determine "Why is this device
1376  * behaving differently?". In this case, all information about the
1377  * configuration is potentially useful, but it <b>does not need to be processed
1378  * by the driver</b>. Instead, the raw registers can be processed by the Mali
1379  * Tools software on the host PC.
1380  *
1381  */
1382 struct gpu_raw_gpu_props {
1383         u64 shader_present;
1384         u64 tiler_present;
1385         u64 l2_present;
1386         u64 unused_1; /* keep for backward compatibility */
1387
1388         u32 l2_features;
1389         u32 suspend_size; /* API 8.2+ */
1390         u32 mem_features;
1391         u32 mmu_features;
1392
1393         u32 as_present;
1394
1395         u32 js_present;
1396         u32 js_features[GPU_MAX_JOB_SLOTS];
1397         u32 tiler_features;
1398         u32 texture_features[3];
1399
1400         u32 gpu_id;
1401
1402         u32 thread_max_threads;
1403         u32 thread_max_workgroup_size;
1404         u32 thread_max_barrier_size;
1405         u32 thread_features;
1406
1407         /*
1408          * Note: This is the _selected_ coherency mode rather than the
1409          * available modes as exposed in the coherency_features register.
1410          */
1411         u32 coherency_mode;
1412 };
1413
1414 /**
1415  * Return structure for _mali_base_get_gpu_props().
1416  *
1417  * NOTE: the raw_props member in this datastructure contains the register
1418  * values from which the value of the other members are derived. The derived
1419  * members exist to allow for efficient access and/or shielding the details
1420  * of the layout of the registers.
1421  *
1422  */
1423 typedef struct mali_base_gpu_props {
1424         struct mali_base_gpu_core_props core_props;
1425         struct mali_base_gpu_l2_cache_props l2_props;
1426         u64 unused_1; /* keep for backwards compatibility */
1427         struct mali_base_gpu_tiler_props tiler_props;
1428         struct mali_base_gpu_thread_props thread_props;
1429
1430         /** This member is large, likely to be 128 bytes */
1431         struct gpu_raw_gpu_props raw_props;
1432
1433         /** This must be last member of the structure */
1434         struct mali_base_gpu_coherent_group_info coherency_info;
1435 } base_gpu_props;
1436
1437 /** @} end group base_user_api_gpuprops_dyn */
1438
1439 /** @} end group base_user_api_gpuprops */
1440
1441 /**
1442  * @addtogroup base_user_api_core User-side Base core APIs
1443  * @{
1444  */
1445
1446 /**
1447  * \enum base_context_create_flags
1448  *
1449  * Flags to pass to ::base_context_init.
1450  * Flags can be ORed together to enable multiple things.
1451  *
1452  * These share the same space as @ref basep_context_private_flags, and so must
1453  * not collide with them.
1454  */
1455 enum base_context_create_flags {
1456         /** No flags set */
1457         BASE_CONTEXT_CREATE_FLAG_NONE = 0,
1458
1459         /** Base context is embedded in a cctx object (flag used for CINSTR software counter macros) */
1460         BASE_CONTEXT_CCTX_EMBEDDED = (1u << 0),
1461
1462         /** Base context is a 'System Monitor' context for Hardware counters.
1463          *
1464          * One important side effect of this is that job submission is disabled. */
1465         BASE_CONTEXT_SYSTEM_MONITOR_SUBMIT_DISABLED = (1u << 1)
1466 };
1467
1468 /**
1469  * Bitpattern describing the ::base_context_create_flags that can be passed to base_context_init()
1470  */
1471 #define BASE_CONTEXT_CREATE_ALLOWED_FLAGS \
1472         (((u32)BASE_CONTEXT_CCTX_EMBEDDED) | \
1473           ((u32)BASE_CONTEXT_SYSTEM_MONITOR_SUBMIT_DISABLED))
1474
1475 /**
1476  * Bitpattern describing the ::base_context_create_flags that can be passed to the kernel
1477  */
1478 #define BASE_CONTEXT_CREATE_KERNEL_FLAGS \
1479         ((u32)BASE_CONTEXT_SYSTEM_MONITOR_SUBMIT_DISABLED)
1480
1481 /**
1482  * Private flags used on the base context
1483  *
1484  * These start at bit 31, and run down to zero.
1485  *
1486  * They share the same space as @ref base_context_create_flags, and so must
1487  * not collide with them.
1488  */
1489 enum basep_context_private_flags {
1490         /** Private flag tracking whether job descriptor dumping is disabled */
1491         BASEP_CONTEXT_FLAG_JOB_DUMP_DISABLED = (1 << 31)
1492 };
1493
1494 /** @} end group base_user_api_core */
1495
1496 /** @} end group base_user_api */
1497
1498 /**
1499  * @addtogroup base_plat_config_gpuprops Base Platform Config GPU Properties
1500  * @{
1501  *
1502  * C Pre-processor macros are exposed here to do with Platform
1503  * Config.
1504  *
1505  * These include:
1506  * - GPU Properties that are constant on a particular Midgard Family
1507  * Implementation e.g. Maximum samples per pixel on Mali-T600.
1508  * - General platform config for the GPU, such as the GPU major and minor
1509  * revison.
1510  */
1511
1512 /** @} end group base_plat_config_gpuprops */
1513
1514 /**
1515  * @addtogroup base_api Base APIs
1516  * @{
1517  */
1518
1519 /**
1520  * @brief The payload for a replay job. This must be in GPU memory.
1521  */
1522 typedef struct base_jd_replay_payload {
1523         /**
1524          * Pointer to the first entry in the base_jd_replay_jc list.  These
1525          * will be replayed in @b reverse order (so that extra ones can be added
1526          * to the head in future soft jobs without affecting this soft job)
1527          */
1528         u64 tiler_jc_list;
1529
1530         /**
1531          * Pointer to the fragment job chain.
1532          */
1533         u64 fragment_jc;
1534
1535         /**
1536          * Pointer to the tiler heap free FBD field to be modified.
1537          */
1538         u64 tiler_heap_free;
1539
1540         /**
1541          * Hierarchy mask for the replayed fragment jobs. May be zero.
1542          */
1543         u16 fragment_hierarchy_mask;
1544
1545         /**
1546          * Hierarchy mask for the replayed tiler jobs. May be zero.
1547          */
1548         u16 tiler_hierarchy_mask;
1549
1550         /**
1551          * Default weight to be used for hierarchy levels not in the original
1552          * mask.
1553          */
1554         u32 hierarchy_default_weight;
1555
1556         /**
1557          * Core requirements for the tiler job chain
1558          */
1559         base_jd_core_req tiler_core_req;
1560
1561         /**
1562          * Core requirements for the fragment job chain
1563          */
1564         base_jd_core_req fragment_core_req;
1565
1566         u8 padding[4];
1567 } base_jd_replay_payload;
1568
1569 /**
1570  * @brief An entry in the linked list of job chains to be replayed. This must
1571  *        be in GPU memory.
1572  */
1573 typedef struct base_jd_replay_jc {
1574         /**
1575          * Pointer to next entry in the list. A setting of NULL indicates the
1576          * end of the list.
1577          */
1578         u64 next;
1579
1580         /**
1581          * Pointer to the job chain.
1582          */
1583         u64 jc;
1584
1585 } base_jd_replay_jc;
1586
1587 /* Maximum number of jobs allowed in a fragment chain in the payload of a
1588  * replay job */
1589 #define BASE_JD_REPLAY_F_CHAIN_JOB_LIMIT 256
1590
1591 /** @} end group base_api */
1592
1593 typedef struct base_profiling_controls {
1594         u32 profiling_controls[FBDUMP_CONTROL_MAX];
1595 } base_profiling_controls;
1596
1597 #endif                          /* _BASE_KERNEL_H_ */