024a9e224ff3ba624035ee2516e5409cf8a0bc8c
[linux-2.6-microblaze.git] / drivers / gpu / drm / i915 / i915_utils.h
1 /*
2  * Copyright © 2016 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  */
24
25 #ifndef __I915_UTILS_H
26 #define __I915_UTILS_H
27
28 #include <linux/list.h>
29 #include <linux/overflow.h>
30 #include <linux/sched.h>
31 #include <linux/types.h>
32 #include <linux/workqueue.h>
33
34 struct drm_i915_private;
35 struct timer_list;
36
37 #define FDO_BUG_URL "https://gitlab.freedesktop.org/drm/intel/-/wikis/How-to-file-i915-bugs"
38
39 #undef WARN_ON
40 /* Many gcc seem to no see through this and fall over :( */
41 #if 0
42 #define WARN_ON(x) ({ \
43         bool __i915_warn_cond = (x); \
44         if (__builtin_constant_p(__i915_warn_cond)) \
45                 BUILD_BUG_ON(__i915_warn_cond); \
46         WARN(__i915_warn_cond, "WARN_ON(" #x ")"); })
47 #else
48 #define WARN_ON(x) WARN((x), "%s", "WARN_ON(" __stringify(x) ")")
49 #endif
50
51 #undef WARN_ON_ONCE
52 #define WARN_ON_ONCE(x) WARN_ONCE((x), "%s", "WARN_ON_ONCE(" __stringify(x) ")")
53
54 #define MISSING_CASE(x) WARN(1, "Missing case (%s == %ld)\n", \
55                              __stringify(x), (long)(x))
56
57 void __printf(3, 4)
58 __i915_printk(struct drm_i915_private *dev_priv, const char *level,
59               const char *fmt, ...);
60
61 #define i915_report_error(dev_priv, fmt, ...)                              \
62         __i915_printk(dev_priv, KERN_ERR, fmt, ##__VA_ARGS__)
63
64 #if IS_ENABLED(CONFIG_DRM_I915_DEBUG)
65
66 int __i915_inject_probe_error(struct drm_i915_private *i915, int err,
67                               const char *func, int line);
68 #define i915_inject_probe_error(_i915, _err) \
69         __i915_inject_probe_error((_i915), (_err), __func__, __LINE__)
70 bool i915_error_injected(void);
71
72 #else
73
74 #define i915_inject_probe_error(i915, e) ({ BUILD_BUG_ON_INVALID(i915); 0; })
75 #define i915_error_injected() false
76
77 #endif
78
79 #define i915_inject_probe_failure(i915) i915_inject_probe_error((i915), -ENODEV)
80
81 #define i915_probe_error(i915, fmt, ...)                                   \
82         __i915_printk(i915, i915_error_injected() ? KERN_DEBUG : KERN_ERR, \
83                       fmt, ##__VA_ARGS__)
84
85 #if defined(GCC_VERSION) && GCC_VERSION >= 70000
86 #define add_overflows_t(T, A, B) \
87         __builtin_add_overflow_p((A), (B), (T)0)
88 #else
89 #define add_overflows_t(T, A, B) ({ \
90         typeof(A) a = (A); \
91         typeof(B) b = (B); \
92         (T)(a + b) < a; \
93 })
94 #endif
95
96 #define add_overflows(A, B) \
97         add_overflows_t(typeof((A) + (B)), (A), (B))
98
99 #define range_overflows(start, size, max) ({ \
100         typeof(start) start__ = (start); \
101         typeof(size) size__ = (size); \
102         typeof(max) max__ = (max); \
103         (void)(&start__ == &size__); \
104         (void)(&start__ == &max__); \
105         start__ > max__ || size__ > max__ - start__; \
106 })
107
108 #define range_overflows_t(type, start, size, max) \
109         range_overflows((type)(start), (type)(size), (type)(max))
110
111 /* Note we don't consider signbits :| */
112 #define overflows_type(x, T) \
113         (sizeof(x) > sizeof(T) && (x) >> BITS_PER_TYPE(T))
114
115 static inline bool
116 __check_struct_size(size_t base, size_t arr, size_t count, size_t *size)
117 {
118         size_t sz;
119
120         if (check_mul_overflow(count, arr, &sz))
121                 return false;
122
123         if (check_add_overflow(sz, base, &sz))
124                 return false;
125
126         *size = sz;
127         return true;
128 }
129
130 /**
131  * check_struct_size() - Calculate size of structure with trailing array.
132  * @p: Pointer to the structure.
133  * @member: Name of the array member.
134  * @n: Number of elements in the array.
135  * @sz: Total size of structure and array
136  *
137  * Calculates size of memory needed for structure @p followed by an
138  * array of @n @member elements, like struct_size() but reports
139  * whether it overflowed, and the resultant size in @sz
140  *
141  * Return: false if the calculation overflowed.
142  */
143 #define check_struct_size(p, member, n, sz) \
144         likely(__check_struct_size(sizeof(*(p)), \
145                                    sizeof(*(p)->member) + __must_be_array((p)->member), \
146                                    n, sz))
147
148 #define ptr_mask_bits(ptr, n) ({                                        \
149         unsigned long __v = (unsigned long)(ptr);                       \
150         (typeof(ptr))(__v & -BIT(n));                                   \
151 })
152
153 #define ptr_unmask_bits(ptr, n) ((unsigned long)(ptr) & (BIT(n) - 1))
154
155 #define ptr_unpack_bits(ptr, bits, n) ({                                \
156         unsigned long __v = (unsigned long)(ptr);                       \
157         *(bits) = __v & (BIT(n) - 1);                                   \
158         (typeof(ptr))(__v & -BIT(n));                                   \
159 })
160
161 #define ptr_pack_bits(ptr, bits, n) ({                                  \
162         unsigned long __bits = (bits);                                  \
163         GEM_BUG_ON(__bits & -BIT(n));                                   \
164         ((typeof(ptr))((unsigned long)(ptr) | __bits));                 \
165 })
166
167 #define ptr_dec(ptr) ({                                                 \
168         unsigned long __v = (unsigned long)(ptr);                       \
169         (typeof(ptr))(__v - 1);                                         \
170 })
171
172 #define ptr_inc(ptr) ({                                                 \
173         unsigned long __v = (unsigned long)(ptr);                       \
174         (typeof(ptr))(__v + 1);                                         \
175 })
176
177 #define page_mask_bits(ptr) ptr_mask_bits(ptr, PAGE_SHIFT)
178 #define page_unmask_bits(ptr) ptr_unmask_bits(ptr, PAGE_SHIFT)
179 #define page_pack_bits(ptr, bits) ptr_pack_bits(ptr, bits, PAGE_SHIFT)
180 #define page_unpack_bits(ptr, bits) ptr_unpack_bits(ptr, bits, PAGE_SHIFT)
181
182 #define struct_member(T, member) (((T *)0)->member)
183
184 #define ptr_offset(ptr, member) offsetof(typeof(*(ptr)), member)
185
186 #define fetch_and_zero(ptr) ({                                          \
187         typeof(*ptr) __T = *(ptr);                                      \
188         *(ptr) = (typeof(*ptr))0;                                       \
189         __T;                                                            \
190 })
191
192 /*
193  * container_of_user: Extract the superclass from a pointer to a member.
194  *
195  * Exactly like container_of() with the exception that it plays nicely
196  * with sparse for __user @ptr.
197  */
198 #define container_of_user(ptr, type, member) ({                         \
199         void __user *__mptr = (void __user *)(ptr);                     \
200         BUILD_BUG_ON_MSG(!__same_type(*(ptr), struct_member(type, member)) && \
201                          !__same_type(*(ptr), void),                    \
202                          "pointer type mismatch in container_of()");    \
203         ((type __user *)(__mptr - offsetof(type, member))); })
204
205 /*
206  * check_user_mbz: Check that a user value exists and is zero
207  *
208  * Frequently in our uABI we reserve space for future extensions, and
209  * two ensure that userspace is prepared we enforce that space must
210  * be zero. (Then any future extension can safely assume a default value
211  * of 0.)
212  *
213  * check_user_mbz() combines checking that the user pointer is accessible
214  * and that the contained value is zero.
215  *
216  * Returns: -EFAULT if not accessible, -EINVAL if !zero, or 0 on success.
217  */
218 #define check_user_mbz(U) ({                                            \
219         typeof(*(U)) mbz__;                                             \
220         get_user(mbz__, (U)) ? -EFAULT : mbz__ ? -EINVAL : 0;           \
221 })
222
223 static inline u64 ptr_to_u64(const void *ptr)
224 {
225         return (uintptr_t)ptr;
226 }
227
228 #define u64_to_ptr(T, x) ({                                             \
229         typecheck(u64, x);                                              \
230         (T *)(uintptr_t)(x);                                            \
231 })
232
233 #define __mask_next_bit(mask) ({                                        \
234         int __idx = ffs(mask) - 1;                                      \
235         mask &= ~BIT(__idx);                                            \
236         __idx;                                                          \
237 })
238
239 static inline bool is_power_of_2_u64(u64 n)
240 {
241         return (n != 0 && ((n & (n - 1)) == 0));
242 }
243
244 static inline void __list_del_many(struct list_head *head,
245                                    struct list_head *first)
246 {
247         first->prev = head;
248         WRITE_ONCE(head->next, first);
249 }
250
251 /*
252  * Wait until the work is finally complete, even if it tries to postpone
253  * by requeueing itself. Note, that if the worker never cancels itself,
254  * we will spin forever.
255  */
256 static inline void drain_delayed_work(struct delayed_work *dw)
257 {
258         do {
259                 while (flush_delayed_work(dw))
260                         ;
261         } while (delayed_work_pending(dw));
262 }
263
264 static inline unsigned long msecs_to_jiffies_timeout(const unsigned int m)
265 {
266         unsigned long j = msecs_to_jiffies(m);
267
268         return min_t(unsigned long, MAX_JIFFY_OFFSET, j + 1);
269 }
270
271 /*
272  * If you need to wait X milliseconds between events A and B, but event B
273  * doesn't happen exactly after event A, you record the timestamp (jiffies) of
274  * when event A happened, then just before event B you call this function and
275  * pass the timestamp as the first argument, and X as the second argument.
276  */
277 static inline void
278 wait_remaining_ms_from_jiffies(unsigned long timestamp_jiffies, int to_wait_ms)
279 {
280         unsigned long target_jiffies, tmp_jiffies, remaining_jiffies;
281
282         /*
283          * Don't re-read the value of "jiffies" every time since it may change
284          * behind our back and break the math.
285          */
286         tmp_jiffies = jiffies;
287         target_jiffies = timestamp_jiffies +
288                          msecs_to_jiffies_timeout(to_wait_ms);
289
290         if (time_after(target_jiffies, tmp_jiffies)) {
291                 remaining_jiffies = target_jiffies - tmp_jiffies;
292                 while (remaining_jiffies)
293                         remaining_jiffies =
294                             schedule_timeout_uninterruptible(remaining_jiffies);
295         }
296 }
297
298 /**
299  * __wait_for - magic wait macro
300  *
301  * Macro to help avoid open coding check/wait/timeout patterns. Note that it's
302  * important that we check the condition again after having timed out, since the
303  * timeout could be due to preemption or similar and we've never had a chance to
304  * check the condition before the timeout.
305  */
306 #define __wait_for(OP, COND, US, Wmin, Wmax) ({ \
307         const ktime_t end__ = ktime_add_ns(ktime_get_raw(), 1000ll * (US)); \
308         long wait__ = (Wmin); /* recommended min for usleep is 10 us */ \
309         int ret__;                                                      \
310         might_sleep();                                                  \
311         for (;;) {                                                      \
312                 const bool expired__ = ktime_after(ktime_get_raw(), end__); \
313                 OP;                                                     \
314                 /* Guarantee COND check prior to timeout */             \
315                 barrier();                                              \
316                 if (COND) {                                             \
317                         ret__ = 0;                                      \
318                         break;                                          \
319                 }                                                       \
320                 if (expired__) {                                        \
321                         ret__ = -ETIMEDOUT;                             \
322                         break;                                          \
323                 }                                                       \
324                 usleep_range(wait__, wait__ * 2);                       \
325                 if (wait__ < (Wmax))                                    \
326                         wait__ <<= 1;                                   \
327         }                                                               \
328         ret__;                                                          \
329 })
330
331 #define _wait_for(COND, US, Wmin, Wmax) __wait_for(, (COND), (US), (Wmin), \
332                                                    (Wmax))
333 #define wait_for(COND, MS)              _wait_for((COND), (MS) * 1000, 10, 1000)
334
335 /* If CONFIG_PREEMPT_COUNT is disabled, in_atomic() always reports false. */
336 #if defined(CONFIG_DRM_I915_DEBUG) && defined(CONFIG_PREEMPT_COUNT)
337 # define _WAIT_FOR_ATOMIC_CHECK(ATOMIC) WARN_ON_ONCE((ATOMIC) && !in_atomic())
338 #else
339 # define _WAIT_FOR_ATOMIC_CHECK(ATOMIC) do { } while (0)
340 #endif
341
342 #define _wait_for_atomic(COND, US, ATOMIC) \
343 ({ \
344         int cpu, ret, timeout = (US) * 1000; \
345         u64 base; \
346         _WAIT_FOR_ATOMIC_CHECK(ATOMIC); \
347         if (!(ATOMIC)) { \
348                 preempt_disable(); \
349                 cpu = smp_processor_id(); \
350         } \
351         base = local_clock(); \
352         for (;;) { \
353                 u64 now = local_clock(); \
354                 if (!(ATOMIC)) \
355                         preempt_enable(); \
356                 /* Guarantee COND check prior to timeout */ \
357                 barrier(); \
358                 if (COND) { \
359                         ret = 0; \
360                         break; \
361                 } \
362                 if (now - base >= timeout) { \
363                         ret = -ETIMEDOUT; \
364                         break; \
365                 } \
366                 cpu_relax(); \
367                 if (!(ATOMIC)) { \
368                         preempt_disable(); \
369                         if (unlikely(cpu != smp_processor_id())) { \
370                                 timeout -= now - base; \
371                                 cpu = smp_processor_id(); \
372                                 base = local_clock(); \
373                         } \
374                 } \
375         } \
376         ret; \
377 })
378
379 #define wait_for_us(COND, US) \
380 ({ \
381         int ret__; \
382         BUILD_BUG_ON(!__builtin_constant_p(US)); \
383         if ((US) > 10) \
384                 ret__ = _wait_for((COND), (US), 10, 10); \
385         else \
386                 ret__ = _wait_for_atomic((COND), (US), 0); \
387         ret__; \
388 })
389
390 #define wait_for_atomic_us(COND, US) \
391 ({ \
392         BUILD_BUG_ON(!__builtin_constant_p(US)); \
393         BUILD_BUG_ON((US) > 50000); \
394         _wait_for_atomic((COND), (US), 1); \
395 })
396
397 #define wait_for_atomic(COND, MS) wait_for_atomic_us((COND), (MS) * 1000)
398
399 #define KHz(x) (1000 * (x))
400 #define MHz(x) KHz(1000 * (x))
401
402 #define KBps(x) (1000 * (x))
403 #define MBps(x) KBps(1000 * (x))
404 #define GBps(x) ((u64)1000 * MBps((x)))
405
406 static inline const char *yesno(bool v)
407 {
408         return v ? "yes" : "no";
409 }
410
411 static inline const char *onoff(bool v)
412 {
413         return v ? "on" : "off";
414 }
415
416 static inline const char *enableddisabled(bool v)
417 {
418         return v ? "enabled" : "disabled";
419 }
420
421 static inline void add_taint_for_CI(unsigned int taint)
422 {
423         /*
424          * The system is "ok", just about surviving for the user, but
425          * CI results are now unreliable as the HW is very suspect.
426          * CI checks the taint state after every test and will reboot
427          * the machine if the kernel is tainted.
428          */
429         add_taint(taint, LOCKDEP_STILL_OK);
430 }
431
432 void cancel_timer(struct timer_list *t);
433 void set_timer_ms(struct timer_list *t, unsigned long timeout);
434
435 static inline bool timer_expired(const struct timer_list *t)
436 {
437         return READ_ONCE(t->expires) && !timer_pending(t);
438 }
439
440 /*
441  * This is a lookalike for IS_ENABLED() that takes a kconfig value,
442  * e.g. CONFIG_DRM_I915_SPIN_REQUEST, and evaluates whether it is non-zero
443  * i.e. whether the configuration is active. Wrapping up the config inside
444  * a boolean context prevents clang and smatch from complaining about potential
445  * issues in confusing logical-&& with bitwise-& for constants.
446  *
447  * Sadly IS_ENABLED() itself does not work with kconfig values.
448  *
449  * Returns 0 if @config is 0, 1 if set to any value.
450  */
451 #define IS_ACTIVE(config) ((config) != 0)
452
453 #endif /* !__I915_UTILS_H */