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