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