]> Git Repo - linux.git/blob - drivers/gpu/drm/i915/i915_utils.h
Merge tag 'for-linus' of git://git.kernel.org/pub/scm/virt/kvm/kvm
[linux.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 #include <linux/sched/clock.h>
34
35 struct drm_i915_private;
36 struct timer_list;
37
38 #define FDO_BUG_URL "https://gitlab.freedesktop.org/drm/intel/-/wikis/How-to-file-i915-bugs"
39
40 #undef WARN_ON
41 /* Many gcc seem to no see through this and fall over :( */
42 #if 0
43 #define WARN_ON(x) ({ \
44         bool __i915_warn_cond = (x); \
45         if (__builtin_constant_p(__i915_warn_cond)) \
46                 BUILD_BUG_ON(__i915_warn_cond); \
47         WARN(__i915_warn_cond, "WARN_ON(" #x ")"); })
48 #else
49 #define WARN_ON(x) WARN((x), "%s", "WARN_ON(" __stringify(x) ")")
50 #endif
51
52 #undef WARN_ON_ONCE
53 #define WARN_ON_ONCE(x) WARN_ONCE((x), "%s", "WARN_ON_ONCE(" __stringify(x) ")")
54
55 #define MISSING_CASE(x) WARN(1, "Missing case (%s == %ld)\n", \
56                              __stringify(x), (long)(x))
57
58 void __printf(3, 4)
59 __i915_printk(struct drm_i915_private *dev_priv, const char *level,
60               const char *fmt, ...);
61
62 #define i915_report_error(dev_priv, fmt, ...)                              \
63         __i915_printk(dev_priv, KERN_ERR, fmt, ##__VA_ARGS__)
64
65 #if IS_ENABLED(CONFIG_DRM_I915_DEBUG)
66
67 int __i915_inject_probe_error(struct drm_i915_private *i915, int err,
68                               const char *func, int line);
69 #define i915_inject_probe_error(_i915, _err) \
70         __i915_inject_probe_error((_i915), (_err), __func__, __LINE__)
71 bool i915_error_injected(void);
72
73 #else
74
75 #define i915_inject_probe_error(i915, e) ({ BUILD_BUG_ON_INVALID(i915); 0; })
76 #define i915_error_injected() false
77
78 #endif
79
80 #define i915_inject_probe_failure(i915) i915_inject_probe_error((i915), -ENODEV)
81
82 #define i915_probe_error(i915, fmt, ...)                                   \
83         __i915_printk(i915, i915_error_injected() ? KERN_DEBUG : KERN_ERR, \
84                       fmt, ##__VA_ARGS__)
85
86 #if defined(GCC_VERSION) && GCC_VERSION >= 70000
87 #define add_overflows_t(T, A, B) \
88         __builtin_add_overflow_p((A), (B), (T)0)
89 #else
90 #define add_overflows_t(T, A, B) ({ \
91         typeof(A) a = (A); \
92         typeof(B) b = (B); \
93         (T)(a + b) < a; \
94 })
95 #endif
96
97 #define add_overflows(A, B) \
98         add_overflows_t(typeof((A) + (B)), (A), (B))
99
100 #define range_overflows(start, size, max) ({ \
101         typeof(start) start__ = (start); \
102         typeof(size) size__ = (size); \
103         typeof(max) max__ = (max); \
104         (void)(&start__ == &size__); \
105         (void)(&start__ == &max__); \
106         start__ >= max__ || size__ > max__ - start__; \
107 })
108
109 #define range_overflows_t(type, start, size, max) \
110         range_overflows((type)(start), (type)(size), (type)(max))
111
112 #define range_overflows_end(start, size, max) ({ \
113         typeof(start) start__ = (start); \
114         typeof(size) size__ = (size); \
115         typeof(max) max__ = (max); \
116         (void)(&start__ == &size__); \
117         (void)(&start__ == &max__); \
118         start__ > max__ || size__ > max__ - start__; \
119 })
120
121 #define range_overflows_end_t(type, start, size, max) \
122         range_overflows_end((type)(start), (type)(size), (type)(max))
123
124 /* Note we don't consider signbits :| */
125 #define overflows_type(x, T) \
126         (sizeof(x) > sizeof(T) && (x) >> BITS_PER_TYPE(T))
127
128 static inline bool
129 __check_struct_size(size_t base, size_t arr, size_t count, size_t *size)
130 {
131         size_t sz;
132
133         if (check_mul_overflow(count, arr, &sz))
134                 return false;
135
136         if (check_add_overflow(sz, base, &sz))
137                 return false;
138
139         *size = sz;
140         return true;
141 }
142
143 /**
144  * check_struct_size() - Calculate size of structure with trailing array.
145  * @p: Pointer to the structure.
146  * @member: Name of the array member.
147  * @n: Number of elements in the array.
148  * @sz: Total size of structure and array
149  *
150  * Calculates size of memory needed for structure @p followed by an
151  * array of @n @member elements, like struct_size() but reports
152  * whether it overflowed, and the resultant size in @sz
153  *
154  * Return: false if the calculation overflowed.
155  */
156 #define check_struct_size(p, member, n, sz) \
157         likely(__check_struct_size(sizeof(*(p)), \
158                                    sizeof(*(p)->member) + __must_be_array((p)->member), \
159                                    n, sz))
160
161 #define ptr_mask_bits(ptr, n) ({                                        \
162         unsigned long __v = (unsigned long)(ptr);                       \
163         (typeof(ptr))(__v & -BIT(n));                                   \
164 })
165
166 #define ptr_unmask_bits(ptr, n) ((unsigned long)(ptr) & (BIT(n) - 1))
167
168 #define ptr_unpack_bits(ptr, bits, n) ({                                \
169         unsigned long __v = (unsigned long)(ptr);                       \
170         *(bits) = __v & (BIT(n) - 1);                                   \
171         (typeof(ptr))(__v & -BIT(n));                                   \
172 })
173
174 #define ptr_pack_bits(ptr, bits, n) ({                                  \
175         unsigned long __bits = (bits);                                  \
176         GEM_BUG_ON(__bits & -BIT(n));                                   \
177         ((typeof(ptr))((unsigned long)(ptr) | __bits));                 \
178 })
179
180 #define ptr_dec(ptr) ({                                                 \
181         unsigned long __v = (unsigned long)(ptr);                       \
182         (typeof(ptr))(__v - 1);                                         \
183 })
184
185 #define ptr_inc(ptr) ({                                                 \
186         unsigned long __v = (unsigned long)(ptr);                       \
187         (typeof(ptr))(__v + 1);                                         \
188 })
189
190 #define page_mask_bits(ptr) ptr_mask_bits(ptr, PAGE_SHIFT)
191 #define page_unmask_bits(ptr) ptr_unmask_bits(ptr, PAGE_SHIFT)
192 #define page_pack_bits(ptr, bits) ptr_pack_bits(ptr, bits, PAGE_SHIFT)
193 #define page_unpack_bits(ptr, bits) ptr_unpack_bits(ptr, bits, PAGE_SHIFT)
194
195 #define struct_member(T, member) (((T *)0)->member)
196
197 #define ptr_offset(ptr, member) offsetof(typeof(*(ptr)), member)
198
199 #define fetch_and_zero(ptr) ({                                          \
200         typeof(*ptr) __T = *(ptr);                                      \
201         *(ptr) = (typeof(*ptr))0;                                       \
202         __T;                                                            \
203 })
204
205 static __always_inline ptrdiff_t ptrdiff(const void *a, const void *b)
206 {
207         return a - b;
208 }
209
210 /*
211  * container_of_user: Extract the superclass from a pointer to a member.
212  *
213  * Exactly like container_of() with the exception that it plays nicely
214  * with sparse for __user @ptr.
215  */
216 #define container_of_user(ptr, type, member) ({                         \
217         void __user *__mptr = (void __user *)(ptr);                     \
218         BUILD_BUG_ON_MSG(!__same_type(*(ptr), struct_member(type, member)) && \
219                          !__same_type(*(ptr), void),                    \
220                          "pointer type mismatch in container_of()");    \
221         ((type __user *)(__mptr - offsetof(type, member))); })
222
223 /*
224  * check_user_mbz: Check that a user value exists and is zero
225  *
226  * Frequently in our uABI we reserve space for future extensions, and
227  * two ensure that userspace is prepared we enforce that space must
228  * be zero. (Then any future extension can safely assume a default value
229  * of 0.)
230  *
231  * check_user_mbz() combines checking that the user pointer is accessible
232  * and that the contained value is zero.
233  *
234  * Returns: -EFAULT if not accessible, -EINVAL if !zero, or 0 on success.
235  */
236 #define check_user_mbz(U) ({                                            \
237         typeof(*(U)) mbz__;                                             \
238         get_user(mbz__, (U)) ? -EFAULT : mbz__ ? -EINVAL : 0;           \
239 })
240
241 static inline u64 ptr_to_u64(const void *ptr)
242 {
243         return (uintptr_t)ptr;
244 }
245
246 #define u64_to_ptr(T, x) ({                                             \
247         typecheck(u64, x);                                              \
248         (T *)(uintptr_t)(x);                                            \
249 })
250
251 #define __mask_next_bit(mask) ({                                        \
252         int __idx = ffs(mask) - 1;                                      \
253         mask &= ~BIT(__idx);                                            \
254         __idx;                                                          \
255 })
256
257 static inline bool is_power_of_2_u64(u64 n)
258 {
259         return (n != 0 && ((n & (n - 1)) == 0));
260 }
261
262 static inline void __list_del_many(struct list_head *head,
263                                    struct list_head *first)
264 {
265         first->prev = head;
266         WRITE_ONCE(head->next, first);
267 }
268
269 static inline int list_is_last_rcu(const struct list_head *list,
270                                    const struct list_head *head)
271 {
272         return READ_ONCE(list->next) == head;
273 }
274
275 static inline unsigned long msecs_to_jiffies_timeout(const unsigned int m)
276 {
277         unsigned long j = msecs_to_jiffies(m);
278
279         return min_t(unsigned long, MAX_JIFFY_OFFSET, j + 1);
280 }
281
282 /*
283  * If you need to wait X milliseconds between events A and B, but event B
284  * doesn't happen exactly after event A, you record the timestamp (jiffies) of
285  * when event A happened, then just before event B you call this function and
286  * pass the timestamp as the first argument, and X as the second argument.
287  */
288 static inline void
289 wait_remaining_ms_from_jiffies(unsigned long timestamp_jiffies, int to_wait_ms)
290 {
291         unsigned long target_jiffies, tmp_jiffies, remaining_jiffies;
292
293         /*
294          * Don't re-read the value of "jiffies" every time since it may change
295          * behind our back and break the math.
296          */
297         tmp_jiffies = jiffies;
298         target_jiffies = timestamp_jiffies +
299                          msecs_to_jiffies_timeout(to_wait_ms);
300
301         if (time_after(target_jiffies, tmp_jiffies)) {
302                 remaining_jiffies = target_jiffies - tmp_jiffies;
303                 while (remaining_jiffies)
304                         remaining_jiffies =
305                             schedule_timeout_uninterruptible(remaining_jiffies);
306         }
307 }
308
309 /**
310  * __wait_for - magic wait macro
311  *
312  * Macro to help avoid open coding check/wait/timeout patterns. Note that it's
313  * important that we check the condition again after having timed out, since the
314  * timeout could be due to preemption or similar and we've never had a chance to
315  * check the condition before the timeout.
316  */
317 #define __wait_for(OP, COND, US, Wmin, Wmax) ({ \
318         const ktime_t end__ = ktime_add_ns(ktime_get_raw(), 1000ll * (US)); \
319         long wait__ = (Wmin); /* recommended min for usleep is 10 us */ \
320         int ret__;                                                      \
321         might_sleep();                                                  \
322         for (;;) {                                                      \
323                 const bool expired__ = ktime_after(ktime_get_raw(), end__); \
324                 OP;                                                     \
325                 /* Guarantee COND check prior to timeout */             \
326                 barrier();                                              \
327                 if (COND) {                                             \
328                         ret__ = 0;                                      \
329                         break;                                          \
330                 }                                                       \
331                 if (expired__) {                                        \
332                         ret__ = -ETIMEDOUT;                             \
333                         break;                                          \
334                 }                                                       \
335                 usleep_range(wait__, wait__ * 2);                       \
336                 if (wait__ < (Wmax))                                    \
337                         wait__ <<= 1;                                   \
338         }                                                               \
339         ret__;                                                          \
340 })
341
342 #define _wait_for(COND, US, Wmin, Wmax) __wait_for(, (COND), (US), (Wmin), \
343                                                    (Wmax))
344 #define wait_for(COND, MS)              _wait_for((COND), (MS) * 1000, 10, 1000)
345
346 /* If CONFIG_PREEMPT_COUNT is disabled, in_atomic() always reports false. */
347 #if defined(CONFIG_DRM_I915_DEBUG) && defined(CONFIG_PREEMPT_COUNT)
348 # define _WAIT_FOR_ATOMIC_CHECK(ATOMIC) WARN_ON_ONCE((ATOMIC) && !in_atomic())
349 #else
350 # define _WAIT_FOR_ATOMIC_CHECK(ATOMIC) do { } while (0)
351 #endif
352
353 #define _wait_for_atomic(COND, US, ATOMIC) \
354 ({ \
355         int cpu, ret, timeout = (US) * 1000; \
356         u64 base; \
357         _WAIT_FOR_ATOMIC_CHECK(ATOMIC); \
358         if (!(ATOMIC)) { \
359                 preempt_disable(); \
360                 cpu = smp_processor_id(); \
361         } \
362         base = local_clock(); \
363         for (;;) { \
364                 u64 now = local_clock(); \
365                 if (!(ATOMIC)) \
366                         preempt_enable(); \
367                 /* Guarantee COND check prior to timeout */ \
368                 barrier(); \
369                 if (COND) { \
370                         ret = 0; \
371                         break; \
372                 } \
373                 if (now - base >= timeout) { \
374                         ret = -ETIMEDOUT; \
375                         break; \
376                 } \
377                 cpu_relax(); \
378                 if (!(ATOMIC)) { \
379                         preempt_disable(); \
380                         if (unlikely(cpu != smp_processor_id())) { \
381                                 timeout -= now - base; \
382                                 cpu = smp_processor_id(); \
383                                 base = local_clock(); \
384                         } \
385                 } \
386         } \
387         ret; \
388 })
389
390 #define wait_for_us(COND, US) \
391 ({ \
392         int ret__; \
393         BUILD_BUG_ON(!__builtin_constant_p(US)); \
394         if ((US) > 10) \
395                 ret__ = _wait_for((COND), (US), 10, 10); \
396         else \
397                 ret__ = _wait_for_atomic((COND), (US), 0); \
398         ret__; \
399 })
400
401 #define wait_for_atomic_us(COND, US) \
402 ({ \
403         BUILD_BUG_ON(!__builtin_constant_p(US)); \
404         BUILD_BUG_ON((US) > 50000); \
405         _wait_for_atomic((COND), (US), 1); \
406 })
407
408 #define wait_for_atomic(COND, MS) wait_for_atomic_us((COND), (MS) * 1000)
409
410 #define KHz(x) (1000 * (x))
411 #define MHz(x) KHz(1000 * (x))
412
413 #define KBps(x) (1000 * (x))
414 #define MBps(x) KBps(1000 * (x))
415 #define GBps(x) ((u64)1000 * MBps((x)))
416
417 static inline const char *yesno(bool v)
418 {
419         return v ? "yes" : "no";
420 }
421
422 static inline const char *onoff(bool v)
423 {
424         return v ? "on" : "off";
425 }
426
427 static inline const char *enabledisable(bool v)
428 {
429         return v ? "enable" : "disable";
430 }
431
432 static inline const char *enableddisabled(bool v)
433 {
434         return v ? "enabled" : "disabled";
435 }
436
437 void add_taint_for_CI(struct drm_i915_private *i915, unsigned int taint);
438 static inline void __add_taint_for_CI(unsigned int taint)
439 {
440         /*
441          * The system is "ok", just about surviving for the user, but
442          * CI results are now unreliable as the HW is very suspect.
443          * CI checks the taint state after every test and will reboot
444          * the machine if the kernel is tainted.
445          */
446         add_taint(taint, LOCKDEP_STILL_OK);
447 }
448
449 void cancel_timer(struct timer_list *t);
450 void set_timer_ms(struct timer_list *t, unsigned long timeout);
451
452 static inline bool timer_active(const struct timer_list *t)
453 {
454         return READ_ONCE(t->expires);
455 }
456
457 static inline bool timer_expired(const struct timer_list *t)
458 {
459         return timer_active(t) && !timer_pending(t);
460 }
461
462 #endif /* !__I915_UTILS_H */
This page took 0.059929 seconds and 4 git commands to generate.