xref: /linux/drivers/gpu/drm/i915/i915_utils.h (revision 520f8350)
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 #define range_overflows_end(start, size, max) ({ \
112 	typeof(start) start__ = (start); \
113 	typeof(size) size__ = (size); \
114 	typeof(max) max__ = (max); \
115 	(void)(&start__ == &size__); \
116 	(void)(&start__ == &max__); \
117 	start__ > max__ || size__ > max__ - start__; \
118 })
119 
120 #define range_overflows_end_t(type, start, size, max) \
121 	range_overflows_end((type)(start), (type)(size), (type)(max))
122 
123 /* Note we don't consider signbits :| */
124 #define overflows_type(x, T) \
125 	(sizeof(x) > sizeof(T) && (x) >> BITS_PER_TYPE(T))
126 
127 static inline bool
128 __check_struct_size(size_t base, size_t arr, size_t count, size_t *size)
129 {
130 	size_t sz;
131 
132 	if (check_mul_overflow(count, arr, &sz))
133 		return false;
134 
135 	if (check_add_overflow(sz, base, &sz))
136 		return false;
137 
138 	*size = sz;
139 	return true;
140 }
141 
142 /**
143  * check_struct_size() - Calculate size of structure with trailing array.
144  * @p: Pointer to the structure.
145  * @member: Name of the array member.
146  * @n: Number of elements in the array.
147  * @sz: Total size of structure and array
148  *
149  * Calculates size of memory needed for structure @p followed by an
150  * array of @n @member elements, like struct_size() but reports
151  * whether it overflowed, and the resultant size in @sz
152  *
153  * Return: false if the calculation overflowed.
154  */
155 #define check_struct_size(p, member, n, sz) \
156 	likely(__check_struct_size(sizeof(*(p)), \
157 				   sizeof(*(p)->member) + __must_be_array((p)->member), \
158 				   n, sz))
159 
160 #define ptr_mask_bits(ptr, n) ({					\
161 	unsigned long __v = (unsigned long)(ptr);			\
162 	(typeof(ptr))(__v & -BIT(n));					\
163 })
164 
165 #define ptr_unmask_bits(ptr, n) ((unsigned long)(ptr) & (BIT(n) - 1))
166 
167 #define ptr_unpack_bits(ptr, bits, n) ({				\
168 	unsigned long __v = (unsigned long)(ptr);			\
169 	*(bits) = __v & (BIT(n) - 1);					\
170 	(typeof(ptr))(__v & -BIT(n));					\
171 })
172 
173 #define ptr_pack_bits(ptr, bits, n) ({					\
174 	unsigned long __bits = (bits);					\
175 	GEM_BUG_ON(__bits & -BIT(n));					\
176 	((typeof(ptr))((unsigned long)(ptr) | __bits));			\
177 })
178 
179 #define ptr_dec(ptr) ({							\
180 	unsigned long __v = (unsigned long)(ptr);			\
181 	(typeof(ptr))(__v - 1);						\
182 })
183 
184 #define ptr_inc(ptr) ({							\
185 	unsigned long __v = (unsigned long)(ptr);			\
186 	(typeof(ptr))(__v + 1);						\
187 })
188 
189 #define page_mask_bits(ptr) ptr_mask_bits(ptr, PAGE_SHIFT)
190 #define page_unmask_bits(ptr) ptr_unmask_bits(ptr, PAGE_SHIFT)
191 #define page_pack_bits(ptr, bits) ptr_pack_bits(ptr, bits, PAGE_SHIFT)
192 #define page_unpack_bits(ptr, bits) ptr_unpack_bits(ptr, bits, PAGE_SHIFT)
193 
194 #define struct_member(T, member) (((T *)0)->member)
195 
196 #define ptr_offset(ptr, member) offsetof(typeof(*(ptr)), member)
197 
198 #define fetch_and_zero(ptr) ({						\
199 	typeof(*ptr) __T = *(ptr);					\
200 	*(ptr) = (typeof(*ptr))0;					\
201 	__T;								\
202 })
203 
204 /*
205  * container_of_user: Extract the superclass from a pointer to a member.
206  *
207  * Exactly like container_of() with the exception that it plays nicely
208  * with sparse for __user @ptr.
209  */
210 #define container_of_user(ptr, type, member) ({				\
211 	void __user *__mptr = (void __user *)(ptr);			\
212 	BUILD_BUG_ON_MSG(!__same_type(*(ptr), struct_member(type, member)) && \
213 			 !__same_type(*(ptr), void),			\
214 			 "pointer type mismatch in container_of()");	\
215 	((type __user *)(__mptr - offsetof(type, member))); })
216 
217 /*
218  * check_user_mbz: Check that a user value exists and is zero
219  *
220  * Frequently in our uABI we reserve space for future extensions, and
221  * two ensure that userspace is prepared we enforce that space must
222  * be zero. (Then any future extension can safely assume a default value
223  * of 0.)
224  *
225  * check_user_mbz() combines checking that the user pointer is accessible
226  * and that the contained value is zero.
227  *
228  * Returns: -EFAULT if not accessible, -EINVAL if !zero, or 0 on success.
229  */
230 #define check_user_mbz(U) ({						\
231 	typeof(*(U)) mbz__;						\
232 	get_user(mbz__, (U)) ? -EFAULT : mbz__ ? -EINVAL : 0;		\
233 })
234 
235 static inline u64 ptr_to_u64(const void *ptr)
236 {
237 	return (uintptr_t)ptr;
238 }
239 
240 #define u64_to_ptr(T, x) ({						\
241 	typecheck(u64, x);						\
242 	(T *)(uintptr_t)(x);						\
243 })
244 
245 #define __mask_next_bit(mask) ({					\
246 	int __idx = ffs(mask) - 1;					\
247 	mask &= ~BIT(__idx);						\
248 	__idx;								\
249 })
250 
251 static inline bool is_power_of_2_u64(u64 n)
252 {
253 	return (n != 0 && ((n & (n - 1)) == 0));
254 }
255 
256 static inline void __list_del_many(struct list_head *head,
257 				   struct list_head *first)
258 {
259 	first->prev = head;
260 	WRITE_ONCE(head->next, first);
261 }
262 
263 /*
264  * Wait until the work is finally complete, even if it tries to postpone
265  * by requeueing itself. Note, that if the worker never cancels itself,
266  * we will spin forever.
267  */
268 static inline void drain_delayed_work(struct delayed_work *dw)
269 {
270 	do {
271 		while (flush_delayed_work(dw))
272 			;
273 	} while (delayed_work_pending(dw));
274 }
275 
276 static inline unsigned long msecs_to_jiffies_timeout(const unsigned int m)
277 {
278 	unsigned long j = msecs_to_jiffies(m);
279 
280 	return min_t(unsigned long, MAX_JIFFY_OFFSET, j + 1);
281 }
282 
283 /*
284  * If you need to wait X milliseconds between events A and B, but event B
285  * doesn't happen exactly after event A, you record the timestamp (jiffies) of
286  * when event A happened, then just before event B you call this function and
287  * pass the timestamp as the first argument, and X as the second argument.
288  */
289 static inline void
290 wait_remaining_ms_from_jiffies(unsigned long timestamp_jiffies, int to_wait_ms)
291 {
292 	unsigned long target_jiffies, tmp_jiffies, remaining_jiffies;
293 
294 	/*
295 	 * Don't re-read the value of "jiffies" every time since it may change
296 	 * behind our back and break the math.
297 	 */
298 	tmp_jiffies = jiffies;
299 	target_jiffies = timestamp_jiffies +
300 			 msecs_to_jiffies_timeout(to_wait_ms);
301 
302 	if (time_after(target_jiffies, tmp_jiffies)) {
303 		remaining_jiffies = target_jiffies - tmp_jiffies;
304 		while (remaining_jiffies)
305 			remaining_jiffies =
306 			    schedule_timeout_uninterruptible(remaining_jiffies);
307 	}
308 }
309 
310 /**
311  * __wait_for - magic wait macro
312  *
313  * Macro to help avoid open coding check/wait/timeout patterns. Note that it's
314  * important that we check the condition again after having timed out, since the
315  * timeout could be due to preemption or similar and we've never had a chance to
316  * check the condition before the timeout.
317  */
318 #define __wait_for(OP, COND, US, Wmin, Wmax) ({ \
319 	const ktime_t end__ = ktime_add_ns(ktime_get_raw(), 1000ll * (US)); \
320 	long wait__ = (Wmin); /* recommended min for usleep is 10 us */	\
321 	int ret__;							\
322 	might_sleep();							\
323 	for (;;) {							\
324 		const bool expired__ = ktime_after(ktime_get_raw(), end__); \
325 		OP;							\
326 		/* Guarantee COND check prior to timeout */		\
327 		barrier();						\
328 		if (COND) {						\
329 			ret__ = 0;					\
330 			break;						\
331 		}							\
332 		if (expired__) {					\
333 			ret__ = -ETIMEDOUT;				\
334 			break;						\
335 		}							\
336 		usleep_range(wait__, wait__ * 2);			\
337 		if (wait__ < (Wmax))					\
338 			wait__ <<= 1;					\
339 	}								\
340 	ret__;								\
341 })
342 
343 #define _wait_for(COND, US, Wmin, Wmax)	__wait_for(, (COND), (US), (Wmin), \
344 						   (Wmax))
345 #define wait_for(COND, MS)		_wait_for((COND), (MS) * 1000, 10, 1000)
346 
347 /* If CONFIG_PREEMPT_COUNT is disabled, in_atomic() always reports false. */
348 #if defined(CONFIG_DRM_I915_DEBUG) && defined(CONFIG_PREEMPT_COUNT)
349 # define _WAIT_FOR_ATOMIC_CHECK(ATOMIC) WARN_ON_ONCE((ATOMIC) && !in_atomic())
350 #else
351 # define _WAIT_FOR_ATOMIC_CHECK(ATOMIC) do { } while (0)
352 #endif
353 
354 #define _wait_for_atomic(COND, US, ATOMIC) \
355 ({ \
356 	int cpu, ret, timeout = (US) * 1000; \
357 	u64 base; \
358 	_WAIT_FOR_ATOMIC_CHECK(ATOMIC); \
359 	if (!(ATOMIC)) { \
360 		preempt_disable(); \
361 		cpu = smp_processor_id(); \
362 	} \
363 	base = local_clock(); \
364 	for (;;) { \
365 		u64 now = local_clock(); \
366 		if (!(ATOMIC)) \
367 			preempt_enable(); \
368 		/* Guarantee COND check prior to timeout */ \
369 		barrier(); \
370 		if (COND) { \
371 			ret = 0; \
372 			break; \
373 		} \
374 		if (now - base >= timeout) { \
375 			ret = -ETIMEDOUT; \
376 			break; \
377 		} \
378 		cpu_relax(); \
379 		if (!(ATOMIC)) { \
380 			preempt_disable(); \
381 			if (unlikely(cpu != smp_processor_id())) { \
382 				timeout -= now - base; \
383 				cpu = smp_processor_id(); \
384 				base = local_clock(); \
385 			} \
386 		} \
387 	} \
388 	ret; \
389 })
390 
391 #define wait_for_us(COND, US) \
392 ({ \
393 	int ret__; \
394 	BUILD_BUG_ON(!__builtin_constant_p(US)); \
395 	if ((US) > 10) \
396 		ret__ = _wait_for((COND), (US), 10, 10); \
397 	else \
398 		ret__ = _wait_for_atomic((COND), (US), 0); \
399 	ret__; \
400 })
401 
402 #define wait_for_atomic_us(COND, US) \
403 ({ \
404 	BUILD_BUG_ON(!__builtin_constant_p(US)); \
405 	BUILD_BUG_ON((US) > 50000); \
406 	_wait_for_atomic((COND), (US), 1); \
407 })
408 
409 #define wait_for_atomic(COND, MS) wait_for_atomic_us((COND), (MS) * 1000)
410 
411 #define KHz(x) (1000 * (x))
412 #define MHz(x) KHz(1000 * (x))
413 
414 #define KBps(x) (1000 * (x))
415 #define MBps(x) KBps(1000 * (x))
416 #define GBps(x) ((u64)1000 * MBps((x)))
417 
418 static inline const char *yesno(bool v)
419 {
420 	return v ? "yes" : "no";
421 }
422 
423 static inline const char *onoff(bool v)
424 {
425 	return v ? "on" : "off";
426 }
427 
428 static inline const char *enableddisabled(bool v)
429 {
430 	return v ? "enabled" : "disabled";
431 }
432 
433 static inline void add_taint_for_CI(unsigned int taint)
434 {
435 	/*
436 	 * The system is "ok", just about surviving for the user, but
437 	 * CI results are now unreliable as the HW is very suspect.
438 	 * CI checks the taint state after every test and will reboot
439 	 * the machine if the kernel is tainted.
440 	 */
441 	add_taint(taint, LOCKDEP_STILL_OK);
442 }
443 
444 void cancel_timer(struct timer_list *t);
445 void set_timer_ms(struct timer_list *t, unsigned long timeout);
446 
447 static inline bool timer_expired(const struct timer_list *t)
448 {
449 	return READ_ONCE(t->expires) && !timer_pending(t);
450 }
451 
452 /*
453  * This is a lookalike for IS_ENABLED() that takes a kconfig value,
454  * e.g. CONFIG_DRM_I915_SPIN_REQUEST, and evaluates whether it is non-zero
455  * i.e. whether the configuration is active. Wrapping up the config inside
456  * a boolean context prevents clang and smatch from complaining about potential
457  * issues in confusing logical-&& with bitwise-& for constants.
458  *
459  * Sadly IS_ENABLED() itself does not work with kconfig values.
460  *
461  * Returns 0 if @config is 0, 1 if set to any value.
462  */
463 #define IS_ACTIVE(config) ((config) != 0)
464 
465 #endif /* !__I915_UTILS_H */
466