1 /*	$NetBSD: i915_utils.h,v 1.6 2022/05/27 21:02:27 riastradh Exp $	*/
2 
3 /*
4  * Copyright © 2016 Intel Corporation
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice (including the next
14  * paragraph) shall be included in all copies or substantial portions of the
15  * Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23  * IN THE SOFTWARE.
24  *
25  */
26 
27 #ifndef __I915_UTILS_H
28 #define __I915_UTILS_H
29 
30 #include <linux/list.h>
31 #include <linux/overflow.h>
32 #include <linux/sched.h>
33 #include <linux/sched/clock.h>
34 #include <linux/types.h>
35 #include <linux/workqueue.h>
36 
37 struct drm_i915_private;
38 struct timer_list;
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 ")\n"); })
48 #else
49 #define WARN_ON(x) WARN((x), "%s\n", "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) ")\n")
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 /* Note we don't consider signbits :| */
113 #define overflows_type(x, T) \
114 	(sizeof(x) > sizeof(T) && (x) >> BITS_PER_TYPE(T))
115 
116 static inline bool
__check_struct_size(size_t base,size_t arr,size_t count,size_t * size)117 __check_struct_size(size_t base, size_t arr, size_t count, size_t *size)
118 {
119 	size_t sz;
120 
121 	if (check_mul_overflow(count, arr, &sz))
122 		return false;
123 
124 	if (check_add_overflow(sz, base, &sz))
125 		return false;
126 
127 	*size = sz;
128 	return true;
129 }
130 
131 /**
132  * check_struct_size() - Calculate size of structure with trailing array.
133  * @p: Pointer to the structure.
134  * @member: Name of the array member.
135  * @n: Number of elements in the array.
136  * @sz: Total size of structure and array
137  *
138  * Calculates size of memory needed for structure @p followed by an
139  * array of @n @member elements, like struct_size() but reports
140  * whether it overflowed, and the resultant size in @sz
141  *
142  * Return: false if the calculation overflowed.
143  */
144 #define check_struct_size(p, member, n, sz) \
145 	likely(__check_struct_size(sizeof(*(p)), \
146 				   sizeof(*(p)->member) + __must_be_array((p)->member), \
147 				   n, sz))
148 
149 #define ptr_mask_bits(ptr, n) ({					\
150 	unsigned long __v = (unsigned long)(ptr);			\
151 	(typeof(ptr))(__v & -BIT(n));					\
152 })
153 
154 #define ptr_unmask_bits(ptr, n) ((unsigned long)(ptr) & (BIT(n) - 1))
155 
156 #define ptr_unpack_bits(ptr, bits, n) ({				\
157 	unsigned long __v = (unsigned long)(ptr);			\
158 	*(bits) = __v & (BIT(n) - 1);					\
159 	(typeof(ptr))(__v & -BIT(n));					\
160 })
161 
162 #define ptr_pack_bits(ptr, bits, n) ({					\
163 	unsigned long __bits = (bits);					\
164 	GEM_BUG_ON(__bits & -BIT(n));					\
165 	((typeof(ptr))((unsigned long)(ptr) | __bits));			\
166 })
167 
168 #define ptr_dec(ptr) ({							\
169 	unsigned long __v = (unsigned long)(ptr);			\
170 	(typeof(ptr))(__v - 1);						\
171 })
172 
173 #define ptr_inc(ptr) ({							\
174 	unsigned long __v = (unsigned long)(ptr);			\
175 	(typeof(ptr))(__v + 1);						\
176 })
177 
178 #define page_mask_bits(ptr) ptr_mask_bits(ptr, PAGE_SHIFT)
179 #define page_unmask_bits(ptr) ptr_unmask_bits(ptr, PAGE_SHIFT)
180 #define page_pack_bits(ptr, bits) ptr_pack_bits(ptr, bits, PAGE_SHIFT)
181 #define page_unpack_bits(ptr, bits) ptr_unpack_bits(ptr, bits, PAGE_SHIFT)
182 
183 #define struct_member(T, member) (((T *)0)->member)
184 
185 #define ptr_offset(ptr, member) offsetof(typeof(*(ptr)), member)
186 
187 #define fetch_and_zero(ptr) ({						\
188 	typeof(*ptr) __T = *(ptr);					\
189 	*(ptr) = (typeof(*ptr))0;					\
190 	__T;								\
191 })
192 
193 /*
194  * container_of_user: Extract the superclass from a pointer to a member.
195  *
196  * Exactly like container_of() with the exception that it plays nicely
197  * with sparse for __user @ptr.
198  */
199 #define container_of_user(ptr, type, member) ({				\
200 	void __user *__mptr = (void __user *)(ptr);			\
201 	BUILD_BUG_ON_MSG(!__same_type(*(ptr), struct_member(type, member)) && \
202 			 !__same_type(*(ptr), void),			\
203 			 "pointer type mismatch in container_of()");	\
204 	((type __user *)(__mptr - offsetof(type, member))); })
205 
206 /*
207  * check_user_mbz: Check that a user value exists and is zero
208  *
209  * Frequently in our uABI we reserve space for future extensions, and
210  * two ensure that userspace is prepared we enforce that space must
211  * be zero. (Then any future extension can safely assume a default value
212  * of 0.)
213  *
214  * check_user_mbz() combines checking that the user pointer is accessible
215  * and that the contained value is zero.
216  *
217  * Returns: -EFAULT if not accessible, -EINVAL if !zero, or 0 on success.
218  */
219 #define check_user_mbz(U) ({						\
220 	typeof(*(U)) mbz__;						\
221 	get_user(mbz__, (U)) ? -EFAULT : mbz__ ? -EINVAL : 0;		\
222 })
223 
ptr_to_u64(const void * ptr)224 static inline u64 ptr_to_u64(const void *ptr)
225 {
226 	return (uintptr_t)ptr;
227 }
228 
229 #define u64_to_ptr(T, x) ({						\
230 	typecheck(u64, x);						\
231 	(T *)(uintptr_t)(x);						\
232 })
233 
234 #define __mask_next_bit(mask) ({					\
235 	int __idx = ffs(mask) - 1;					\
236 	mask &= ~BIT(__idx);						\
237 	__idx;								\
238 })
239 
__list_del_many(struct list_head * head,struct list_head * first)240 static inline void __list_del_many(struct list_head *head,
241 				   struct list_head *first)
242 {
243 	first->prev = head;
244 	WRITE_ONCE(head->next, first);
245 }
246 
247 /*
248  * Wait until the work is finally complete, even if it tries to postpone
249  * by requeueing itself. Note, that if the worker never cancels itself,
250  * we will spin forever.
251  */
drain_delayed_work(struct delayed_work * dw)252 static inline void drain_delayed_work(struct delayed_work *dw)
253 {
254 	do {
255 		while (flush_delayed_work(dw))
256 			;
257 	} while (delayed_work_pending(dw));
258 }
259 
msecs_to_jiffies_timeout(const unsigned int m)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
wait_remaining_ms_from_jiffies(unsigned long timestamp_jiffies,int to_wait_ms)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 #ifdef __NetBSD__
303 #define __wait_for(OP, COND, US, Wmin, Wmax) ({ \
304 	int ret__ = 0;							\
305 	if (cold) {							\
306 		int ms__ = ((US) + 999)/1000;				\
307 		for (;;) {						\
308 			const bool expired__ = ms__-- == 0;		\
309 			OP;						\
310 			barrier();					\
311 			if (COND) {					\
312 				ret__ = 0;				\
313 				break;					\
314 			}						\
315 			if (expired__) {				\
316 				ret__ = -ETIMEDOUT;			\
317 				break;					\
318 			}						\
319 			DELAY(1000);					\
320 		}							\
321 	} else {							\
322 		const ktime_t end__ =					\
323 		    ktime_add_ns(ktime_get_raw(), 1000ll * (US));	\
324 		long wait__ = (Wmin);					\
325 		might_sleep();						\
326 		for (;;) {						\
327 			const bool expired__ =				\
328 			    ktime_after(ktime_get_raw(), end__);	\
329 			OP;						\
330 			/* Guarantee COND check prior to timeout */	\
331 			barrier();					\
332 			if (COND) {					\
333 				ret__ = 0;				\
334 				break;					\
335 			}						\
336 			if (expired__) {				\
337 				ret__ = -ETIMEDOUT;			\
338 				break;					\
339 			}						\
340 			usleep_range(wait__, wait__ * 2);		\
341 			if (wait__ < (Wmax))				\
342 				wait__ <<= 1;				\
343 		}							\
344 	}								\
345 	ret__;								\
346 })
347 #else	/* !NetBSD */
348 #define __wait_for(OP, COND, US, Wmin, Wmax) ({ \
349 	const ktime_t end__ = ktime_add_ns(ktime_get_raw(), 1000ll * (US)); \
350 	long wait__ = (Wmin); /* recommended min for usleep is 10 us */	\
351 	int ret__;							\
352 	might_sleep();							\
353 	for (;;) {							\
354 		const bool expired__ = ktime_after(ktime_get_raw(), end__); \
355 		OP;							\
356 		/* Guarantee COND check prior to timeout */		\
357 		barrier();						\
358 		if (COND) {						\
359 			ret__ = 0;					\
360 			break;						\
361 		}							\
362 		if (expired__) {					\
363 			ret__ = -ETIMEDOUT;				\
364 			break;						\
365 		}							\
366 		usleep_range(wait__, wait__ * 2);			\
367 		if (wait__ < (Wmax))					\
368 			wait__ <<= 1;					\
369 	}								\
370 	ret__;								\
371 })
372 #endif
373 
374 #define _wait_for(COND, US, Wmin, Wmax)	__wait_for(, (COND), (US), (Wmin), \
375 						   (Wmax))
376 #define wait_for(COND, MS)		_wait_for((COND), (MS) * 1000, 10, 1000)
377 
378 /* If CONFIG_PREEMPT_COUNT is disabled, in_atomic() always reports false. */
379 #if defined(CONFIG_DRM_I915_DEBUG) && defined(CONFIG_PREEMPT_COUNT)
380 # define _WAIT_FOR_ATOMIC_CHECK(ATOMIC) WARN_ON_ONCE((ATOMIC) && !in_atomic())
381 #else
382 # define _WAIT_FOR_ATOMIC_CHECK(ATOMIC) do { } while (0)
383 #endif
384 
385 #define _wait_for_atomic(COND, US, ATOMIC) \
386 ({ \
387 	int cpu, ret, timeout = (US) * 1000; \
388 	u64 base; \
389 	_WAIT_FOR_ATOMIC_CHECK(ATOMIC); \
390 	if (!(ATOMIC)) { \
391 		preempt_disable(); \
392 		cpu = smp_processor_id(); \
393 	} \
394 	base = local_clock(); \
395 	for (;;) { \
396 		u64 now = local_clock(); \
397 		if (!(ATOMIC)) \
398 			preempt_enable(); \
399 		/* Guarantee COND check prior to timeout */ \
400 		barrier(); \
401 		if (COND) { \
402 			ret = 0; \
403 			break; \
404 		} \
405 		if (now - base >= timeout) { \
406 			ret = -ETIMEDOUT; \
407 			break; \
408 		} \
409 		cpu_relax(); \
410 		if (!(ATOMIC)) { \
411 			preempt_disable(); \
412 			if (unlikely(cpu != smp_processor_id())) { \
413 				timeout -= now - base; \
414 				cpu = smp_processor_id(); \
415 				base = local_clock(); \
416 			} \
417 		} \
418 	} \
419 	ret; \
420 })
421 
422 #define wait_for_us(COND, US) \
423 ({ \
424 	int ret__; \
425 	BUILD_BUG_ON(!__builtin_constant_p(US)); \
426 	if ((US) > 10) \
427 		ret__ = _wait_for((COND), (US), 10, 10); \
428 	else \
429 		ret__ = _wait_for_atomic((COND), (US), 0); \
430 	ret__; \
431 })
432 
433 #define wait_for_atomic_us(COND, US) \
434 ({ \
435 	BUILD_BUG_ON(!__builtin_constant_p(US)); \
436 	BUILD_BUG_ON((US) > 50000); \
437 	_wait_for_atomic((COND), (US), 1); \
438 })
439 
440 #define wait_for_atomic(COND, MS) wait_for_atomic_us((COND), (MS) * 1000)
441 
442 #define KHz(x) (1000 * (x))
443 #define MHz(x) KHz(1000 * (x))
444 
445 #define KBps(x) (1000 * (x))
446 #define MBps(x) KBps(1000 * (x))
447 #define GBps(x) ((u64)1000 * MBps((x)))
448 
yesno(bool v)449 static inline const char *yesno(bool v)
450 {
451 	return v ? "yes" : "no";
452 }
453 
onoff(bool v)454 static inline const char *onoff(bool v)
455 {
456 	return v ? "on" : "off";
457 }
458 
enableddisabled(bool v)459 static inline const char *enableddisabled(bool v)
460 {
461 	return v ? "enabled" : "disabled";
462 }
463 
add_taint_for_CI(unsigned int taint)464 static inline void add_taint_for_CI(unsigned int taint)
465 {
466 	/*
467 	 * The system is "ok", just about surviving for the user, but
468 	 * CI results are now unreliable as the HW is very suspect.
469 	 * CI checks the taint state after every test and will reboot
470 	 * the machine if the kernel is tainted.
471 	 */
472 	add_taint(taint, LOCKDEP_STILL_OK);
473 }
474 
475 void cancel_timer(struct timer_list *t);
476 void set_timer_ms(struct timer_list *t, unsigned long timeout);
477 
478 #ifdef __NetBSD__
479 static inline bool
timer_expired(const struct timer_list * t)480 timer_expired(const struct timer_list *t)
481 {
482 	return callout_expired(__UNCONST(&t->tl_callout));
483 }
484 #else
timer_expired(const struct timer_list * t)485 static inline bool timer_expired(const struct timer_list *t)
486 {
487 	return READ_ONCE(t->expires) && !timer_pending(t);
488 }
489 #endif
490 
491 /*
492  * This is a lookalike for IS_ENABLED() that takes a kconfig value,
493  * e.g. CONFIG_DRM_I915_SPIN_REQUEST, and evaluates whether it is non-zero
494  * i.e. whether the configuration is active. Wrapping up the config inside
495  * a boolean context prevents clang and smatch from complaining about potential
496  * issues in confusing logical-&& with bitwise-& for constants.
497  *
498  * Sadly IS_ENABLED() itself does not work with kconfig values.
499  *
500  * Returns 0 if @config is 0, 1 if set to any value.
501  */
502 #define IS_ACTIVE(config) ((config) != 0)
503 
504 #endif /* !__I915_UTILS_H */
505