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