xref: /linux/drivers/gpu/drm/i915/i915_utils.h (revision 9d106c6dd81bb26ad7fc3ee89cb1d62557c8e2c9)
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 #undef WARN_ON
38 /* Many gcc seem to no see through this and fall over :( */
39 #if 0
40 #define WARN_ON(x) ({ \
41 	bool __i915_warn_cond = (x); \
42 	if (__builtin_constant_p(__i915_warn_cond)) \
43 		BUILD_BUG_ON(__i915_warn_cond); \
44 	WARN(__i915_warn_cond, "WARN_ON(" #x ")"); })
45 #else
46 #define WARN_ON(x) WARN((x), "%s", "WARN_ON(" __stringify(x) ")")
47 #endif
48 
49 #undef WARN_ON_ONCE
50 #define WARN_ON_ONCE(x) WARN_ONCE((x), "%s", "WARN_ON_ONCE(" __stringify(x) ")")
51 
52 #define MISSING_CASE(x) WARN(1, "Missing case (%s == %ld)\n", \
53 			     __stringify(x), (long)(x))
54 
55 void __printf(3, 4)
56 __i915_printk(struct drm_i915_private *dev_priv, const char *level,
57 	      const char *fmt, ...);
58 
59 #define i915_report_error(dev_priv, fmt, ...)				   \
60 	__i915_printk(dev_priv, KERN_ERR, fmt, ##__VA_ARGS__)
61 
62 #if IS_ENABLED(CONFIG_DRM_I915_DEBUG)
63 
64 int __i915_inject_probe_error(struct drm_i915_private *i915, int err,
65 			      const char *func, int line);
66 #define i915_inject_probe_error(_i915, _err) \
67 	__i915_inject_probe_error((_i915), (_err), __func__, __LINE__)
68 bool i915_error_injected(void);
69 
70 #else
71 
72 #define i915_inject_probe_error(i915, e) ({ BUILD_BUG_ON_INVALID(i915); 0; })
73 #define i915_error_injected() false
74 
75 #endif
76 
77 #define i915_inject_probe_failure(i915) i915_inject_probe_error((i915), -ENODEV)
78 
79 #define i915_probe_error(i915, fmt, ...)				   \
80 	__i915_printk(i915, i915_error_injected() ? KERN_DEBUG : KERN_ERR, \
81 		      fmt, ##__VA_ARGS__)
82 
83 #if defined(GCC_VERSION) && GCC_VERSION >= 70000
84 #define add_overflows_t(T, A, B) \
85 	__builtin_add_overflow_p((A), (B), (T)0)
86 #else
87 #define add_overflows_t(T, A, B) ({ \
88 	typeof(A) a = (A); \
89 	typeof(B) b = (B); \
90 	(T)(a + b) < a; \
91 })
92 #endif
93 
94 #define add_overflows(A, B) \
95 	add_overflows_t(typeof((A) + (B)), (A), (B))
96 
97 #define range_overflows(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_t(type, start, size, max) \
107 	range_overflows((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 /*
191  * container_of_user: Extract the superclass from a pointer to a member.
192  *
193  * Exactly like container_of() with the exception that it plays nicely
194  * with sparse for __user @ptr.
195  */
196 #define container_of_user(ptr, type, member) ({				\
197 	void __user *__mptr = (void __user *)(ptr);			\
198 	BUILD_BUG_ON_MSG(!__same_type(*(ptr), struct_member(type, member)) && \
199 			 !__same_type(*(ptr), void),			\
200 			 "pointer type mismatch in container_of()");	\
201 	((type __user *)(__mptr - offsetof(type, member))); })
202 
203 /*
204  * check_user_mbz: Check that a user value exists and is zero
205  *
206  * Frequently in our uABI we reserve space for future extensions, and
207  * two ensure that userspace is prepared we enforce that space must
208  * be zero. (Then any future extension can safely assume a default value
209  * of 0.)
210  *
211  * check_user_mbz() combines checking that the user pointer is accessible
212  * and that the contained value is zero.
213  *
214  * Returns: -EFAULT if not accessible, -EINVAL if !zero, or 0 on success.
215  */
216 #define check_user_mbz(U) ({						\
217 	typeof(*(U)) mbz__;						\
218 	get_user(mbz__, (U)) ? -EFAULT : mbz__ ? -EINVAL : 0;		\
219 })
220 
221 static inline u64 ptr_to_u64(const void *ptr)
222 {
223 	return (uintptr_t)ptr;
224 }
225 
226 #define u64_to_ptr(T, x) ({						\
227 	typecheck(u64, x);						\
228 	(T *)(uintptr_t)(x);						\
229 })
230 
231 #define __mask_next_bit(mask) ({					\
232 	int __idx = ffs(mask) - 1;					\
233 	mask &= ~BIT(__idx);						\
234 	__idx;								\
235 })
236 
237 static inline bool is_power_of_2_u64(u64 n)
238 {
239 	return (n != 0 && ((n & (n - 1)) == 0));
240 }
241 
242 static inline void __list_del_many(struct list_head *head,
243 				   struct list_head *first)
244 {
245 	first->prev = head;
246 	WRITE_ONCE(head->next, first);
247 }
248 
249 /*
250  * Wait until the work is finally complete, even if it tries to postpone
251  * by requeueing itself. Note, that if the worker never cancels itself,
252  * we will spin forever.
253  */
254 static inline void drain_delayed_work(struct delayed_work *dw)
255 {
256 	do {
257 		while (flush_delayed_work(dw))
258 			;
259 	} while (delayed_work_pending(dw));
260 }
261 
262 static inline unsigned long msecs_to_jiffies_timeout(const unsigned int m)
263 {
264 	unsigned long j = msecs_to_jiffies(m);
265 
266 	return min_t(unsigned long, MAX_JIFFY_OFFSET, j + 1);
267 }
268 
269 /*
270  * If you need to wait X milliseconds between events A and B, but event B
271  * doesn't happen exactly after event A, you record the timestamp (jiffies) of
272  * when event A happened, then just before event B you call this function and
273  * pass the timestamp as the first argument, and X as the second argument.
274  */
275 static inline void
276 wait_remaining_ms_from_jiffies(unsigned long timestamp_jiffies, int to_wait_ms)
277 {
278 	unsigned long target_jiffies, tmp_jiffies, remaining_jiffies;
279 
280 	/*
281 	 * Don't re-read the value of "jiffies" every time since it may change
282 	 * behind our back and break the math.
283 	 */
284 	tmp_jiffies = jiffies;
285 	target_jiffies = timestamp_jiffies +
286 			 msecs_to_jiffies_timeout(to_wait_ms);
287 
288 	if (time_after(target_jiffies, tmp_jiffies)) {
289 		remaining_jiffies = target_jiffies - tmp_jiffies;
290 		while (remaining_jiffies)
291 			remaining_jiffies =
292 			    schedule_timeout_uninterruptible(remaining_jiffies);
293 	}
294 }
295 
296 /**
297  * __wait_for - magic wait macro
298  *
299  * Macro to help avoid open coding check/wait/timeout patterns. Note that it's
300  * important that we check the condition again after having timed out, since the
301  * timeout could be due to preemption or similar and we've never had a chance to
302  * check the condition before the timeout.
303  */
304 #define __wait_for(OP, COND, US, Wmin, Wmax) ({ \
305 	const ktime_t end__ = ktime_add_ns(ktime_get_raw(), 1000ll * (US)); \
306 	long wait__ = (Wmin); /* recommended min for usleep is 10 us */	\
307 	int ret__;							\
308 	might_sleep();							\
309 	for (;;) {							\
310 		const bool expired__ = ktime_after(ktime_get_raw(), end__); \
311 		OP;							\
312 		/* Guarantee COND check prior to timeout */		\
313 		barrier();						\
314 		if (COND) {						\
315 			ret__ = 0;					\
316 			break;						\
317 		}							\
318 		if (expired__) {					\
319 			ret__ = -ETIMEDOUT;				\
320 			break;						\
321 		}							\
322 		usleep_range(wait__, wait__ * 2);			\
323 		if (wait__ < (Wmax))					\
324 			wait__ <<= 1;					\
325 	}								\
326 	ret__;								\
327 })
328 
329 #define _wait_for(COND, US, Wmin, Wmax)	__wait_for(, (COND), (US), (Wmin), \
330 						   (Wmax))
331 #define wait_for(COND, MS)		_wait_for((COND), (MS) * 1000, 10, 1000)
332 
333 /* If CONFIG_PREEMPT_COUNT is disabled, in_atomic() always reports false. */
334 #if defined(CONFIG_DRM_I915_DEBUG) && defined(CONFIG_PREEMPT_COUNT)
335 # define _WAIT_FOR_ATOMIC_CHECK(ATOMIC) WARN_ON_ONCE((ATOMIC) && !in_atomic())
336 #else
337 # define _WAIT_FOR_ATOMIC_CHECK(ATOMIC) do { } while (0)
338 #endif
339 
340 #define _wait_for_atomic(COND, US, ATOMIC) \
341 ({ \
342 	int cpu, ret, timeout = (US) * 1000; \
343 	u64 base; \
344 	_WAIT_FOR_ATOMIC_CHECK(ATOMIC); \
345 	if (!(ATOMIC)) { \
346 		preempt_disable(); \
347 		cpu = smp_processor_id(); \
348 	} \
349 	base = local_clock(); \
350 	for (;;) { \
351 		u64 now = local_clock(); \
352 		if (!(ATOMIC)) \
353 			preempt_enable(); \
354 		/* Guarantee COND check prior to timeout */ \
355 		barrier(); \
356 		if (COND) { \
357 			ret = 0; \
358 			break; \
359 		} \
360 		if (now - base >= timeout) { \
361 			ret = -ETIMEDOUT; \
362 			break; \
363 		} \
364 		cpu_relax(); \
365 		if (!(ATOMIC)) { \
366 			preempt_disable(); \
367 			if (unlikely(cpu != smp_processor_id())) { \
368 				timeout -= now - base; \
369 				cpu = smp_processor_id(); \
370 				base = local_clock(); \
371 			} \
372 		} \
373 	} \
374 	ret; \
375 })
376 
377 #define wait_for_us(COND, US) \
378 ({ \
379 	int ret__; \
380 	BUILD_BUG_ON(!__builtin_constant_p(US)); \
381 	if ((US) > 10) \
382 		ret__ = _wait_for((COND), (US), 10, 10); \
383 	else \
384 		ret__ = _wait_for_atomic((COND), (US), 0); \
385 	ret__; \
386 })
387 
388 #define wait_for_atomic_us(COND, US) \
389 ({ \
390 	BUILD_BUG_ON(!__builtin_constant_p(US)); \
391 	BUILD_BUG_ON((US) > 50000); \
392 	_wait_for_atomic((COND), (US), 1); \
393 })
394 
395 #define wait_for_atomic(COND, MS) wait_for_atomic_us((COND), (MS) * 1000)
396 
397 #define KHz(x) (1000 * (x))
398 #define MHz(x) KHz(1000 * (x))
399 
400 #define KBps(x) (1000 * (x))
401 #define MBps(x) KBps(1000 * (x))
402 #define GBps(x) ((u64)1000 * MBps((x)))
403 
404 static inline const char *yesno(bool v)
405 {
406 	return v ? "yes" : "no";
407 }
408 
409 static inline const char *onoff(bool v)
410 {
411 	return v ? "on" : "off";
412 }
413 
414 static inline const char *enableddisabled(bool v)
415 {
416 	return v ? "enabled" : "disabled";
417 }
418 
419 static inline void add_taint_for_CI(unsigned int taint)
420 {
421 	/*
422 	 * The system is "ok", just about surviving for the user, but
423 	 * CI results are now unreliable as the HW is very suspect.
424 	 * CI checks the taint state after every test and will reboot
425 	 * the machine if the kernel is tainted.
426 	 */
427 	add_taint(taint, LOCKDEP_STILL_OK);
428 }
429 
430 void cancel_timer(struct timer_list *t);
431 void set_timer_ms(struct timer_list *t, unsigned long timeout);
432 
433 static inline bool timer_expired(const struct timer_list *t)
434 {
435 	return READ_ONCE(t->expires) && !timer_pending(t);
436 }
437 
438 /*
439  * This is a lookalike for IS_ENABLED() that takes a kconfig value,
440  * e.g. CONFIG_DRM_I915_SPIN_REQUEST, and evaluates whether it is non-zero
441  * i.e. whether the configuration is active. Wrapping up the config inside
442  * a boolean context prevents clang and smatch from complaining about potential
443  * issues in confusing logical-&& with bitwise-& for constants.
444  *
445  * Sadly IS_ENABLED() itself does not work with kconfig values.
446  *
447  * Returns 0 if @config is 0, 1 if set to any value.
448  */
449 #define IS_ACTIVE(config) ((config) != 0)
450 
451 #endif /* !__I915_UTILS_H */
452