1 /*
2  * Copyright (C) 2014 Red Hat
3  * Copyright (C) 2014 Intel Corp.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  * Rob Clark <robdclark@gmail.com>
25  * Daniel Vetter <daniel.vetter@ffwll.ch>
26  */
27 
28 #include <linux/dma-fence.h>
29 #include <linux/ktime.h>
30 
31 #include <drm/drm_atomic.h>
32 #include <drm/drm_atomic_helper.h>
33 #include <drm/drm_atomic_uapi.h>
34 #include <drm/drm_bridge.h>
35 #include <drm/drm_damage_helper.h>
36 #include <drm/drm_device.h>
37 #include <drm/drm_plane_helper.h>
38 #include <drm/drm_print.h>
39 #include <drm/drm_self_refresh_helper.h>
40 #include <drm/drm_vblank.h>
41 #include <drm/drm_writeback.h>
42 
43 #include "drm_crtc_helper_internal.h"
44 #include "drm_crtc_internal.h"
45 
46 /**
47  * DOC: overview
48  *
49  * This helper library provides implementations of check and commit functions on
50  * top of the CRTC modeset helper callbacks and the plane helper callbacks. It
51  * also provides convenience implementations for the atomic state handling
52  * callbacks for drivers which don't need to subclass the drm core structures to
53  * add their own additional internal state.
54  *
55  * This library also provides default implementations for the check callback in
56  * drm_atomic_helper_check() and for the commit callback with
57  * drm_atomic_helper_commit(). But the individual stages and callbacks are
58  * exposed to allow drivers to mix and match and e.g. use the plane helpers only
59  * together with a driver private modeset implementation.
60  *
61  * This library also provides implementations for all the legacy driver
62  * interfaces on top of the atomic interface. See drm_atomic_helper_set_config(),
63  * drm_atomic_helper_disable_plane(), drm_atomic_helper_disable_plane() and the
64  * various functions to implement set_property callbacks. New drivers must not
65  * implement these functions themselves but must use the provided helpers.
66  *
67  * The atomic helper uses the same function table structures as all other
68  * modesetting helpers. See the documentation for &struct drm_crtc_helper_funcs,
69  * struct &drm_encoder_helper_funcs and &struct drm_connector_helper_funcs. It
70  * also shares the &struct drm_plane_helper_funcs function table with the plane
71  * helpers.
72  */
73 static void
74 drm_atomic_helper_plane_changed(struct drm_atomic_state *state,
75 				struct drm_plane_state *old_plane_state,
76 				struct drm_plane_state *plane_state,
77 				struct drm_plane *plane)
78 {
79 	struct drm_crtc_state *crtc_state;
80 
81 	if (old_plane_state->crtc) {
82 		crtc_state = drm_atomic_get_new_crtc_state(state,
83 							   old_plane_state->crtc);
84 
85 		if (WARN_ON(!crtc_state))
86 			return;
87 
88 		crtc_state->planes_changed = true;
89 	}
90 
91 	if (plane_state->crtc) {
92 		crtc_state = drm_atomic_get_new_crtc_state(state, plane_state->crtc);
93 
94 		if (WARN_ON(!crtc_state))
95 			return;
96 
97 		crtc_state->planes_changed = true;
98 	}
99 }
100 
101 static int handle_conflicting_encoders(struct drm_atomic_state *state,
102 				       bool disable_conflicting_encoders)
103 {
104 	struct drm_connector_state *new_conn_state;
105 	struct drm_connector *connector;
106 	struct drm_connector_list_iter conn_iter;
107 	struct drm_encoder *encoder;
108 	unsigned encoder_mask = 0;
109 	int i, ret = 0;
110 
111 	/*
112 	 * First loop, find all newly assigned encoders from the connectors
113 	 * part of the state. If the same encoder is assigned to multiple
114 	 * connectors bail out.
115 	 */
116 	for_each_new_connector_in_state(state, connector, new_conn_state, i) {
117 		const struct drm_connector_helper_funcs *funcs = connector->helper_private;
118 		struct drm_encoder *new_encoder;
119 
120 		if (!new_conn_state->crtc)
121 			continue;
122 
123 		if (funcs->atomic_best_encoder)
124 			new_encoder = funcs->atomic_best_encoder(connector, new_conn_state);
125 		else if (funcs->best_encoder)
126 			new_encoder = funcs->best_encoder(connector);
127 		else
128 			new_encoder = drm_connector_get_single_encoder(connector);
129 
130 		if (new_encoder) {
131 			if (encoder_mask & drm_encoder_mask(new_encoder)) {
132 				DRM_DEBUG_ATOMIC("[ENCODER:%d:%s] on [CONNECTOR:%d:%s] already assigned\n",
133 					new_encoder->base.id, new_encoder->name,
134 					connector->base.id, connector->name);
135 
136 				return -EINVAL;
137 			}
138 
139 			encoder_mask |= drm_encoder_mask(new_encoder);
140 		}
141 	}
142 
143 	if (!encoder_mask)
144 		return 0;
145 
146 	/*
147 	 * Second loop, iterate over all connectors not part of the state.
148 	 *
149 	 * If a conflicting encoder is found and disable_conflicting_encoders
150 	 * is not set, an error is returned. Userspace can provide a solution
151 	 * through the atomic ioctl.
152 	 *
153 	 * If the flag is set conflicting connectors are removed from the CRTC
154 	 * and the CRTC is disabled if no encoder is left. This preserves
155 	 * compatibility with the legacy set_config behavior.
156 	 */
157 	drm_connector_list_iter_begin(state->dev, &conn_iter);
158 	drm_for_each_connector_iter(connector, &conn_iter) {
159 		struct drm_crtc_state *crtc_state;
160 
161 		if (drm_atomic_get_new_connector_state(state, connector))
162 			continue;
163 
164 		encoder = connector->state->best_encoder;
165 		if (!encoder || !(encoder_mask & drm_encoder_mask(encoder)))
166 			continue;
167 
168 		if (!disable_conflicting_encoders) {
169 			DRM_DEBUG_ATOMIC("[ENCODER:%d:%s] in use on [CRTC:%d:%s] by [CONNECTOR:%d:%s]\n",
170 					 encoder->base.id, encoder->name,
171 					 connector->state->crtc->base.id,
172 					 connector->state->crtc->name,
173 					 connector->base.id, connector->name);
174 			ret = -EINVAL;
175 			goto out;
176 		}
177 
178 		new_conn_state = drm_atomic_get_connector_state(state, connector);
179 		if (IS_ERR(new_conn_state)) {
180 			ret = PTR_ERR(new_conn_state);
181 			goto out;
182 		}
183 
184 		DRM_DEBUG_ATOMIC("[ENCODER:%d:%s] in use on [CRTC:%d:%s], disabling [CONNECTOR:%d:%s]\n",
185 				 encoder->base.id, encoder->name,
186 				 new_conn_state->crtc->base.id, new_conn_state->crtc->name,
187 				 connector->base.id, connector->name);
188 
189 		crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
190 
191 		ret = drm_atomic_set_crtc_for_connector(new_conn_state, NULL);
192 		if (ret)
193 			goto out;
194 
195 		if (!crtc_state->connector_mask) {
196 			ret = drm_atomic_set_mode_prop_for_crtc(crtc_state,
197 								NULL);
198 			if (ret < 0)
199 				goto out;
200 
201 			crtc_state->active = false;
202 		}
203 	}
204 out:
205 	drm_connector_list_iter_end(&conn_iter);
206 
207 	return ret;
208 }
209 
210 static void
211 set_best_encoder(struct drm_atomic_state *state,
212 		 struct drm_connector_state *conn_state,
213 		 struct drm_encoder *encoder)
214 {
215 	struct drm_crtc_state *crtc_state;
216 	struct drm_crtc *crtc;
217 
218 	if (conn_state->best_encoder) {
219 		/* Unset the encoder_mask in the old crtc state. */
220 		crtc = conn_state->connector->state->crtc;
221 
222 		/* A NULL crtc is an error here because we should have
223 		 * duplicated a NULL best_encoder when crtc was NULL.
224 		 * As an exception restoring duplicated atomic state
225 		 * during resume is allowed, so don't warn when
226 		 * best_encoder is equal to encoder we intend to set.
227 		 */
228 		WARN_ON(!crtc && encoder != conn_state->best_encoder);
229 		if (crtc) {
230 			crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
231 
232 			crtc_state->encoder_mask &=
233 				~drm_encoder_mask(conn_state->best_encoder);
234 		}
235 	}
236 
237 	if (encoder) {
238 		crtc = conn_state->crtc;
239 		WARN_ON(!crtc);
240 		if (crtc) {
241 			crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
242 
243 			crtc_state->encoder_mask |=
244 				drm_encoder_mask(encoder);
245 		}
246 	}
247 
248 	conn_state->best_encoder = encoder;
249 }
250 
251 static void
252 steal_encoder(struct drm_atomic_state *state,
253 	      struct drm_encoder *encoder)
254 {
255 	struct drm_crtc_state *crtc_state;
256 	struct drm_connector *connector;
257 	struct drm_connector_state *old_connector_state, *new_connector_state;
258 	int i;
259 
260 	for_each_oldnew_connector_in_state(state, connector, old_connector_state, new_connector_state, i) {
261 		struct drm_crtc *encoder_crtc;
262 
263 		if (new_connector_state->best_encoder != encoder)
264 			continue;
265 
266 		encoder_crtc = old_connector_state->crtc;
267 
268 		DRM_DEBUG_ATOMIC("[ENCODER:%d:%s] in use on [CRTC:%d:%s], stealing it\n",
269 				 encoder->base.id, encoder->name,
270 				 encoder_crtc->base.id, encoder_crtc->name);
271 
272 		set_best_encoder(state, new_connector_state, NULL);
273 
274 		crtc_state = drm_atomic_get_new_crtc_state(state, encoder_crtc);
275 		crtc_state->connectors_changed = true;
276 
277 		return;
278 	}
279 }
280 
281 static int
282 update_connector_routing(struct drm_atomic_state *state,
283 			 struct drm_connector *connector,
284 			 struct drm_connector_state *old_connector_state,
285 			 struct drm_connector_state *new_connector_state)
286 {
287 	const struct drm_connector_helper_funcs *funcs;
288 	struct drm_encoder *new_encoder;
289 	struct drm_crtc_state *crtc_state;
290 
291 	DRM_DEBUG_ATOMIC("Updating routing for [CONNECTOR:%d:%s]\n",
292 			 connector->base.id,
293 			 connector->name);
294 
295 	if (old_connector_state->crtc != new_connector_state->crtc) {
296 		if (old_connector_state->crtc) {
297 			crtc_state = drm_atomic_get_new_crtc_state(state, old_connector_state->crtc);
298 			crtc_state->connectors_changed = true;
299 		}
300 
301 		if (new_connector_state->crtc) {
302 			crtc_state = drm_atomic_get_new_crtc_state(state, new_connector_state->crtc);
303 			crtc_state->connectors_changed = true;
304 		}
305 	}
306 
307 	if (!new_connector_state->crtc) {
308 		DRM_DEBUG_ATOMIC("Disabling [CONNECTOR:%d:%s]\n",
309 				connector->base.id,
310 				connector->name);
311 
312 		set_best_encoder(state, new_connector_state, NULL);
313 
314 		return 0;
315 	}
316 
317 	crtc_state = drm_atomic_get_new_crtc_state(state,
318 						   new_connector_state->crtc);
319 	/*
320 	 * For compatibility with legacy users, we want to make sure that
321 	 * we allow DPMS On->Off modesets on unregistered connectors. Modesets
322 	 * which would result in anything else must be considered invalid, to
323 	 * avoid turning on new displays on dead connectors.
324 	 *
325 	 * Since the connector can be unregistered at any point during an
326 	 * atomic check or commit, this is racy. But that's OK: all we care
327 	 * about is ensuring that userspace can't do anything but shut off the
328 	 * display on a connector that was destroyed after it's been notified,
329 	 * not before.
330 	 *
331 	 * Additionally, we also want to ignore connector registration when
332 	 * we're trying to restore an atomic state during system resume since
333 	 * there's a chance the connector may have been destroyed during the
334 	 * process, but it's better to ignore that then cause
335 	 * drm_atomic_helper_resume() to fail.
336 	 */
337 	if (!state->duplicated && drm_connector_is_unregistered(connector) &&
338 	    crtc_state->active) {
339 		DRM_DEBUG_ATOMIC("[CONNECTOR:%d:%s] is not registered\n",
340 				 connector->base.id, connector->name);
341 		return -EINVAL;
342 	}
343 
344 	funcs = connector->helper_private;
345 
346 	if (funcs->atomic_best_encoder)
347 		new_encoder = funcs->atomic_best_encoder(connector,
348 							 new_connector_state);
349 	else if (funcs->best_encoder)
350 		new_encoder = funcs->best_encoder(connector);
351 	else
352 		new_encoder = drm_connector_get_single_encoder(connector);
353 
354 	if (!new_encoder) {
355 		DRM_DEBUG_ATOMIC("No suitable encoder found for [CONNECTOR:%d:%s]\n",
356 				 connector->base.id,
357 				 connector->name);
358 		return -EINVAL;
359 	}
360 
361 	if (!drm_encoder_crtc_ok(new_encoder, new_connector_state->crtc)) {
362 		DRM_DEBUG_ATOMIC("[ENCODER:%d:%s] incompatible with [CRTC:%d:%s]\n",
363 				 new_encoder->base.id,
364 				 new_encoder->name,
365 				 new_connector_state->crtc->base.id,
366 				 new_connector_state->crtc->name);
367 		return -EINVAL;
368 	}
369 
370 	if (new_encoder == new_connector_state->best_encoder) {
371 		set_best_encoder(state, new_connector_state, new_encoder);
372 
373 		DRM_DEBUG_ATOMIC("[CONNECTOR:%d:%s] keeps [ENCODER:%d:%s], now on [CRTC:%d:%s]\n",
374 				 connector->base.id,
375 				 connector->name,
376 				 new_encoder->base.id,
377 				 new_encoder->name,
378 				 new_connector_state->crtc->base.id,
379 				 new_connector_state->crtc->name);
380 
381 		return 0;
382 	}
383 
384 	steal_encoder(state, new_encoder);
385 
386 	set_best_encoder(state, new_connector_state, new_encoder);
387 
388 	crtc_state->connectors_changed = true;
389 
390 	DRM_DEBUG_ATOMIC("[CONNECTOR:%d:%s] using [ENCODER:%d:%s] on [CRTC:%d:%s]\n",
391 			 connector->base.id,
392 			 connector->name,
393 			 new_encoder->base.id,
394 			 new_encoder->name,
395 			 new_connector_state->crtc->base.id,
396 			 new_connector_state->crtc->name);
397 
398 	return 0;
399 }
400 
401 static int
402 mode_fixup(struct drm_atomic_state *state)
403 {
404 	struct drm_crtc *crtc;
405 	struct drm_crtc_state *new_crtc_state;
406 	struct drm_connector *connector;
407 	struct drm_connector_state *new_conn_state;
408 	int i;
409 	int ret;
410 
411 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
412 		if (!new_crtc_state->mode_changed &&
413 		    !new_crtc_state->connectors_changed)
414 			continue;
415 
416 		drm_mode_copy(&new_crtc_state->adjusted_mode, &new_crtc_state->mode);
417 	}
418 
419 	for_each_new_connector_in_state(state, connector, new_conn_state, i) {
420 		const struct drm_encoder_helper_funcs *funcs;
421 		struct drm_encoder *encoder;
422 		struct drm_bridge *bridge;
423 
424 		WARN_ON(!!new_conn_state->best_encoder != !!new_conn_state->crtc);
425 
426 		if (!new_conn_state->crtc || !new_conn_state->best_encoder)
427 			continue;
428 
429 		new_crtc_state =
430 			drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
431 
432 		/*
433 		 * Each encoder has at most one connector (since we always steal
434 		 * it away), so we won't call ->mode_fixup twice.
435 		 */
436 		encoder = new_conn_state->best_encoder;
437 		funcs = encoder->helper_private;
438 
439 		bridge = drm_bridge_chain_get_first_bridge(encoder);
440 		ret = drm_atomic_bridge_chain_check(bridge,
441 						    new_crtc_state,
442 						    new_conn_state);
443 		if (ret) {
444 			DRM_DEBUG_ATOMIC("Bridge atomic check failed\n");
445 			return ret;
446 		}
447 
448 		if (funcs && funcs->atomic_check) {
449 			ret = funcs->atomic_check(encoder, new_crtc_state,
450 						  new_conn_state);
451 			if (ret) {
452 				DRM_DEBUG_ATOMIC("[ENCODER:%d:%s] check failed\n",
453 						 encoder->base.id, encoder->name);
454 				return ret;
455 			}
456 		} else if (funcs && funcs->mode_fixup) {
457 			ret = funcs->mode_fixup(encoder, &new_crtc_state->mode,
458 						&new_crtc_state->adjusted_mode);
459 			if (!ret) {
460 				DRM_DEBUG_ATOMIC("[ENCODER:%d:%s] fixup failed\n",
461 						 encoder->base.id, encoder->name);
462 				return -EINVAL;
463 			}
464 		}
465 	}
466 
467 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
468 		const struct drm_crtc_helper_funcs *funcs;
469 
470 		if (!new_crtc_state->enable)
471 			continue;
472 
473 		if (!new_crtc_state->mode_changed &&
474 		    !new_crtc_state->connectors_changed)
475 			continue;
476 
477 		funcs = crtc->helper_private;
478 		if (!funcs || !funcs->mode_fixup)
479 			continue;
480 
481 		ret = funcs->mode_fixup(crtc, &new_crtc_state->mode,
482 					&new_crtc_state->adjusted_mode);
483 		if (!ret) {
484 			DRM_DEBUG_ATOMIC("[CRTC:%d:%s] fixup failed\n",
485 					 crtc->base.id, crtc->name);
486 			return -EINVAL;
487 		}
488 	}
489 
490 	return 0;
491 }
492 
493 static enum drm_mode_status mode_valid_path(struct drm_connector *connector,
494 					    struct drm_encoder *encoder,
495 					    struct drm_crtc *crtc,
496 					    const struct drm_display_mode *mode)
497 {
498 	struct drm_bridge *bridge;
499 	enum drm_mode_status ret;
500 
501 	ret = drm_encoder_mode_valid(encoder, mode);
502 	if (ret != MODE_OK) {
503 		DRM_DEBUG_ATOMIC("[ENCODER:%d:%s] mode_valid() failed\n",
504 				encoder->base.id, encoder->name);
505 		return ret;
506 	}
507 
508 	bridge = drm_bridge_chain_get_first_bridge(encoder);
509 	ret = drm_bridge_chain_mode_valid(bridge, mode);
510 	if (ret != MODE_OK) {
511 		DRM_DEBUG_ATOMIC("[BRIDGE] mode_valid() failed\n");
512 		return ret;
513 	}
514 
515 	ret = drm_crtc_mode_valid(crtc, mode);
516 	if (ret != MODE_OK) {
517 		DRM_DEBUG_ATOMIC("[CRTC:%d:%s] mode_valid() failed\n",
518 				crtc->base.id, crtc->name);
519 		return ret;
520 	}
521 
522 	return ret;
523 }
524 
525 static int
526 mode_valid(struct drm_atomic_state *state)
527 {
528 	struct drm_connector_state *conn_state;
529 	struct drm_connector *connector;
530 	int i;
531 
532 	for_each_new_connector_in_state(state, connector, conn_state, i) {
533 		struct drm_encoder *encoder = conn_state->best_encoder;
534 		struct drm_crtc *crtc = conn_state->crtc;
535 		struct drm_crtc_state *crtc_state;
536 		enum drm_mode_status mode_status;
537 		const struct drm_display_mode *mode;
538 
539 		if (!crtc || !encoder)
540 			continue;
541 
542 		crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
543 		if (!crtc_state)
544 			continue;
545 		if (!crtc_state->mode_changed && !crtc_state->connectors_changed)
546 			continue;
547 
548 		mode = &crtc_state->mode;
549 
550 		mode_status = mode_valid_path(connector, encoder, crtc, mode);
551 		if (mode_status != MODE_OK)
552 			return -EINVAL;
553 	}
554 
555 	return 0;
556 }
557 
558 /**
559  * drm_atomic_helper_check_modeset - validate state object for modeset changes
560  * @dev: DRM device
561  * @state: the driver state object
562  *
563  * Check the state object to see if the requested state is physically possible.
564  * This does all the CRTC and connector related computations for an atomic
565  * update and adds any additional connectors needed for full modesets. It calls
566  * the various per-object callbacks in the follow order:
567  *
568  * 1. &drm_connector_helper_funcs.atomic_best_encoder for determining the new encoder.
569  * 2. &drm_connector_helper_funcs.atomic_check to validate the connector state.
570  * 3. If it's determined a modeset is needed then all connectors on the affected
571  *    CRTC are added and &drm_connector_helper_funcs.atomic_check is run on them.
572  * 4. &drm_encoder_helper_funcs.mode_valid, &drm_bridge_funcs.mode_valid and
573  *    &drm_crtc_helper_funcs.mode_valid are called on the affected components.
574  * 5. &drm_bridge_funcs.mode_fixup is called on all encoder bridges.
575  * 6. &drm_encoder_helper_funcs.atomic_check is called to validate any encoder state.
576  *    This function is only called when the encoder will be part of a configured CRTC,
577  *    it must not be used for implementing connector property validation.
578  *    If this function is NULL, &drm_atomic_encoder_helper_funcs.mode_fixup is called
579  *    instead.
580  * 7. &drm_crtc_helper_funcs.mode_fixup is called last, to fix up the mode with CRTC constraints.
581  *
582  * &drm_crtc_state.mode_changed is set when the input mode is changed.
583  * &drm_crtc_state.connectors_changed is set when a connector is added or
584  * removed from the CRTC.  &drm_crtc_state.active_changed is set when
585  * &drm_crtc_state.active changes, which is used for DPMS.
586  * &drm_crtc_state.no_vblank is set from the result of drm_dev_has_vblank().
587  * See also: drm_atomic_crtc_needs_modeset()
588  *
589  * IMPORTANT:
590  *
591  * Drivers which set &drm_crtc_state.mode_changed (e.g. in their
592  * &drm_plane_helper_funcs.atomic_check hooks if a plane update can't be done
593  * without a full modeset) _must_ call this function afterwards after that
594  * change. It is permitted to call this function multiple times for the same
595  * update, e.g. when the &drm_crtc_helper_funcs.atomic_check functions depend
596  * upon the adjusted dotclock for fifo space allocation and watermark
597  * computation.
598  *
599  * RETURNS:
600  * Zero for success or -errno
601  */
602 int
603 drm_atomic_helper_check_modeset(struct drm_device *dev,
604 				struct drm_atomic_state *state)
605 {
606 	struct drm_crtc *crtc;
607 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
608 	struct drm_connector *connector;
609 	struct drm_connector_state *old_connector_state, *new_connector_state;
610 	int i, ret;
611 	unsigned connectors_mask = 0;
612 
613 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
614 		bool has_connectors =
615 			!!new_crtc_state->connector_mask;
616 
617 		WARN_ON(!drm_modeset_is_locked(&crtc->mutex));
618 
619 		if (!drm_mode_equal(&old_crtc_state->mode, &new_crtc_state->mode)) {
620 			DRM_DEBUG_ATOMIC("[CRTC:%d:%s] mode changed\n",
621 					 crtc->base.id, crtc->name);
622 			new_crtc_state->mode_changed = true;
623 		}
624 
625 		if (old_crtc_state->enable != new_crtc_state->enable) {
626 			DRM_DEBUG_ATOMIC("[CRTC:%d:%s] enable changed\n",
627 					 crtc->base.id, crtc->name);
628 
629 			/*
630 			 * For clarity this assignment is done here, but
631 			 * enable == 0 is only true when there are no
632 			 * connectors and a NULL mode.
633 			 *
634 			 * The other way around is true as well. enable != 0
635 			 * iff connectors are attached and a mode is set.
636 			 */
637 			new_crtc_state->mode_changed = true;
638 			new_crtc_state->connectors_changed = true;
639 		}
640 
641 		if (old_crtc_state->active != new_crtc_state->active) {
642 			DRM_DEBUG_ATOMIC("[CRTC:%d:%s] active changed\n",
643 					 crtc->base.id, crtc->name);
644 			new_crtc_state->active_changed = true;
645 		}
646 
647 		if (new_crtc_state->enable != has_connectors) {
648 			DRM_DEBUG_ATOMIC("[CRTC:%d:%s] enabled/connectors mismatch\n",
649 					 crtc->base.id, crtc->name);
650 
651 			return -EINVAL;
652 		}
653 
654 		if (drm_dev_has_vblank(dev))
655 			new_crtc_state->no_vblank = false;
656 		else
657 			new_crtc_state->no_vblank = true;
658 	}
659 
660 	ret = handle_conflicting_encoders(state, false);
661 	if (ret)
662 		return ret;
663 
664 	for_each_oldnew_connector_in_state(state, connector, old_connector_state, new_connector_state, i) {
665 		const struct drm_connector_helper_funcs *funcs = connector->helper_private;
666 
667 		WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
668 
669 		/*
670 		 * This only sets crtc->connectors_changed for routing changes,
671 		 * drivers must set crtc->connectors_changed themselves when
672 		 * connector properties need to be updated.
673 		 */
674 		ret = update_connector_routing(state, connector,
675 					       old_connector_state,
676 					       new_connector_state);
677 		if (ret)
678 			return ret;
679 		if (old_connector_state->crtc) {
680 			new_crtc_state = drm_atomic_get_new_crtc_state(state,
681 								       old_connector_state->crtc);
682 			if (old_connector_state->link_status !=
683 			    new_connector_state->link_status)
684 				new_crtc_state->connectors_changed = true;
685 
686 			if (old_connector_state->max_requested_bpc !=
687 			    new_connector_state->max_requested_bpc)
688 				new_crtc_state->connectors_changed = true;
689 		}
690 
691 		if (funcs->atomic_check)
692 			ret = funcs->atomic_check(connector, state);
693 		if (ret)
694 			return ret;
695 
696 		connectors_mask |= BIT(i);
697 	}
698 
699 	/*
700 	 * After all the routing has been prepared we need to add in any
701 	 * connector which is itself unchanged, but whose CRTC changes its
702 	 * configuration. This must be done before calling mode_fixup in case a
703 	 * crtc only changed its mode but has the same set of connectors.
704 	 */
705 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
706 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
707 			continue;
708 
709 		DRM_DEBUG_ATOMIC("[CRTC:%d:%s] needs all connectors, enable: %c, active: %c\n",
710 				 crtc->base.id, crtc->name,
711 				 new_crtc_state->enable ? 'y' : 'n',
712 				 new_crtc_state->active ? 'y' : 'n');
713 
714 		ret = drm_atomic_add_affected_connectors(state, crtc);
715 		if (ret != 0)
716 			return ret;
717 
718 		ret = drm_atomic_add_affected_planes(state, crtc);
719 		if (ret != 0)
720 			return ret;
721 	}
722 
723 	/*
724 	 * Iterate over all connectors again, to make sure atomic_check()
725 	 * has been called on them when a modeset is forced.
726 	 */
727 	for_each_oldnew_connector_in_state(state, connector, old_connector_state, new_connector_state, i) {
728 		const struct drm_connector_helper_funcs *funcs = connector->helper_private;
729 
730 		if (connectors_mask & BIT(i))
731 			continue;
732 
733 		if (funcs->atomic_check)
734 			ret = funcs->atomic_check(connector, state);
735 		if (ret)
736 			return ret;
737 	}
738 
739 	/*
740 	 * Iterate over all connectors again, and add all affected bridges to
741 	 * the state.
742 	 */
743 	for_each_oldnew_connector_in_state(state, connector,
744 					   old_connector_state,
745 					   new_connector_state, i) {
746 		struct drm_encoder *encoder;
747 
748 		encoder = old_connector_state->best_encoder;
749 		ret = drm_atomic_add_encoder_bridges(state, encoder);
750 		if (ret)
751 			return ret;
752 
753 		encoder = new_connector_state->best_encoder;
754 		ret = drm_atomic_add_encoder_bridges(state, encoder);
755 		if (ret)
756 			return ret;
757 	}
758 
759 	ret = mode_valid(state);
760 	if (ret)
761 		return ret;
762 
763 	return mode_fixup(state);
764 }
765 EXPORT_SYMBOL(drm_atomic_helper_check_modeset);
766 
767 /**
768  * drm_atomic_helper_check_plane_state() - Check plane state for validity
769  * @plane_state: plane state to check
770  * @crtc_state: CRTC state to check
771  * @min_scale: minimum @src:@dest scaling factor in 16.16 fixed point
772  * @max_scale: maximum @src:@dest scaling factor in 16.16 fixed point
773  * @can_position: is it legal to position the plane such that it
774  *                doesn't cover the entire CRTC?  This will generally
775  *                only be false for primary planes.
776  * @can_update_disabled: can the plane be updated while the CRTC
777  *                       is disabled?
778  *
779  * Checks that a desired plane update is valid, and updates various
780  * bits of derived state (clipped coordinates etc.). Drivers that provide
781  * their own plane handling rather than helper-provided implementations may
782  * still wish to call this function to avoid duplication of error checking
783  * code.
784  *
785  * RETURNS:
786  * Zero if update appears valid, error code on failure
787  */
788 int drm_atomic_helper_check_plane_state(struct drm_plane_state *plane_state,
789 					const struct drm_crtc_state *crtc_state,
790 					int min_scale,
791 					int max_scale,
792 					bool can_position,
793 					bool can_update_disabled)
794 {
795 	struct drm_framebuffer *fb = plane_state->fb;
796 	struct drm_rect *src = &plane_state->src;
797 	struct drm_rect *dst = &plane_state->dst;
798 	unsigned int rotation = plane_state->rotation;
799 	struct drm_rect clip = {};
800 	int hscale, vscale;
801 
802 	WARN_ON(plane_state->crtc && plane_state->crtc != crtc_state->crtc);
803 
804 	*src = drm_plane_state_src(plane_state);
805 	*dst = drm_plane_state_dest(plane_state);
806 
807 	if (!fb) {
808 		plane_state->visible = false;
809 		return 0;
810 	}
811 
812 	/* crtc should only be NULL when disabling (i.e., !fb) */
813 	if (WARN_ON(!plane_state->crtc)) {
814 		plane_state->visible = false;
815 		return 0;
816 	}
817 
818 	if (!crtc_state->enable && !can_update_disabled) {
819 		DRM_DEBUG_KMS("Cannot update plane of a disabled CRTC.\n");
820 		return -EINVAL;
821 	}
822 
823 	drm_rect_rotate(src, fb->width << 16, fb->height << 16, rotation);
824 
825 	/* Check scaling */
826 	hscale = drm_rect_calc_hscale(src, dst, min_scale, max_scale);
827 	vscale = drm_rect_calc_vscale(src, dst, min_scale, max_scale);
828 	if (hscale < 0 || vscale < 0) {
829 		DRM_DEBUG_KMS("Invalid scaling of plane\n");
830 		drm_rect_debug_print("src: ", &plane_state->src, true);
831 		drm_rect_debug_print("dst: ", &plane_state->dst, false);
832 		return -ERANGE;
833 	}
834 
835 	if (crtc_state->enable)
836 		drm_mode_get_hv_timing(&crtc_state->mode, &clip.x2, &clip.y2);
837 
838 	plane_state->visible = drm_rect_clip_scaled(src, dst, &clip);
839 
840 	drm_rect_rotate_inv(src, fb->width << 16, fb->height << 16, rotation);
841 
842 	if (!plane_state->visible)
843 		/*
844 		 * Plane isn't visible; some drivers can handle this
845 		 * so we just return success here.  Drivers that can't
846 		 * (including those that use the primary plane helper's
847 		 * update function) will return an error from their
848 		 * update_plane handler.
849 		 */
850 		return 0;
851 
852 	if (!can_position && !drm_rect_equals(dst, &clip)) {
853 		DRM_DEBUG_KMS("Plane must cover entire CRTC\n");
854 		drm_rect_debug_print("dst: ", dst, false);
855 		drm_rect_debug_print("clip: ", &clip, false);
856 		return -EINVAL;
857 	}
858 
859 	return 0;
860 }
861 EXPORT_SYMBOL(drm_atomic_helper_check_plane_state);
862 
863 /**
864  * drm_atomic_helper_check_planes - validate state object for planes changes
865  * @dev: DRM device
866  * @state: the driver state object
867  *
868  * Check the state object to see if the requested state is physically possible.
869  * This does all the plane update related checks using by calling into the
870  * &drm_crtc_helper_funcs.atomic_check and &drm_plane_helper_funcs.atomic_check
871  * hooks provided by the driver.
872  *
873  * It also sets &drm_crtc_state.planes_changed to indicate that a CRTC has
874  * updated planes.
875  *
876  * RETURNS:
877  * Zero for success or -errno
878  */
879 int
880 drm_atomic_helper_check_planes(struct drm_device *dev,
881 			       struct drm_atomic_state *state)
882 {
883 	struct drm_crtc *crtc;
884 	struct drm_crtc_state *new_crtc_state;
885 	struct drm_plane *plane;
886 	struct drm_plane_state *new_plane_state, *old_plane_state;
887 	int i, ret = 0;
888 
889 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
890 		const struct drm_plane_helper_funcs *funcs;
891 
892 		WARN_ON(!drm_modeset_is_locked(&plane->mutex));
893 
894 		funcs = plane->helper_private;
895 
896 		drm_atomic_helper_plane_changed(state, old_plane_state, new_plane_state, plane);
897 
898 		drm_atomic_helper_check_plane_damage(state, new_plane_state);
899 
900 		if (!funcs || !funcs->atomic_check)
901 			continue;
902 
903 		ret = funcs->atomic_check(plane, new_plane_state);
904 		if (ret) {
905 			DRM_DEBUG_ATOMIC("[PLANE:%d:%s] atomic driver check failed\n",
906 					 plane->base.id, plane->name);
907 			return ret;
908 		}
909 	}
910 
911 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
912 		const struct drm_crtc_helper_funcs *funcs;
913 
914 		funcs = crtc->helper_private;
915 
916 		if (!funcs || !funcs->atomic_check)
917 			continue;
918 
919 		ret = funcs->atomic_check(crtc, new_crtc_state);
920 		if (ret) {
921 			DRM_DEBUG_ATOMIC("[CRTC:%d:%s] atomic driver check failed\n",
922 					 crtc->base.id, crtc->name);
923 			return ret;
924 		}
925 	}
926 
927 	return ret;
928 }
929 EXPORT_SYMBOL(drm_atomic_helper_check_planes);
930 
931 /**
932  * drm_atomic_helper_check - validate state object
933  * @dev: DRM device
934  * @state: the driver state object
935  *
936  * Check the state object to see if the requested state is physically possible.
937  * Only CRTCs and planes have check callbacks, so for any additional (global)
938  * checking that a driver needs it can simply wrap that around this function.
939  * Drivers without such needs can directly use this as their
940  * &drm_mode_config_funcs.atomic_check callback.
941  *
942  * This just wraps the two parts of the state checking for planes and modeset
943  * state in the default order: First it calls drm_atomic_helper_check_modeset()
944  * and then drm_atomic_helper_check_planes(). The assumption is that the
945  * @drm_plane_helper_funcs.atomic_check and @drm_crtc_helper_funcs.atomic_check
946  * functions depend upon an updated adjusted_mode.clock to e.g. properly compute
947  * watermarks.
948  *
949  * Note that zpos normalization will add all enable planes to the state which
950  * might not desired for some drivers.
951  * For example enable/disable of a cursor plane which have fixed zpos value
952  * would trigger all other enabled planes to be forced to the state change.
953  *
954  * RETURNS:
955  * Zero for success or -errno
956  */
957 int drm_atomic_helper_check(struct drm_device *dev,
958 			    struct drm_atomic_state *state)
959 {
960 	int ret;
961 
962 	ret = drm_atomic_helper_check_modeset(dev, state);
963 	if (ret)
964 		return ret;
965 
966 	if (dev->mode_config.normalize_zpos) {
967 		ret = drm_atomic_normalize_zpos(dev, state);
968 		if (ret)
969 			return ret;
970 	}
971 
972 	ret = drm_atomic_helper_check_planes(dev, state);
973 	if (ret)
974 		return ret;
975 
976 	if (state->legacy_cursor_update)
977 		state->async_update = !drm_atomic_helper_async_check(dev, state);
978 
979 	drm_self_refresh_helper_alter_state(state);
980 
981 	return ret;
982 }
983 EXPORT_SYMBOL(drm_atomic_helper_check);
984 
985 static bool
986 crtc_needs_disable(struct drm_crtc_state *old_state,
987 		   struct drm_crtc_state *new_state)
988 {
989 	/*
990 	 * No new_state means the CRTC is off, so the only criteria is whether
991 	 * it's currently active or in self refresh mode.
992 	 */
993 	if (!new_state)
994 		return drm_atomic_crtc_effectively_active(old_state);
995 
996 	/*
997 	 * We need to run through the crtc_funcs->disable() function if the CRTC
998 	 * is currently on, if it's transitioning to self refresh mode, or if
999 	 * it's in self refresh mode and needs to be fully disabled.
1000 	 */
1001 	return old_state->active ||
1002 	       (old_state->self_refresh_active && !new_state->enable) ||
1003 	       new_state->self_refresh_active;
1004 }
1005 
1006 static void
1007 disable_outputs(struct drm_device *dev, struct drm_atomic_state *old_state)
1008 {
1009 	struct drm_connector *connector;
1010 	struct drm_connector_state *old_conn_state, *new_conn_state;
1011 	struct drm_crtc *crtc;
1012 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
1013 	int i;
1014 
1015 	for_each_oldnew_connector_in_state(old_state, connector, old_conn_state, new_conn_state, i) {
1016 		const struct drm_encoder_helper_funcs *funcs;
1017 		struct drm_encoder *encoder;
1018 		struct drm_bridge *bridge;
1019 
1020 		/* Shut down everything that's in the changeset and currently
1021 		 * still on. So need to check the old, saved state. */
1022 		if (!old_conn_state->crtc)
1023 			continue;
1024 
1025 		old_crtc_state = drm_atomic_get_old_crtc_state(old_state, old_conn_state->crtc);
1026 
1027 		if (new_conn_state->crtc)
1028 			new_crtc_state = drm_atomic_get_new_crtc_state(
1029 						old_state,
1030 						new_conn_state->crtc);
1031 		else
1032 			new_crtc_state = NULL;
1033 
1034 		if (!crtc_needs_disable(old_crtc_state, new_crtc_state) ||
1035 		    !drm_atomic_crtc_needs_modeset(old_conn_state->crtc->state))
1036 			continue;
1037 
1038 		encoder = old_conn_state->best_encoder;
1039 
1040 		/* We shouldn't get this far if we didn't previously have
1041 		 * an encoder.. but WARN_ON() rather than explode.
1042 		 */
1043 		if (WARN_ON(!encoder))
1044 			continue;
1045 
1046 		funcs = encoder->helper_private;
1047 
1048 		DRM_DEBUG_ATOMIC("disabling [ENCODER:%d:%s]\n",
1049 				 encoder->base.id, encoder->name);
1050 
1051 		/*
1052 		 * Each encoder has at most one connector (since we always steal
1053 		 * it away), so we won't call disable hooks twice.
1054 		 */
1055 		bridge = drm_bridge_chain_get_first_bridge(encoder);
1056 		drm_atomic_bridge_chain_disable(bridge, old_state);
1057 
1058 		/* Right function depends upon target state. */
1059 		if (funcs) {
1060 			if (funcs->atomic_disable)
1061 				funcs->atomic_disable(encoder, old_state);
1062 			else if (new_conn_state->crtc && funcs->prepare)
1063 				funcs->prepare(encoder);
1064 			else if (funcs->disable)
1065 				funcs->disable(encoder);
1066 			else if (funcs->dpms)
1067 				funcs->dpms(encoder, DRM_MODE_DPMS_OFF);
1068 		}
1069 
1070 		drm_atomic_bridge_chain_post_disable(bridge, old_state);
1071 	}
1072 
1073 	for_each_oldnew_crtc_in_state(old_state, crtc, old_crtc_state, new_crtc_state, i) {
1074 		const struct drm_crtc_helper_funcs *funcs;
1075 		int ret;
1076 
1077 		/* Shut down everything that needs a full modeset. */
1078 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
1079 			continue;
1080 
1081 		if (!crtc_needs_disable(old_crtc_state, new_crtc_state))
1082 			continue;
1083 
1084 		funcs = crtc->helper_private;
1085 
1086 		DRM_DEBUG_ATOMIC("disabling [CRTC:%d:%s]\n",
1087 				 crtc->base.id, crtc->name);
1088 
1089 
1090 		/* Right function depends upon target state. */
1091 		if (new_crtc_state->enable && funcs->prepare)
1092 			funcs->prepare(crtc);
1093 		else if (funcs->atomic_disable)
1094 			funcs->atomic_disable(crtc, old_crtc_state);
1095 		else if (funcs->disable)
1096 			funcs->disable(crtc);
1097 		else if (funcs->dpms)
1098 			funcs->dpms(crtc, DRM_MODE_DPMS_OFF);
1099 
1100 		if (!(dev->irq_enabled && dev->num_crtcs))
1101 			continue;
1102 
1103 		ret = drm_crtc_vblank_get(crtc);
1104 		WARN_ONCE(ret != -EINVAL, "driver forgot to call drm_crtc_vblank_off()\n");
1105 		if (ret == 0)
1106 			drm_crtc_vblank_put(crtc);
1107 	}
1108 }
1109 
1110 /**
1111  * drm_atomic_helper_update_legacy_modeset_state - update legacy modeset state
1112  * @dev: DRM device
1113  * @old_state: atomic state object with old state structures
1114  *
1115  * This function updates all the various legacy modeset state pointers in
1116  * connectors, encoders and CRTCs. It also updates the timestamping constants
1117  * used for precise vblank timestamps by calling
1118  * drm_calc_timestamping_constants().
1119  *
1120  * Drivers can use this for building their own atomic commit if they don't have
1121  * a pure helper-based modeset implementation.
1122  *
1123  * Since these updates are not synchronized with lockings, only code paths
1124  * called from &drm_mode_config_helper_funcs.atomic_commit_tail can look at the
1125  * legacy state filled out by this helper. Defacto this means this helper and
1126  * the legacy state pointers are only really useful for transitioning an
1127  * existing driver to the atomic world.
1128  */
1129 void
1130 drm_atomic_helper_update_legacy_modeset_state(struct drm_device *dev,
1131 					      struct drm_atomic_state *old_state)
1132 {
1133 	struct drm_connector *connector;
1134 	struct drm_connector_state *old_conn_state, *new_conn_state;
1135 	struct drm_crtc *crtc;
1136 	struct drm_crtc_state *new_crtc_state;
1137 	int i;
1138 
1139 	/* clear out existing links and update dpms */
1140 	for_each_oldnew_connector_in_state(old_state, connector, old_conn_state, new_conn_state, i) {
1141 		if (connector->encoder) {
1142 			WARN_ON(!connector->encoder->crtc);
1143 
1144 			connector->encoder->crtc = NULL;
1145 			connector->encoder = NULL;
1146 		}
1147 
1148 		crtc = new_conn_state->crtc;
1149 		if ((!crtc && old_conn_state->crtc) ||
1150 		    (crtc && drm_atomic_crtc_needs_modeset(crtc->state))) {
1151 			int mode = DRM_MODE_DPMS_OFF;
1152 
1153 			if (crtc && crtc->state->active)
1154 				mode = DRM_MODE_DPMS_ON;
1155 
1156 			connector->dpms = mode;
1157 		}
1158 	}
1159 
1160 	/* set new links */
1161 	for_each_new_connector_in_state(old_state, connector, new_conn_state, i) {
1162 		if (!new_conn_state->crtc)
1163 			continue;
1164 
1165 		if (WARN_ON(!new_conn_state->best_encoder))
1166 			continue;
1167 
1168 		connector->encoder = new_conn_state->best_encoder;
1169 		connector->encoder->crtc = new_conn_state->crtc;
1170 	}
1171 
1172 	/* set legacy state in the crtc structure */
1173 	for_each_new_crtc_in_state(old_state, crtc, new_crtc_state, i) {
1174 		struct drm_plane *primary = crtc->primary;
1175 		struct drm_plane_state *new_plane_state;
1176 
1177 		crtc->mode = new_crtc_state->mode;
1178 		crtc->enabled = new_crtc_state->enable;
1179 
1180 		new_plane_state =
1181 			drm_atomic_get_new_plane_state(old_state, primary);
1182 
1183 		if (new_plane_state && new_plane_state->crtc == crtc) {
1184 			crtc->x = new_plane_state->src_x >> 16;
1185 			crtc->y = new_plane_state->src_y >> 16;
1186 		}
1187 
1188 		if (new_crtc_state->enable)
1189 			drm_calc_timestamping_constants(crtc,
1190 							&new_crtc_state->adjusted_mode);
1191 	}
1192 }
1193 EXPORT_SYMBOL(drm_atomic_helper_update_legacy_modeset_state);
1194 
1195 static void
1196 crtc_set_mode(struct drm_device *dev, struct drm_atomic_state *old_state)
1197 {
1198 	struct drm_crtc *crtc;
1199 	struct drm_crtc_state *new_crtc_state;
1200 	struct drm_connector *connector;
1201 	struct drm_connector_state *new_conn_state;
1202 	int i;
1203 
1204 	for_each_new_crtc_in_state(old_state, crtc, new_crtc_state, i) {
1205 		const struct drm_crtc_helper_funcs *funcs;
1206 
1207 		if (!new_crtc_state->mode_changed)
1208 			continue;
1209 
1210 		funcs = crtc->helper_private;
1211 
1212 		if (new_crtc_state->enable && funcs->mode_set_nofb) {
1213 			DRM_DEBUG_ATOMIC("modeset on [CRTC:%d:%s]\n",
1214 					 crtc->base.id, crtc->name);
1215 
1216 			funcs->mode_set_nofb(crtc);
1217 		}
1218 	}
1219 
1220 	for_each_new_connector_in_state(old_state, connector, new_conn_state, i) {
1221 		const struct drm_encoder_helper_funcs *funcs;
1222 		struct drm_encoder *encoder;
1223 		struct drm_display_mode *mode, *adjusted_mode;
1224 		struct drm_bridge *bridge;
1225 
1226 		if (!new_conn_state->best_encoder)
1227 			continue;
1228 
1229 		encoder = new_conn_state->best_encoder;
1230 		funcs = encoder->helper_private;
1231 		new_crtc_state = new_conn_state->crtc->state;
1232 		mode = &new_crtc_state->mode;
1233 		adjusted_mode = &new_crtc_state->adjusted_mode;
1234 
1235 		if (!new_crtc_state->mode_changed)
1236 			continue;
1237 
1238 		DRM_DEBUG_ATOMIC("modeset on [ENCODER:%d:%s]\n",
1239 				 encoder->base.id, encoder->name);
1240 
1241 		/*
1242 		 * Each encoder has at most one connector (since we always steal
1243 		 * it away), so we won't call mode_set hooks twice.
1244 		 */
1245 		if (funcs && funcs->atomic_mode_set) {
1246 			funcs->atomic_mode_set(encoder, new_crtc_state,
1247 					       new_conn_state);
1248 		} else if (funcs && funcs->mode_set) {
1249 			funcs->mode_set(encoder, mode, adjusted_mode);
1250 		}
1251 
1252 		bridge = drm_bridge_chain_get_first_bridge(encoder);
1253 		drm_bridge_chain_mode_set(bridge, mode, adjusted_mode);
1254 	}
1255 }
1256 
1257 /**
1258  * drm_atomic_helper_commit_modeset_disables - modeset commit to disable outputs
1259  * @dev: DRM device
1260  * @old_state: atomic state object with old state structures
1261  *
1262  * This function shuts down all the outputs that need to be shut down and
1263  * prepares them (if required) with the new mode.
1264  *
1265  * For compatibility with legacy CRTC helpers this should be called before
1266  * drm_atomic_helper_commit_planes(), which is what the default commit function
1267  * does. But drivers with different needs can group the modeset commits together
1268  * and do the plane commits at the end. This is useful for drivers doing runtime
1269  * PM since planes updates then only happen when the CRTC is actually enabled.
1270  */
1271 void drm_atomic_helper_commit_modeset_disables(struct drm_device *dev,
1272 					       struct drm_atomic_state *old_state)
1273 {
1274 	disable_outputs(dev, old_state);
1275 
1276 	drm_atomic_helper_update_legacy_modeset_state(dev, old_state);
1277 
1278 	crtc_set_mode(dev, old_state);
1279 }
1280 EXPORT_SYMBOL(drm_atomic_helper_commit_modeset_disables);
1281 
1282 static void drm_atomic_helper_commit_writebacks(struct drm_device *dev,
1283 						struct drm_atomic_state *old_state)
1284 {
1285 	struct drm_connector *connector;
1286 	struct drm_connector_state *new_conn_state;
1287 	int i;
1288 
1289 	for_each_new_connector_in_state(old_state, connector, new_conn_state, i) {
1290 		const struct drm_connector_helper_funcs *funcs;
1291 
1292 		funcs = connector->helper_private;
1293 		if (!funcs->atomic_commit)
1294 			continue;
1295 
1296 		if (new_conn_state->writeback_job && new_conn_state->writeback_job->fb) {
1297 			WARN_ON(connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK);
1298 			funcs->atomic_commit(connector, new_conn_state);
1299 		}
1300 	}
1301 }
1302 
1303 /**
1304  * drm_atomic_helper_commit_modeset_enables - modeset commit to enable outputs
1305  * @dev: DRM device
1306  * @old_state: atomic state object with old state structures
1307  *
1308  * This function enables all the outputs with the new configuration which had to
1309  * be turned off for the update.
1310  *
1311  * For compatibility with legacy CRTC helpers this should be called after
1312  * drm_atomic_helper_commit_planes(), which is what the default commit function
1313  * does. But drivers with different needs can group the modeset commits together
1314  * and do the plane commits at the end. This is useful for drivers doing runtime
1315  * PM since planes updates then only happen when the CRTC is actually enabled.
1316  */
1317 void drm_atomic_helper_commit_modeset_enables(struct drm_device *dev,
1318 					      struct drm_atomic_state *old_state)
1319 {
1320 	struct drm_crtc *crtc;
1321 	struct drm_crtc_state *old_crtc_state;
1322 	struct drm_crtc_state *new_crtc_state;
1323 	struct drm_connector *connector;
1324 	struct drm_connector_state *new_conn_state;
1325 	int i;
1326 
1327 	for_each_oldnew_crtc_in_state(old_state, crtc, old_crtc_state, new_crtc_state, i) {
1328 		const struct drm_crtc_helper_funcs *funcs;
1329 
1330 		/* Need to filter out CRTCs where only planes change. */
1331 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
1332 			continue;
1333 
1334 		if (!new_crtc_state->active)
1335 			continue;
1336 
1337 		funcs = crtc->helper_private;
1338 
1339 		if (new_crtc_state->enable) {
1340 			DRM_DEBUG_ATOMIC("enabling [CRTC:%d:%s]\n",
1341 					 crtc->base.id, crtc->name);
1342 			if (funcs->atomic_enable)
1343 				funcs->atomic_enable(crtc, old_crtc_state);
1344 			else if (funcs->commit)
1345 				funcs->commit(crtc);
1346 		}
1347 	}
1348 
1349 	for_each_new_connector_in_state(old_state, connector, new_conn_state, i) {
1350 		const struct drm_encoder_helper_funcs *funcs;
1351 		struct drm_encoder *encoder;
1352 		struct drm_bridge *bridge;
1353 
1354 		if (!new_conn_state->best_encoder)
1355 			continue;
1356 
1357 		if (!new_conn_state->crtc->state->active ||
1358 		    !drm_atomic_crtc_needs_modeset(new_conn_state->crtc->state))
1359 			continue;
1360 
1361 		encoder = new_conn_state->best_encoder;
1362 		funcs = encoder->helper_private;
1363 
1364 		DRM_DEBUG_ATOMIC("enabling [ENCODER:%d:%s]\n",
1365 				 encoder->base.id, encoder->name);
1366 
1367 		/*
1368 		 * Each encoder has at most one connector (since we always steal
1369 		 * it away), so we won't call enable hooks twice.
1370 		 */
1371 		bridge = drm_bridge_chain_get_first_bridge(encoder);
1372 		drm_atomic_bridge_chain_pre_enable(bridge, old_state);
1373 
1374 		if (funcs) {
1375 			if (funcs->atomic_enable)
1376 				funcs->atomic_enable(encoder, old_state);
1377 			else if (funcs->enable)
1378 				funcs->enable(encoder);
1379 			else if (funcs->commit)
1380 				funcs->commit(encoder);
1381 		}
1382 
1383 		drm_atomic_bridge_chain_enable(bridge, old_state);
1384 	}
1385 
1386 	drm_atomic_helper_commit_writebacks(dev, old_state);
1387 }
1388 EXPORT_SYMBOL(drm_atomic_helper_commit_modeset_enables);
1389 
1390 /**
1391  * drm_atomic_helper_wait_for_fences - wait for fences stashed in plane state
1392  * @dev: DRM device
1393  * @state: atomic state object with old state structures
1394  * @pre_swap: If true, do an interruptible wait, and @state is the new state.
1395  * 	Otherwise @state is the old state.
1396  *
1397  * For implicit sync, driver should fish the exclusive fence out from the
1398  * incoming fb's and stash it in the drm_plane_state.  This is called after
1399  * drm_atomic_helper_swap_state() so it uses the current plane state (and
1400  * just uses the atomic state to find the changed planes)
1401  *
1402  * Note that @pre_swap is needed since the point where we block for fences moves
1403  * around depending upon whether an atomic commit is blocking or
1404  * non-blocking. For non-blocking commit all waiting needs to happen after
1405  * drm_atomic_helper_swap_state() is called, but for blocking commits we want
1406  * to wait **before** we do anything that can't be easily rolled back. That is
1407  * before we call drm_atomic_helper_swap_state().
1408  *
1409  * Returns zero if success or < 0 if dma_fence_wait() fails.
1410  */
1411 int drm_atomic_helper_wait_for_fences(struct drm_device *dev,
1412 				      struct drm_atomic_state *state,
1413 				      bool pre_swap)
1414 {
1415 	struct drm_plane *plane;
1416 	struct drm_plane_state *new_plane_state;
1417 	int i, ret;
1418 
1419 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
1420 		if (!new_plane_state->fence)
1421 			continue;
1422 
1423 		WARN_ON(!new_plane_state->fb);
1424 
1425 		/*
1426 		 * If waiting for fences pre-swap (ie: nonblock), userspace can
1427 		 * still interrupt the operation. Instead of blocking until the
1428 		 * timer expires, make the wait interruptible.
1429 		 */
1430 		ret = dma_fence_wait(new_plane_state->fence, pre_swap);
1431 		if (ret)
1432 			return ret;
1433 
1434 		dma_fence_put(new_plane_state->fence);
1435 		new_plane_state->fence = NULL;
1436 	}
1437 
1438 	return 0;
1439 }
1440 EXPORT_SYMBOL(drm_atomic_helper_wait_for_fences);
1441 
1442 /**
1443  * drm_atomic_helper_wait_for_vblanks - wait for vblank on CRTCs
1444  * @dev: DRM device
1445  * @old_state: atomic state object with old state structures
1446  *
1447  * Helper to, after atomic commit, wait for vblanks on all affected
1448  * CRTCs (ie. before cleaning up old framebuffers using
1449  * drm_atomic_helper_cleanup_planes()). It will only wait on CRTCs where the
1450  * framebuffers have actually changed to optimize for the legacy cursor and
1451  * plane update use-case.
1452  *
1453  * Drivers using the nonblocking commit tracking support initialized by calling
1454  * drm_atomic_helper_setup_commit() should look at
1455  * drm_atomic_helper_wait_for_flip_done() as an alternative.
1456  */
1457 void
1458 drm_atomic_helper_wait_for_vblanks(struct drm_device *dev,
1459 		struct drm_atomic_state *old_state)
1460 {
1461 	struct drm_crtc *crtc;
1462 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
1463 	int i, ret;
1464 	unsigned crtc_mask = 0;
1465 
1466 	 /*
1467 	  * Legacy cursor ioctls are completely unsynced, and userspace
1468 	  * relies on that (by doing tons of cursor updates).
1469 	  */
1470 	if (old_state->legacy_cursor_update)
1471 		return;
1472 
1473 	for_each_oldnew_crtc_in_state(old_state, crtc, old_crtc_state, new_crtc_state, i) {
1474 		if (!new_crtc_state->active)
1475 			continue;
1476 
1477 		ret = drm_crtc_vblank_get(crtc);
1478 		if (ret != 0)
1479 			continue;
1480 
1481 		crtc_mask |= drm_crtc_mask(crtc);
1482 		old_state->crtcs[i].last_vblank_count = drm_crtc_vblank_count(crtc);
1483 	}
1484 
1485 	for_each_old_crtc_in_state(old_state, crtc, old_crtc_state, i) {
1486 		if (!(crtc_mask & drm_crtc_mask(crtc)))
1487 			continue;
1488 
1489 		ret = wait_event_timeout(dev->vblank[i].queue,
1490 				old_state->crtcs[i].last_vblank_count !=
1491 					drm_crtc_vblank_count(crtc),
1492 				msecs_to_jiffies(100));
1493 
1494 		WARN(!ret, "[CRTC:%d:%s] vblank wait timed out\n",
1495 		     crtc->base.id, crtc->name);
1496 
1497 		drm_crtc_vblank_put(crtc);
1498 	}
1499 }
1500 EXPORT_SYMBOL(drm_atomic_helper_wait_for_vblanks);
1501 
1502 /**
1503  * drm_atomic_helper_wait_for_flip_done - wait for all page flips to be done
1504  * @dev: DRM device
1505  * @old_state: atomic state object with old state structures
1506  *
1507  * Helper to, after atomic commit, wait for page flips on all affected
1508  * crtcs (ie. before cleaning up old framebuffers using
1509  * drm_atomic_helper_cleanup_planes()). Compared to
1510  * drm_atomic_helper_wait_for_vblanks() this waits for the completion on all
1511  * CRTCs, assuming that cursors-only updates are signalling their completion
1512  * immediately (or using a different path).
1513  *
1514  * This requires that drivers use the nonblocking commit tracking support
1515  * initialized using drm_atomic_helper_setup_commit().
1516  */
1517 void drm_atomic_helper_wait_for_flip_done(struct drm_device *dev,
1518 					  struct drm_atomic_state *old_state)
1519 {
1520 	struct drm_crtc *crtc;
1521 	int i;
1522 
1523 	for (i = 0; i < dev->mode_config.num_crtc; i++) {
1524 		struct drm_crtc_commit *commit = old_state->crtcs[i].commit;
1525 		int ret;
1526 
1527 		crtc = old_state->crtcs[i].ptr;
1528 
1529 		if (!crtc || !commit)
1530 			continue;
1531 
1532 		ret = wait_for_completion_timeout(&commit->flip_done, 10 * HZ);
1533 		if (ret == 0)
1534 			DRM_ERROR("[CRTC:%d:%s] flip_done timed out\n",
1535 				  crtc->base.id, crtc->name);
1536 	}
1537 
1538 	if (old_state->fake_commit)
1539 		complete_all(&old_state->fake_commit->flip_done);
1540 }
1541 EXPORT_SYMBOL(drm_atomic_helper_wait_for_flip_done);
1542 
1543 /**
1544  * drm_atomic_helper_commit_tail - commit atomic update to hardware
1545  * @old_state: atomic state object with old state structures
1546  *
1547  * This is the default implementation for the
1548  * &drm_mode_config_helper_funcs.atomic_commit_tail hook, for drivers
1549  * that do not support runtime_pm or do not need the CRTC to be
1550  * enabled to perform a commit. Otherwise, see
1551  * drm_atomic_helper_commit_tail_rpm().
1552  *
1553  * Note that the default ordering of how the various stages are called is to
1554  * match the legacy modeset helper library closest.
1555  */
1556 void drm_atomic_helper_commit_tail(struct drm_atomic_state *old_state)
1557 {
1558 	struct drm_device *dev = old_state->dev;
1559 
1560 	drm_atomic_helper_commit_modeset_disables(dev, old_state);
1561 
1562 	drm_atomic_helper_commit_planes(dev, old_state, 0);
1563 
1564 	drm_atomic_helper_commit_modeset_enables(dev, old_state);
1565 
1566 	drm_atomic_helper_fake_vblank(old_state);
1567 
1568 	drm_atomic_helper_commit_hw_done(old_state);
1569 
1570 	drm_atomic_helper_wait_for_vblanks(dev, old_state);
1571 
1572 	drm_atomic_helper_cleanup_planes(dev, old_state);
1573 }
1574 EXPORT_SYMBOL(drm_atomic_helper_commit_tail);
1575 
1576 /**
1577  * drm_atomic_helper_commit_tail_rpm - commit atomic update to hardware
1578  * @old_state: new modeset state to be committed
1579  *
1580  * This is an alternative implementation for the
1581  * &drm_mode_config_helper_funcs.atomic_commit_tail hook, for drivers
1582  * that support runtime_pm or need the CRTC to be enabled to perform a
1583  * commit. Otherwise, one should use the default implementation
1584  * drm_atomic_helper_commit_tail().
1585  */
1586 void drm_atomic_helper_commit_tail_rpm(struct drm_atomic_state *old_state)
1587 {
1588 	struct drm_device *dev = old_state->dev;
1589 
1590 	drm_atomic_helper_commit_modeset_disables(dev, old_state);
1591 
1592 	drm_atomic_helper_commit_modeset_enables(dev, old_state);
1593 
1594 	drm_atomic_helper_commit_planes(dev, old_state,
1595 					DRM_PLANE_COMMIT_ACTIVE_ONLY);
1596 
1597 	drm_atomic_helper_fake_vblank(old_state);
1598 
1599 	drm_atomic_helper_commit_hw_done(old_state);
1600 
1601 	drm_atomic_helper_wait_for_vblanks(dev, old_state);
1602 
1603 	drm_atomic_helper_cleanup_planes(dev, old_state);
1604 }
1605 EXPORT_SYMBOL(drm_atomic_helper_commit_tail_rpm);
1606 
1607 static void commit_tail(struct drm_atomic_state *old_state)
1608 {
1609 	struct drm_device *dev = old_state->dev;
1610 	const struct drm_mode_config_helper_funcs *funcs;
1611 	struct drm_crtc_state *new_crtc_state;
1612 	struct drm_crtc *crtc;
1613 	ktime_t start;
1614 	s64 commit_time_ms;
1615 	unsigned int i, new_self_refresh_mask = 0;
1616 
1617 	funcs = dev->mode_config.helper_private;
1618 
1619 	/*
1620 	 * We're measuring the _entire_ commit, so the time will vary depending
1621 	 * on how many fences and objects are involved. For the purposes of self
1622 	 * refresh, this is desirable since it'll give us an idea of how
1623 	 * congested things are. This will inform our decision on how often we
1624 	 * should enter self refresh after idle.
1625 	 *
1626 	 * These times will be averaged out in the self refresh helpers to avoid
1627 	 * overreacting over one outlier frame
1628 	 */
1629 	start = ktime_get();
1630 
1631 	drm_atomic_helper_wait_for_fences(dev, old_state, false);
1632 
1633 	drm_atomic_helper_wait_for_dependencies(old_state);
1634 
1635 	/*
1636 	 * We cannot safely access new_crtc_state after
1637 	 * drm_atomic_helper_commit_hw_done() so figure out which crtc's have
1638 	 * self-refresh active beforehand:
1639 	 */
1640 	for_each_new_crtc_in_state(old_state, crtc, new_crtc_state, i)
1641 		if (new_crtc_state->self_refresh_active)
1642 			new_self_refresh_mask |= BIT(i);
1643 
1644 	if (funcs && funcs->atomic_commit_tail)
1645 		funcs->atomic_commit_tail(old_state);
1646 	else
1647 		drm_atomic_helper_commit_tail(old_state);
1648 
1649 	commit_time_ms = ktime_ms_delta(ktime_get(), start);
1650 	if (commit_time_ms > 0)
1651 		drm_self_refresh_helper_update_avg_times(old_state,
1652 						 (unsigned long)commit_time_ms,
1653 						 new_self_refresh_mask);
1654 
1655 	drm_atomic_helper_commit_cleanup_done(old_state);
1656 
1657 	drm_atomic_state_put(old_state);
1658 }
1659 
1660 static void commit_work(struct work_struct *work)
1661 {
1662 	struct drm_atomic_state *state = container_of(work,
1663 						      struct drm_atomic_state,
1664 						      commit_work);
1665 	commit_tail(state);
1666 }
1667 
1668 /**
1669  * drm_atomic_helper_async_check - check if state can be commited asynchronously
1670  * @dev: DRM device
1671  * @state: the driver state object
1672  *
1673  * This helper will check if it is possible to commit the state asynchronously.
1674  * Async commits are not supposed to swap the states like normal sync commits
1675  * but just do in-place changes on the current state.
1676  *
1677  * It will return 0 if the commit can happen in an asynchronous fashion or error
1678  * if not. Note that error just mean it can't be commited asynchronously, if it
1679  * fails the commit should be treated like a normal synchronous commit.
1680  */
1681 int drm_atomic_helper_async_check(struct drm_device *dev,
1682 				   struct drm_atomic_state *state)
1683 {
1684 	struct drm_crtc *crtc;
1685 	struct drm_crtc_state *crtc_state;
1686 	struct drm_plane *plane = NULL;
1687 	struct drm_plane_state *old_plane_state = NULL;
1688 	struct drm_plane_state *new_plane_state = NULL;
1689 	const struct drm_plane_helper_funcs *funcs;
1690 	int i, n_planes = 0;
1691 
1692 	for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
1693 		if (drm_atomic_crtc_needs_modeset(crtc_state))
1694 			return -EINVAL;
1695 	}
1696 
1697 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
1698 		n_planes++;
1699 
1700 	/* FIXME: we support only single plane updates for now */
1701 	if (n_planes != 1)
1702 		return -EINVAL;
1703 
1704 	if (!new_plane_state->crtc ||
1705 	    old_plane_state->crtc != new_plane_state->crtc)
1706 		return -EINVAL;
1707 
1708 	funcs = plane->helper_private;
1709 	if (!funcs->atomic_async_update)
1710 		return -EINVAL;
1711 
1712 	if (new_plane_state->fence)
1713 		return -EINVAL;
1714 
1715 	/*
1716 	 * Don't do an async update if there is an outstanding commit modifying
1717 	 * the plane.  This prevents our async update's changes from getting
1718 	 * overridden by a previous synchronous update's state.
1719 	 */
1720 	if (old_plane_state->commit &&
1721 	    !try_wait_for_completion(&old_plane_state->commit->hw_done))
1722 		return -EBUSY;
1723 
1724 	return funcs->atomic_async_check(plane, new_plane_state);
1725 }
1726 EXPORT_SYMBOL(drm_atomic_helper_async_check);
1727 
1728 /**
1729  * drm_atomic_helper_async_commit - commit state asynchronously
1730  * @dev: DRM device
1731  * @state: the driver state object
1732  *
1733  * This function commits a state asynchronously, i.e., not vblank
1734  * synchronized. It should be used on a state only when
1735  * drm_atomic_async_check() succeeds. Async commits are not supposed to swap
1736  * the states like normal sync commits, but just do in-place changes on the
1737  * current state.
1738  *
1739  * TODO: Implement full swap instead of doing in-place changes.
1740  */
1741 void drm_atomic_helper_async_commit(struct drm_device *dev,
1742 				    struct drm_atomic_state *state)
1743 {
1744 	struct drm_plane *plane;
1745 	struct drm_plane_state *plane_state;
1746 	const struct drm_plane_helper_funcs *funcs;
1747 	int i;
1748 
1749 	for_each_new_plane_in_state(state, plane, plane_state, i) {
1750 		struct drm_framebuffer *new_fb = plane_state->fb;
1751 		struct drm_framebuffer *old_fb = plane->state->fb;
1752 
1753 		funcs = plane->helper_private;
1754 		funcs->atomic_async_update(plane, plane_state);
1755 
1756 		/*
1757 		 * ->atomic_async_update() is supposed to update the
1758 		 * plane->state in-place, make sure at least common
1759 		 * properties have been properly updated.
1760 		 */
1761 		WARN_ON_ONCE(plane->state->fb != new_fb);
1762 		WARN_ON_ONCE(plane->state->crtc_x != plane_state->crtc_x);
1763 		WARN_ON_ONCE(plane->state->crtc_y != plane_state->crtc_y);
1764 		WARN_ON_ONCE(plane->state->src_x != plane_state->src_x);
1765 		WARN_ON_ONCE(plane->state->src_y != plane_state->src_y);
1766 
1767 		/*
1768 		 * Make sure the FBs have been swapped so that cleanups in the
1769 		 * new_state performs a cleanup in the old FB.
1770 		 */
1771 		WARN_ON_ONCE(plane_state->fb != old_fb);
1772 	}
1773 }
1774 EXPORT_SYMBOL(drm_atomic_helper_async_commit);
1775 
1776 /**
1777  * drm_atomic_helper_commit - commit validated state object
1778  * @dev: DRM device
1779  * @state: the driver state object
1780  * @nonblock: whether nonblocking behavior is requested.
1781  *
1782  * This function commits a with drm_atomic_helper_check() pre-validated state
1783  * object. This can still fail when e.g. the framebuffer reservation fails. This
1784  * function implements nonblocking commits, using
1785  * drm_atomic_helper_setup_commit() and related functions.
1786  *
1787  * Committing the actual hardware state is done through the
1788  * &drm_mode_config_helper_funcs.atomic_commit_tail callback, or its default
1789  * implementation drm_atomic_helper_commit_tail().
1790  *
1791  * RETURNS:
1792  * Zero for success or -errno.
1793  */
1794 int drm_atomic_helper_commit(struct drm_device *dev,
1795 			     struct drm_atomic_state *state,
1796 			     bool nonblock)
1797 {
1798 	int ret;
1799 
1800 	if (state->async_update) {
1801 		ret = drm_atomic_helper_prepare_planes(dev, state);
1802 		if (ret)
1803 			return ret;
1804 
1805 		drm_atomic_helper_async_commit(dev, state);
1806 		drm_atomic_helper_cleanup_planes(dev, state);
1807 
1808 		return 0;
1809 	}
1810 
1811 	ret = drm_atomic_helper_setup_commit(state, nonblock);
1812 	if (ret)
1813 		return ret;
1814 
1815 	INIT_WORK(&state->commit_work, commit_work);
1816 
1817 	ret = drm_atomic_helper_prepare_planes(dev, state);
1818 	if (ret)
1819 		return ret;
1820 
1821 	if (!nonblock) {
1822 		ret = drm_atomic_helper_wait_for_fences(dev, state, true);
1823 		if (ret)
1824 			goto err;
1825 	}
1826 
1827 	/*
1828 	 * This is the point of no return - everything below never fails except
1829 	 * when the hw goes bonghits. Which means we can commit the new state on
1830 	 * the software side now.
1831 	 */
1832 
1833 	ret = drm_atomic_helper_swap_state(state, true);
1834 	if (ret)
1835 		goto err;
1836 
1837 	/*
1838 	 * Everything below can be run asynchronously without the need to grab
1839 	 * any modeset locks at all under one condition: It must be guaranteed
1840 	 * that the asynchronous work has either been cancelled (if the driver
1841 	 * supports it, which at least requires that the framebuffers get
1842 	 * cleaned up with drm_atomic_helper_cleanup_planes()) or completed
1843 	 * before the new state gets committed on the software side with
1844 	 * drm_atomic_helper_swap_state().
1845 	 *
1846 	 * This scheme allows new atomic state updates to be prepared and
1847 	 * checked in parallel to the asynchronous completion of the previous
1848 	 * update. Which is important since compositors need to figure out the
1849 	 * composition of the next frame right after having submitted the
1850 	 * current layout.
1851 	 *
1852 	 * NOTE: Commit work has multiple phases, first hardware commit, then
1853 	 * cleanup. We want them to overlap, hence need system_unbound_wq to
1854 	 * make sure work items don't artificially stall on each another.
1855 	 */
1856 
1857 	drm_atomic_state_get(state);
1858 	if (nonblock)
1859 		queue_work(system_unbound_wq, &state->commit_work);
1860 	else
1861 		commit_tail(state);
1862 
1863 	return 0;
1864 
1865 err:
1866 	drm_atomic_helper_cleanup_planes(dev, state);
1867 	return ret;
1868 }
1869 EXPORT_SYMBOL(drm_atomic_helper_commit);
1870 
1871 /**
1872  * DOC: implementing nonblocking commit
1873  *
1874  * Nonblocking atomic commits should use struct &drm_crtc_commit to sequence
1875  * different operations against each another. Locks, especially struct
1876  * &drm_modeset_lock, should not be held in worker threads or any other
1877  * asynchronous context used to commit the hardware state.
1878  *
1879  * drm_atomic_helper_commit() implements the recommended sequence for
1880  * nonblocking commits, using drm_atomic_helper_setup_commit() internally:
1881  *
1882  * 1. Run drm_atomic_helper_prepare_planes(). Since this can fail and we
1883  * need to propagate out of memory/VRAM errors to userspace, it must be called
1884  * synchronously.
1885  *
1886  * 2. Synchronize with any outstanding nonblocking commit worker threads which
1887  * might be affected by the new state update. This is handled by
1888  * drm_atomic_helper_setup_commit().
1889  *
1890  * Asynchronous workers need to have sufficient parallelism to be able to run
1891  * different atomic commits on different CRTCs in parallel. The simplest way to
1892  * achieve this is by running them on the &system_unbound_wq work queue. Note
1893  * that drivers are not required to split up atomic commits and run an
1894  * individual commit in parallel - userspace is supposed to do that if it cares.
1895  * But it might be beneficial to do that for modesets, since those necessarily
1896  * must be done as one global operation, and enabling or disabling a CRTC can
1897  * take a long time. But even that is not required.
1898  *
1899  * IMPORTANT: A &drm_atomic_state update for multiple CRTCs is sequenced
1900  * against all CRTCs therein. Therefore for atomic state updates which only flip
1901  * planes the driver must not get the struct &drm_crtc_state of unrelated CRTCs
1902  * in its atomic check code: This would prevent committing of atomic updates to
1903  * multiple CRTCs in parallel. In general, adding additional state structures
1904  * should be avoided as much as possible, because this reduces parallelism in
1905  * (nonblocking) commits, both due to locking and due to commit sequencing
1906  * requirements.
1907  *
1908  * 3. The software state is updated synchronously with
1909  * drm_atomic_helper_swap_state(). Doing this under the protection of all modeset
1910  * locks means concurrent callers never see inconsistent state. Note that commit
1911  * workers do not hold any locks; their access is only coordinated through
1912  * ordering. If workers would access state only through the pointers in the
1913  * free-standing state objects (currently not the case for any driver) then even
1914  * multiple pending commits could be in-flight at the same time.
1915  *
1916  * 4. Schedule a work item to do all subsequent steps, using the split-out
1917  * commit helpers: a) pre-plane commit b) plane commit c) post-plane commit and
1918  * then cleaning up the framebuffers after the old framebuffer is no longer
1919  * being displayed. The scheduled work should synchronize against other workers
1920  * using the &drm_crtc_commit infrastructure as needed. See
1921  * drm_atomic_helper_setup_commit() for more details.
1922  */
1923 
1924 static int stall_checks(struct drm_crtc *crtc, bool nonblock)
1925 {
1926 	struct drm_crtc_commit *commit, *stall_commit = NULL;
1927 	bool completed = true;
1928 	int i;
1929 	long ret = 0;
1930 
1931 	spin_lock(&crtc->commit_lock);
1932 	i = 0;
1933 	list_for_each_entry(commit, &crtc->commit_list, commit_entry) {
1934 		if (i == 0) {
1935 			completed = try_wait_for_completion(&commit->flip_done);
1936 			/* Userspace is not allowed to get ahead of the previous
1937 			 * commit with nonblocking ones. */
1938 			if (!completed && nonblock) {
1939 				spin_unlock(&crtc->commit_lock);
1940 				return -EBUSY;
1941 			}
1942 		} else if (i == 1) {
1943 			stall_commit = drm_crtc_commit_get(commit);
1944 			break;
1945 		}
1946 
1947 		i++;
1948 	}
1949 	spin_unlock(&crtc->commit_lock);
1950 
1951 	if (!stall_commit)
1952 		return 0;
1953 
1954 	/* We don't want to let commits get ahead of cleanup work too much,
1955 	 * stalling on 2nd previous commit means triple-buffer won't ever stall.
1956 	 */
1957 	ret = wait_for_completion_interruptible_timeout(&stall_commit->cleanup_done,
1958 							10*HZ);
1959 	if (ret == 0)
1960 		DRM_ERROR("[CRTC:%d:%s] cleanup_done timed out\n",
1961 			  crtc->base.id, crtc->name);
1962 
1963 	drm_crtc_commit_put(stall_commit);
1964 
1965 	return ret < 0 ? ret : 0;
1966 }
1967 
1968 static void release_crtc_commit(struct completion *completion)
1969 {
1970 	struct drm_crtc_commit *commit = container_of(completion,
1971 						      typeof(*commit),
1972 						      flip_done);
1973 
1974 	drm_crtc_commit_put(commit);
1975 }
1976 
1977 static void init_commit(struct drm_crtc_commit *commit, struct drm_crtc *crtc)
1978 {
1979 	init_completion(&commit->flip_done);
1980 	init_completion(&commit->hw_done);
1981 	init_completion(&commit->cleanup_done);
1982 	INIT_LIST_HEAD(&commit->commit_entry);
1983 	kref_init(&commit->ref);
1984 	commit->crtc = crtc;
1985 }
1986 
1987 static struct drm_crtc_commit *
1988 crtc_or_fake_commit(struct drm_atomic_state *state, struct drm_crtc *crtc)
1989 {
1990 	if (crtc) {
1991 		struct drm_crtc_state *new_crtc_state;
1992 
1993 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
1994 
1995 		return new_crtc_state->commit;
1996 	}
1997 
1998 	if (!state->fake_commit) {
1999 		state->fake_commit = kzalloc(sizeof(*state->fake_commit), GFP_KERNEL);
2000 		if (!state->fake_commit)
2001 			return NULL;
2002 
2003 		init_commit(state->fake_commit, NULL);
2004 	}
2005 
2006 	return state->fake_commit;
2007 }
2008 
2009 /**
2010  * drm_atomic_helper_setup_commit - setup possibly nonblocking commit
2011  * @state: new modeset state to be committed
2012  * @nonblock: whether nonblocking behavior is requested.
2013  *
2014  * This function prepares @state to be used by the atomic helper's support for
2015  * nonblocking commits. Drivers using the nonblocking commit infrastructure
2016  * should always call this function from their
2017  * &drm_mode_config_funcs.atomic_commit hook.
2018  *
2019  * To be able to use this support drivers need to use a few more helper
2020  * functions. drm_atomic_helper_wait_for_dependencies() must be called before
2021  * actually committing the hardware state, and for nonblocking commits this call
2022  * must be placed in the async worker. See also drm_atomic_helper_swap_state()
2023  * and its stall parameter, for when a driver's commit hooks look at the
2024  * &drm_crtc.state, &drm_plane.state or &drm_connector.state pointer directly.
2025  *
2026  * Completion of the hardware commit step must be signalled using
2027  * drm_atomic_helper_commit_hw_done(). After this step the driver is not allowed
2028  * to read or change any permanent software or hardware modeset state. The only
2029  * exception is state protected by other means than &drm_modeset_lock locks.
2030  * Only the free standing @state with pointers to the old state structures can
2031  * be inspected, e.g. to clean up old buffers using
2032  * drm_atomic_helper_cleanup_planes().
2033  *
2034  * At the very end, before cleaning up @state drivers must call
2035  * drm_atomic_helper_commit_cleanup_done().
2036  *
2037  * This is all implemented by in drm_atomic_helper_commit(), giving drivers a
2038  * complete and easy-to-use default implementation of the atomic_commit() hook.
2039  *
2040  * The tracking of asynchronously executed and still pending commits is done
2041  * using the core structure &drm_crtc_commit.
2042  *
2043  * By default there's no need to clean up resources allocated by this function
2044  * explicitly: drm_atomic_state_default_clear() will take care of that
2045  * automatically.
2046  *
2047  * Returns:
2048  *
2049  * 0 on success. -EBUSY when userspace schedules nonblocking commits too fast,
2050  * -ENOMEM on allocation failures and -EINTR when a signal is pending.
2051  */
2052 int drm_atomic_helper_setup_commit(struct drm_atomic_state *state,
2053 				   bool nonblock)
2054 {
2055 	struct drm_crtc *crtc;
2056 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
2057 	struct drm_connector *conn;
2058 	struct drm_connector_state *old_conn_state, *new_conn_state;
2059 	struct drm_plane *plane;
2060 	struct drm_plane_state *old_plane_state, *new_plane_state;
2061 	struct drm_crtc_commit *commit;
2062 	int i, ret;
2063 
2064 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
2065 		commit = kzalloc(sizeof(*commit), GFP_KERNEL);
2066 		if (!commit)
2067 			return -ENOMEM;
2068 
2069 		init_commit(commit, crtc);
2070 
2071 		new_crtc_state->commit = commit;
2072 
2073 		ret = stall_checks(crtc, nonblock);
2074 		if (ret)
2075 			return ret;
2076 
2077 		/* Drivers only send out events when at least either current or
2078 		 * new CRTC state is active. Complete right away if everything
2079 		 * stays off. */
2080 		if (!old_crtc_state->active && !new_crtc_state->active) {
2081 			complete_all(&commit->flip_done);
2082 			continue;
2083 		}
2084 
2085 		/* Legacy cursor updates are fully unsynced. */
2086 		if (state->legacy_cursor_update) {
2087 			complete_all(&commit->flip_done);
2088 			continue;
2089 		}
2090 
2091 		if (!new_crtc_state->event) {
2092 			commit->event = kzalloc(sizeof(*commit->event),
2093 						GFP_KERNEL);
2094 			if (!commit->event)
2095 				return -ENOMEM;
2096 
2097 			new_crtc_state->event = commit->event;
2098 		}
2099 
2100 		new_crtc_state->event->base.completion = &commit->flip_done;
2101 		new_crtc_state->event->base.completion_release = release_crtc_commit;
2102 		drm_crtc_commit_get(commit);
2103 
2104 		commit->abort_completion = true;
2105 
2106 		state->crtcs[i].commit = commit;
2107 		drm_crtc_commit_get(commit);
2108 	}
2109 
2110 	for_each_oldnew_connector_in_state(state, conn, old_conn_state, new_conn_state, i) {
2111 		/* Userspace is not allowed to get ahead of the previous
2112 		 * commit with nonblocking ones. */
2113 		if (nonblock && old_conn_state->commit &&
2114 		    !try_wait_for_completion(&old_conn_state->commit->flip_done))
2115 			return -EBUSY;
2116 
2117 		/* Always track connectors explicitly for e.g. link retraining. */
2118 		commit = crtc_or_fake_commit(state, new_conn_state->crtc ?: old_conn_state->crtc);
2119 		if (!commit)
2120 			return -ENOMEM;
2121 
2122 		new_conn_state->commit = drm_crtc_commit_get(commit);
2123 	}
2124 
2125 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
2126 		/* Userspace is not allowed to get ahead of the previous
2127 		 * commit with nonblocking ones. */
2128 		if (nonblock && old_plane_state->commit &&
2129 		    !try_wait_for_completion(&old_plane_state->commit->flip_done))
2130 			return -EBUSY;
2131 
2132 		/* Always track planes explicitly for async pageflip support. */
2133 		commit = crtc_or_fake_commit(state, new_plane_state->crtc ?: old_plane_state->crtc);
2134 		if (!commit)
2135 			return -ENOMEM;
2136 
2137 		new_plane_state->commit = drm_crtc_commit_get(commit);
2138 	}
2139 
2140 	return 0;
2141 }
2142 EXPORT_SYMBOL(drm_atomic_helper_setup_commit);
2143 
2144 /**
2145  * drm_atomic_helper_wait_for_dependencies - wait for required preceeding commits
2146  * @old_state: atomic state object with old state structures
2147  *
2148  * This function waits for all preceeding commits that touch the same CRTC as
2149  * @old_state to both be committed to the hardware (as signalled by
2150  * drm_atomic_helper_commit_hw_done()) and executed by the hardware (as signalled
2151  * by calling drm_crtc_send_vblank_event() on the &drm_crtc_state.event).
2152  *
2153  * This is part of the atomic helper support for nonblocking commits, see
2154  * drm_atomic_helper_setup_commit() for an overview.
2155  */
2156 void drm_atomic_helper_wait_for_dependencies(struct drm_atomic_state *old_state)
2157 {
2158 	struct drm_crtc *crtc;
2159 	struct drm_crtc_state *old_crtc_state;
2160 	struct drm_plane *plane;
2161 	struct drm_plane_state *old_plane_state;
2162 	struct drm_connector *conn;
2163 	struct drm_connector_state *old_conn_state;
2164 	struct drm_crtc_commit *commit;
2165 	int i;
2166 	long ret;
2167 
2168 	for_each_old_crtc_in_state(old_state, crtc, old_crtc_state, i) {
2169 		commit = old_crtc_state->commit;
2170 
2171 		if (!commit)
2172 			continue;
2173 
2174 		ret = wait_for_completion_timeout(&commit->hw_done,
2175 						  10*HZ);
2176 		if (ret == 0)
2177 			DRM_ERROR("[CRTC:%d:%s] hw_done timed out\n",
2178 				  crtc->base.id, crtc->name);
2179 
2180 		/* Currently no support for overwriting flips, hence
2181 		 * stall for previous one to execute completely. */
2182 		ret = wait_for_completion_timeout(&commit->flip_done,
2183 						  10*HZ);
2184 		if (ret == 0)
2185 			DRM_ERROR("[CRTC:%d:%s] flip_done timed out\n",
2186 				  crtc->base.id, crtc->name);
2187 	}
2188 
2189 	for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
2190 		commit = old_conn_state->commit;
2191 
2192 		if (!commit)
2193 			continue;
2194 
2195 		ret = wait_for_completion_timeout(&commit->hw_done,
2196 						  10*HZ);
2197 		if (ret == 0)
2198 			DRM_ERROR("[CONNECTOR:%d:%s] hw_done timed out\n",
2199 				  conn->base.id, conn->name);
2200 
2201 		/* Currently no support for overwriting flips, hence
2202 		 * stall for previous one to execute completely. */
2203 		ret = wait_for_completion_timeout(&commit->flip_done,
2204 						  10*HZ);
2205 		if (ret == 0)
2206 			DRM_ERROR("[CONNECTOR:%d:%s] flip_done timed out\n",
2207 				  conn->base.id, conn->name);
2208 	}
2209 
2210 	for_each_old_plane_in_state(old_state, plane, old_plane_state, i) {
2211 		commit = old_plane_state->commit;
2212 
2213 		if (!commit)
2214 			continue;
2215 
2216 		ret = wait_for_completion_timeout(&commit->hw_done,
2217 						  10*HZ);
2218 		if (ret == 0)
2219 			DRM_ERROR("[PLANE:%d:%s] hw_done timed out\n",
2220 				  plane->base.id, plane->name);
2221 
2222 		/* Currently no support for overwriting flips, hence
2223 		 * stall for previous one to execute completely. */
2224 		ret = wait_for_completion_timeout(&commit->flip_done,
2225 						  10*HZ);
2226 		if (ret == 0)
2227 			DRM_ERROR("[PLANE:%d:%s] flip_done timed out\n",
2228 				  plane->base.id, plane->name);
2229 	}
2230 }
2231 EXPORT_SYMBOL(drm_atomic_helper_wait_for_dependencies);
2232 
2233 /**
2234  * drm_atomic_helper_fake_vblank - fake VBLANK events if needed
2235  * @old_state: atomic state object with old state structures
2236  *
2237  * This function walks all CRTCs and fakes VBLANK events on those with
2238  * &drm_crtc_state.no_vblank set to true and &drm_crtc_state.event != NULL.
2239  * The primary use of this function is writeback connectors working in oneshot
2240  * mode and faking VBLANK events. In this case they only fake the VBLANK event
2241  * when a job is queued, and any change to the pipeline that does not touch the
2242  * connector is leading to timeouts when calling
2243  * drm_atomic_helper_wait_for_vblanks() or
2244  * drm_atomic_helper_wait_for_flip_done(). In addition to writeback
2245  * connectors, this function can also fake VBLANK events for CRTCs without
2246  * VBLANK interrupt.
2247  *
2248  * This is part of the atomic helper support for nonblocking commits, see
2249  * drm_atomic_helper_setup_commit() for an overview.
2250  */
2251 void drm_atomic_helper_fake_vblank(struct drm_atomic_state *old_state)
2252 {
2253 	struct drm_crtc_state *new_crtc_state;
2254 	struct drm_crtc *crtc;
2255 	int i;
2256 
2257 	for_each_new_crtc_in_state(old_state, crtc, new_crtc_state, i) {
2258 		unsigned long flags;
2259 
2260 		if (!new_crtc_state->no_vblank)
2261 			continue;
2262 
2263 		spin_lock_irqsave(&old_state->dev->event_lock, flags);
2264 		if (new_crtc_state->event) {
2265 			drm_crtc_send_vblank_event(crtc,
2266 						   new_crtc_state->event);
2267 			new_crtc_state->event = NULL;
2268 		}
2269 		spin_unlock_irqrestore(&old_state->dev->event_lock, flags);
2270 	}
2271 }
2272 EXPORT_SYMBOL(drm_atomic_helper_fake_vblank);
2273 
2274 /**
2275  * drm_atomic_helper_commit_hw_done - setup possible nonblocking commit
2276  * @old_state: atomic state object with old state structures
2277  *
2278  * This function is used to signal completion of the hardware commit step. After
2279  * this step the driver is not allowed to read or change any permanent software
2280  * or hardware modeset state. The only exception is state protected by other
2281  * means than &drm_modeset_lock locks.
2282  *
2283  * Drivers should try to postpone any expensive or delayed cleanup work after
2284  * this function is called.
2285  *
2286  * This is part of the atomic helper support for nonblocking commits, see
2287  * drm_atomic_helper_setup_commit() for an overview.
2288  */
2289 void drm_atomic_helper_commit_hw_done(struct drm_atomic_state *old_state)
2290 {
2291 	struct drm_crtc *crtc;
2292 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
2293 	struct drm_crtc_commit *commit;
2294 	int i;
2295 
2296 	for_each_oldnew_crtc_in_state(old_state, crtc, old_crtc_state, new_crtc_state, i) {
2297 		commit = new_crtc_state->commit;
2298 		if (!commit)
2299 			continue;
2300 
2301 		/*
2302 		 * copy new_crtc_state->commit to old_crtc_state->commit,
2303 		 * it's unsafe to touch new_crtc_state after hw_done,
2304 		 * but we still need to do so in cleanup_done().
2305 		 */
2306 		if (old_crtc_state->commit)
2307 			drm_crtc_commit_put(old_crtc_state->commit);
2308 
2309 		old_crtc_state->commit = drm_crtc_commit_get(commit);
2310 
2311 		/* backend must have consumed any event by now */
2312 		WARN_ON(new_crtc_state->event);
2313 		complete_all(&commit->hw_done);
2314 	}
2315 
2316 	if (old_state->fake_commit) {
2317 		complete_all(&old_state->fake_commit->hw_done);
2318 		complete_all(&old_state->fake_commit->flip_done);
2319 	}
2320 }
2321 EXPORT_SYMBOL(drm_atomic_helper_commit_hw_done);
2322 
2323 /**
2324  * drm_atomic_helper_commit_cleanup_done - signal completion of commit
2325  * @old_state: atomic state object with old state structures
2326  *
2327  * This signals completion of the atomic update @old_state, including any
2328  * cleanup work. If used, it must be called right before calling
2329  * drm_atomic_state_put().
2330  *
2331  * This is part of the atomic helper support for nonblocking commits, see
2332  * drm_atomic_helper_setup_commit() for an overview.
2333  */
2334 void drm_atomic_helper_commit_cleanup_done(struct drm_atomic_state *old_state)
2335 {
2336 	struct drm_crtc *crtc;
2337 	struct drm_crtc_state *old_crtc_state;
2338 	struct drm_crtc_commit *commit;
2339 	int i;
2340 
2341 	for_each_old_crtc_in_state(old_state, crtc, old_crtc_state, i) {
2342 		commit = old_crtc_state->commit;
2343 		if (WARN_ON(!commit))
2344 			continue;
2345 
2346 		complete_all(&commit->cleanup_done);
2347 		WARN_ON(!try_wait_for_completion(&commit->hw_done));
2348 
2349 		spin_lock(&crtc->commit_lock);
2350 		list_del(&commit->commit_entry);
2351 		spin_unlock(&crtc->commit_lock);
2352 	}
2353 
2354 	if (old_state->fake_commit) {
2355 		complete_all(&old_state->fake_commit->cleanup_done);
2356 		WARN_ON(!try_wait_for_completion(&old_state->fake_commit->hw_done));
2357 	}
2358 }
2359 EXPORT_SYMBOL(drm_atomic_helper_commit_cleanup_done);
2360 
2361 /**
2362  * drm_atomic_helper_prepare_planes - prepare plane resources before commit
2363  * @dev: DRM device
2364  * @state: atomic state object with new state structures
2365  *
2366  * This function prepares plane state, specifically framebuffers, for the new
2367  * configuration, by calling &drm_plane_helper_funcs.prepare_fb. If any failure
2368  * is encountered this function will call &drm_plane_helper_funcs.cleanup_fb on
2369  * any already successfully prepared framebuffer.
2370  *
2371  * Returns:
2372  * 0 on success, negative error code on failure.
2373  */
2374 int drm_atomic_helper_prepare_planes(struct drm_device *dev,
2375 				     struct drm_atomic_state *state)
2376 {
2377 	struct drm_connector *connector;
2378 	struct drm_connector_state *new_conn_state;
2379 	struct drm_plane *plane;
2380 	struct drm_plane_state *new_plane_state;
2381 	int ret, i, j;
2382 
2383 	for_each_new_connector_in_state(state, connector, new_conn_state, i) {
2384 		if (!new_conn_state->writeback_job)
2385 			continue;
2386 
2387 		ret = drm_writeback_prepare_job(new_conn_state->writeback_job);
2388 		if (ret < 0)
2389 			return ret;
2390 	}
2391 
2392 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
2393 		const struct drm_plane_helper_funcs *funcs;
2394 
2395 		funcs = plane->helper_private;
2396 
2397 		if (funcs->prepare_fb) {
2398 			ret = funcs->prepare_fb(plane, new_plane_state);
2399 			if (ret)
2400 				goto fail;
2401 		}
2402 	}
2403 
2404 	return 0;
2405 
2406 fail:
2407 	for_each_new_plane_in_state(state, plane, new_plane_state, j) {
2408 		const struct drm_plane_helper_funcs *funcs;
2409 
2410 		if (j >= i)
2411 			continue;
2412 
2413 		funcs = plane->helper_private;
2414 
2415 		if (funcs->cleanup_fb)
2416 			funcs->cleanup_fb(plane, new_plane_state);
2417 	}
2418 
2419 	return ret;
2420 }
2421 EXPORT_SYMBOL(drm_atomic_helper_prepare_planes);
2422 
2423 static bool plane_crtc_active(const struct drm_plane_state *state)
2424 {
2425 	return state->crtc && state->crtc->state->active;
2426 }
2427 
2428 /**
2429  * drm_atomic_helper_commit_planes - commit plane state
2430  * @dev: DRM device
2431  * @old_state: atomic state object with old state structures
2432  * @flags: flags for committing plane state
2433  *
2434  * This function commits the new plane state using the plane and atomic helper
2435  * functions for planes and CRTCs. It assumes that the atomic state has already
2436  * been pushed into the relevant object state pointers, since this step can no
2437  * longer fail.
2438  *
2439  * It still requires the global state object @old_state to know which planes and
2440  * crtcs need to be updated though.
2441  *
2442  * Note that this function does all plane updates across all CRTCs in one step.
2443  * If the hardware can't support this approach look at
2444  * drm_atomic_helper_commit_planes_on_crtc() instead.
2445  *
2446  * Plane parameters can be updated by applications while the associated CRTC is
2447  * disabled. The DRM/KMS core will store the parameters in the plane state,
2448  * which will be available to the driver when the CRTC is turned on. As a result
2449  * most drivers don't need to be immediately notified of plane updates for a
2450  * disabled CRTC.
2451  *
2452  * Unless otherwise needed, drivers are advised to set the ACTIVE_ONLY flag in
2453  * @flags in order not to receive plane update notifications related to a
2454  * disabled CRTC. This avoids the need to manually ignore plane updates in
2455  * driver code when the driver and/or hardware can't or just don't need to deal
2456  * with updates on disabled CRTCs, for example when supporting runtime PM.
2457  *
2458  * Drivers may set the NO_DISABLE_AFTER_MODESET flag in @flags if the relevant
2459  * display controllers require to disable a CRTC's planes when the CRTC is
2460  * disabled. This function would skip the &drm_plane_helper_funcs.atomic_disable
2461  * call for a plane if the CRTC of the old plane state needs a modesetting
2462  * operation. Of course, the drivers need to disable the planes in their CRTC
2463  * disable callbacks since no one else would do that.
2464  *
2465  * The drm_atomic_helper_commit() default implementation doesn't set the
2466  * ACTIVE_ONLY flag to most closely match the behaviour of the legacy helpers.
2467  * This should not be copied blindly by drivers.
2468  */
2469 void drm_atomic_helper_commit_planes(struct drm_device *dev,
2470 				     struct drm_atomic_state *old_state,
2471 				     uint32_t flags)
2472 {
2473 	struct drm_crtc *crtc;
2474 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
2475 	struct drm_plane *plane;
2476 	struct drm_plane_state *old_plane_state, *new_plane_state;
2477 	int i;
2478 	bool active_only = flags & DRM_PLANE_COMMIT_ACTIVE_ONLY;
2479 	bool no_disable = flags & DRM_PLANE_COMMIT_NO_DISABLE_AFTER_MODESET;
2480 
2481 	for_each_oldnew_crtc_in_state(old_state, crtc, old_crtc_state, new_crtc_state, i) {
2482 		const struct drm_crtc_helper_funcs *funcs;
2483 
2484 		funcs = crtc->helper_private;
2485 
2486 		if (!funcs || !funcs->atomic_begin)
2487 			continue;
2488 
2489 		if (active_only && !new_crtc_state->active)
2490 			continue;
2491 
2492 		funcs->atomic_begin(crtc, old_crtc_state);
2493 	}
2494 
2495 	for_each_oldnew_plane_in_state(old_state, plane, old_plane_state, new_plane_state, i) {
2496 		const struct drm_plane_helper_funcs *funcs;
2497 		bool disabling;
2498 
2499 		funcs = plane->helper_private;
2500 
2501 		if (!funcs)
2502 			continue;
2503 
2504 		disabling = drm_atomic_plane_disabling(old_plane_state,
2505 						       new_plane_state);
2506 
2507 		if (active_only) {
2508 			/*
2509 			 * Skip planes related to inactive CRTCs. If the plane
2510 			 * is enabled use the state of the current CRTC. If the
2511 			 * plane is being disabled use the state of the old
2512 			 * CRTC to avoid skipping planes being disabled on an
2513 			 * active CRTC.
2514 			 */
2515 			if (!disabling && !plane_crtc_active(new_plane_state))
2516 				continue;
2517 			if (disabling && !plane_crtc_active(old_plane_state))
2518 				continue;
2519 		}
2520 
2521 		/*
2522 		 * Special-case disabling the plane if drivers support it.
2523 		 */
2524 		if (disabling && funcs->atomic_disable) {
2525 			struct drm_crtc_state *crtc_state;
2526 
2527 			crtc_state = old_plane_state->crtc->state;
2528 
2529 			if (drm_atomic_crtc_needs_modeset(crtc_state) &&
2530 			    no_disable)
2531 				continue;
2532 
2533 			funcs->atomic_disable(plane, old_plane_state);
2534 		} else if (new_plane_state->crtc || disabling) {
2535 			funcs->atomic_update(plane, old_plane_state);
2536 		}
2537 	}
2538 
2539 	for_each_oldnew_crtc_in_state(old_state, crtc, old_crtc_state, new_crtc_state, i) {
2540 		const struct drm_crtc_helper_funcs *funcs;
2541 
2542 		funcs = crtc->helper_private;
2543 
2544 		if (!funcs || !funcs->atomic_flush)
2545 			continue;
2546 
2547 		if (active_only && !new_crtc_state->active)
2548 			continue;
2549 
2550 		funcs->atomic_flush(crtc, old_crtc_state);
2551 	}
2552 }
2553 EXPORT_SYMBOL(drm_atomic_helper_commit_planes);
2554 
2555 /**
2556  * drm_atomic_helper_commit_planes_on_crtc - commit plane state for a CRTC
2557  * @old_crtc_state: atomic state object with the old CRTC state
2558  *
2559  * This function commits the new plane state using the plane and atomic helper
2560  * functions for planes on the specific CRTC. It assumes that the atomic state
2561  * has already been pushed into the relevant object state pointers, since this
2562  * step can no longer fail.
2563  *
2564  * This function is useful when plane updates should be done CRTC-by-CRTC
2565  * instead of one global step like drm_atomic_helper_commit_planes() does.
2566  *
2567  * This function can only be savely used when planes are not allowed to move
2568  * between different CRTCs because this function doesn't handle inter-CRTC
2569  * depencies. Callers need to ensure that either no such depencies exist,
2570  * resolve them through ordering of commit calls or through some other means.
2571  */
2572 void
2573 drm_atomic_helper_commit_planes_on_crtc(struct drm_crtc_state *old_crtc_state)
2574 {
2575 	const struct drm_crtc_helper_funcs *crtc_funcs;
2576 	struct drm_crtc *crtc = old_crtc_state->crtc;
2577 	struct drm_atomic_state *old_state = old_crtc_state->state;
2578 	struct drm_crtc_state *new_crtc_state =
2579 		drm_atomic_get_new_crtc_state(old_state, crtc);
2580 	struct drm_plane *plane;
2581 	unsigned plane_mask;
2582 
2583 	plane_mask = old_crtc_state->plane_mask;
2584 	plane_mask |= new_crtc_state->plane_mask;
2585 
2586 	crtc_funcs = crtc->helper_private;
2587 	if (crtc_funcs && crtc_funcs->atomic_begin)
2588 		crtc_funcs->atomic_begin(crtc, old_crtc_state);
2589 
2590 	drm_for_each_plane_mask(plane, crtc->dev, plane_mask) {
2591 		struct drm_plane_state *old_plane_state =
2592 			drm_atomic_get_old_plane_state(old_state, plane);
2593 		struct drm_plane_state *new_plane_state =
2594 			drm_atomic_get_new_plane_state(old_state, plane);
2595 		const struct drm_plane_helper_funcs *plane_funcs;
2596 
2597 		plane_funcs = plane->helper_private;
2598 
2599 		if (!old_plane_state || !plane_funcs)
2600 			continue;
2601 
2602 		WARN_ON(new_plane_state->crtc &&
2603 			new_plane_state->crtc != crtc);
2604 
2605 		if (drm_atomic_plane_disabling(old_plane_state, new_plane_state) &&
2606 		    plane_funcs->atomic_disable)
2607 			plane_funcs->atomic_disable(plane, old_plane_state);
2608 		else if (new_plane_state->crtc ||
2609 			 drm_atomic_plane_disabling(old_plane_state, new_plane_state))
2610 			plane_funcs->atomic_update(plane, old_plane_state);
2611 	}
2612 
2613 	if (crtc_funcs && crtc_funcs->atomic_flush)
2614 		crtc_funcs->atomic_flush(crtc, old_crtc_state);
2615 }
2616 EXPORT_SYMBOL(drm_atomic_helper_commit_planes_on_crtc);
2617 
2618 /**
2619  * drm_atomic_helper_disable_planes_on_crtc - helper to disable CRTC's planes
2620  * @old_crtc_state: atomic state object with the old CRTC state
2621  * @atomic: if set, synchronize with CRTC's atomic_begin/flush hooks
2622  *
2623  * Disables all planes associated with the given CRTC. This can be
2624  * used for instance in the CRTC helper atomic_disable callback to disable
2625  * all planes.
2626  *
2627  * If the atomic-parameter is set the function calls the CRTC's
2628  * atomic_begin hook before and atomic_flush hook after disabling the
2629  * planes.
2630  *
2631  * It is a bug to call this function without having implemented the
2632  * &drm_plane_helper_funcs.atomic_disable plane hook.
2633  */
2634 void
2635 drm_atomic_helper_disable_planes_on_crtc(struct drm_crtc_state *old_crtc_state,
2636 					 bool atomic)
2637 {
2638 	struct drm_crtc *crtc = old_crtc_state->crtc;
2639 	const struct drm_crtc_helper_funcs *crtc_funcs =
2640 		crtc->helper_private;
2641 	struct drm_plane *plane;
2642 
2643 	if (atomic && crtc_funcs && crtc_funcs->atomic_begin)
2644 		crtc_funcs->atomic_begin(crtc, NULL);
2645 
2646 	drm_atomic_crtc_state_for_each_plane(plane, old_crtc_state) {
2647 		const struct drm_plane_helper_funcs *plane_funcs =
2648 			plane->helper_private;
2649 
2650 		if (!plane_funcs)
2651 			continue;
2652 
2653 		WARN_ON(!plane_funcs->atomic_disable);
2654 		if (plane_funcs->atomic_disable)
2655 			plane_funcs->atomic_disable(plane, NULL);
2656 	}
2657 
2658 	if (atomic && crtc_funcs && crtc_funcs->atomic_flush)
2659 		crtc_funcs->atomic_flush(crtc, NULL);
2660 }
2661 EXPORT_SYMBOL(drm_atomic_helper_disable_planes_on_crtc);
2662 
2663 /**
2664  * drm_atomic_helper_cleanup_planes - cleanup plane resources after commit
2665  * @dev: DRM device
2666  * @old_state: atomic state object with old state structures
2667  *
2668  * This function cleans up plane state, specifically framebuffers, from the old
2669  * configuration. Hence the old configuration must be perserved in @old_state to
2670  * be able to call this function.
2671  *
2672  * This function must also be called on the new state when the atomic update
2673  * fails at any point after calling drm_atomic_helper_prepare_planes().
2674  */
2675 void drm_atomic_helper_cleanup_planes(struct drm_device *dev,
2676 				      struct drm_atomic_state *old_state)
2677 {
2678 	struct drm_plane *plane;
2679 	struct drm_plane_state *old_plane_state, *new_plane_state;
2680 	int i;
2681 
2682 	for_each_oldnew_plane_in_state(old_state, plane, old_plane_state, new_plane_state, i) {
2683 		const struct drm_plane_helper_funcs *funcs;
2684 		struct drm_plane_state *plane_state;
2685 
2686 		/*
2687 		 * This might be called before swapping when commit is aborted,
2688 		 * in which case we have to cleanup the new state.
2689 		 */
2690 		if (old_plane_state == plane->state)
2691 			plane_state = new_plane_state;
2692 		else
2693 			plane_state = old_plane_state;
2694 
2695 		funcs = plane->helper_private;
2696 
2697 		if (funcs->cleanup_fb)
2698 			funcs->cleanup_fb(plane, plane_state);
2699 	}
2700 }
2701 EXPORT_SYMBOL(drm_atomic_helper_cleanup_planes);
2702 
2703 /**
2704  * drm_atomic_helper_swap_state - store atomic state into current sw state
2705  * @state: atomic state
2706  * @stall: stall for preceeding commits
2707  *
2708  * This function stores the atomic state into the current state pointers in all
2709  * driver objects. It should be called after all failing steps have been done
2710  * and succeeded, but before the actual hardware state is committed.
2711  *
2712  * For cleanup and error recovery the current state for all changed objects will
2713  * be swapped into @state.
2714  *
2715  * With that sequence it fits perfectly into the plane prepare/cleanup sequence:
2716  *
2717  * 1. Call drm_atomic_helper_prepare_planes() with the staged atomic state.
2718  *
2719  * 2. Do any other steps that might fail.
2720  *
2721  * 3. Put the staged state into the current state pointers with this function.
2722  *
2723  * 4. Actually commit the hardware state.
2724  *
2725  * 5. Call drm_atomic_helper_cleanup_planes() with @state, which since step 3
2726  * contains the old state. Also do any other cleanup required with that state.
2727  *
2728  * @stall must be set when nonblocking commits for this driver directly access
2729  * the &drm_plane.state, &drm_crtc.state or &drm_connector.state pointer. With
2730  * the current atomic helpers this is almost always the case, since the helpers
2731  * don't pass the right state structures to the callbacks.
2732  *
2733  * Returns:
2734  *
2735  * Returns 0 on success. Can return -ERESTARTSYS when @stall is true and the
2736  * waiting for the previous commits has been interrupted.
2737  */
2738 int drm_atomic_helper_swap_state(struct drm_atomic_state *state,
2739 				  bool stall)
2740 {
2741 	int i, ret;
2742 	struct drm_connector *connector;
2743 	struct drm_connector_state *old_conn_state, *new_conn_state;
2744 	struct drm_crtc *crtc;
2745 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
2746 	struct drm_plane *plane;
2747 	struct drm_plane_state *old_plane_state, *new_plane_state;
2748 	struct drm_crtc_commit *commit;
2749 	struct drm_private_obj *obj;
2750 	struct drm_private_state *old_obj_state, *new_obj_state;
2751 
2752 	if (stall) {
2753 		/*
2754 		 * We have to stall for hw_done here before
2755 		 * drm_atomic_helper_wait_for_dependencies() because flip
2756 		 * depth > 1 is not yet supported by all drivers. As long as
2757 		 * obj->state is directly dereferenced anywhere in the drivers
2758 		 * atomic_commit_tail function, then it's unsafe to swap state
2759 		 * before drm_atomic_helper_commit_hw_done() is called.
2760 		 */
2761 
2762 		for_each_old_crtc_in_state(state, crtc, old_crtc_state, i) {
2763 			commit = old_crtc_state->commit;
2764 
2765 			if (!commit)
2766 				continue;
2767 
2768 			ret = wait_for_completion_interruptible(&commit->hw_done);
2769 			if (ret)
2770 				return ret;
2771 		}
2772 
2773 		for_each_old_connector_in_state(state, connector, old_conn_state, i) {
2774 			commit = old_conn_state->commit;
2775 
2776 			if (!commit)
2777 				continue;
2778 
2779 			ret = wait_for_completion_interruptible(&commit->hw_done);
2780 			if (ret)
2781 				return ret;
2782 		}
2783 
2784 		for_each_old_plane_in_state(state, plane, old_plane_state, i) {
2785 			commit = old_plane_state->commit;
2786 
2787 			if (!commit)
2788 				continue;
2789 
2790 			ret = wait_for_completion_interruptible(&commit->hw_done);
2791 			if (ret)
2792 				return ret;
2793 		}
2794 	}
2795 
2796 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, new_conn_state, i) {
2797 		WARN_ON(connector->state != old_conn_state);
2798 
2799 		old_conn_state->state = state;
2800 		new_conn_state->state = NULL;
2801 
2802 		state->connectors[i].state = old_conn_state;
2803 		connector->state = new_conn_state;
2804 	}
2805 
2806 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
2807 		WARN_ON(crtc->state != old_crtc_state);
2808 
2809 		old_crtc_state->state = state;
2810 		new_crtc_state->state = NULL;
2811 
2812 		state->crtcs[i].state = old_crtc_state;
2813 		crtc->state = new_crtc_state;
2814 
2815 		if (new_crtc_state->commit) {
2816 			spin_lock(&crtc->commit_lock);
2817 			list_add(&new_crtc_state->commit->commit_entry,
2818 				 &crtc->commit_list);
2819 			spin_unlock(&crtc->commit_lock);
2820 
2821 			new_crtc_state->commit->event = NULL;
2822 		}
2823 	}
2824 
2825 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
2826 		WARN_ON(plane->state != old_plane_state);
2827 
2828 		old_plane_state->state = state;
2829 		new_plane_state->state = NULL;
2830 
2831 		state->planes[i].state = old_plane_state;
2832 		plane->state = new_plane_state;
2833 	}
2834 
2835 	for_each_oldnew_private_obj_in_state(state, obj, old_obj_state, new_obj_state, i) {
2836 		WARN_ON(obj->state != old_obj_state);
2837 
2838 		old_obj_state->state = state;
2839 		new_obj_state->state = NULL;
2840 
2841 		state->private_objs[i].state = old_obj_state;
2842 		obj->state = new_obj_state;
2843 	}
2844 
2845 	return 0;
2846 }
2847 EXPORT_SYMBOL(drm_atomic_helper_swap_state);
2848 
2849 /**
2850  * drm_atomic_helper_update_plane - Helper for primary plane update using atomic
2851  * @plane: plane object to update
2852  * @crtc: owning CRTC of owning plane
2853  * @fb: framebuffer to flip onto plane
2854  * @crtc_x: x offset of primary plane on @crtc
2855  * @crtc_y: y offset of primary plane on @crtc
2856  * @crtc_w: width of primary plane rectangle on @crtc
2857  * @crtc_h: height of primary plane rectangle on @crtc
2858  * @src_x: x offset of @fb for panning
2859  * @src_y: y offset of @fb for panning
2860  * @src_w: width of source rectangle in @fb
2861  * @src_h: height of source rectangle in @fb
2862  * @ctx: lock acquire context
2863  *
2864  * Provides a default plane update handler using the atomic driver interface.
2865  *
2866  * RETURNS:
2867  * Zero on success, error code on failure
2868  */
2869 int drm_atomic_helper_update_plane(struct drm_plane *plane,
2870 				   struct drm_crtc *crtc,
2871 				   struct drm_framebuffer *fb,
2872 				   int crtc_x, int crtc_y,
2873 				   unsigned int crtc_w, unsigned int crtc_h,
2874 				   uint32_t src_x, uint32_t src_y,
2875 				   uint32_t src_w, uint32_t src_h,
2876 				   struct drm_modeset_acquire_ctx *ctx)
2877 {
2878 	struct drm_atomic_state *state;
2879 	struct drm_plane_state *plane_state;
2880 	int ret = 0;
2881 
2882 	state = drm_atomic_state_alloc(plane->dev);
2883 	if (!state)
2884 		return -ENOMEM;
2885 
2886 	state->acquire_ctx = ctx;
2887 	plane_state = drm_atomic_get_plane_state(state, plane);
2888 	if (IS_ERR(plane_state)) {
2889 		ret = PTR_ERR(plane_state);
2890 		goto fail;
2891 	}
2892 
2893 	ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
2894 	if (ret != 0)
2895 		goto fail;
2896 	drm_atomic_set_fb_for_plane(plane_state, fb);
2897 	plane_state->crtc_x = crtc_x;
2898 	plane_state->crtc_y = crtc_y;
2899 	plane_state->crtc_w = crtc_w;
2900 	plane_state->crtc_h = crtc_h;
2901 	plane_state->src_x = src_x;
2902 	plane_state->src_y = src_y;
2903 	plane_state->src_w = src_w;
2904 	plane_state->src_h = src_h;
2905 
2906 	if (plane == crtc->cursor)
2907 		state->legacy_cursor_update = true;
2908 
2909 	ret = drm_atomic_commit(state);
2910 fail:
2911 	drm_atomic_state_put(state);
2912 	return ret;
2913 }
2914 EXPORT_SYMBOL(drm_atomic_helper_update_plane);
2915 
2916 /**
2917  * drm_atomic_helper_disable_plane - Helper for primary plane disable using * atomic
2918  * @plane: plane to disable
2919  * @ctx: lock acquire context
2920  *
2921  * Provides a default plane disable handler using the atomic driver interface.
2922  *
2923  * RETURNS:
2924  * Zero on success, error code on failure
2925  */
2926 int drm_atomic_helper_disable_plane(struct drm_plane *plane,
2927 				    struct drm_modeset_acquire_ctx *ctx)
2928 {
2929 	struct drm_atomic_state *state;
2930 	struct drm_plane_state *plane_state;
2931 	int ret = 0;
2932 
2933 	state = drm_atomic_state_alloc(plane->dev);
2934 	if (!state)
2935 		return -ENOMEM;
2936 
2937 	state->acquire_ctx = ctx;
2938 	plane_state = drm_atomic_get_plane_state(state, plane);
2939 	if (IS_ERR(plane_state)) {
2940 		ret = PTR_ERR(plane_state);
2941 		goto fail;
2942 	}
2943 
2944 	if (plane_state->crtc && plane_state->crtc->cursor == plane)
2945 		plane_state->state->legacy_cursor_update = true;
2946 
2947 	ret = __drm_atomic_helper_disable_plane(plane, plane_state);
2948 	if (ret != 0)
2949 		goto fail;
2950 
2951 	ret = drm_atomic_commit(state);
2952 fail:
2953 	drm_atomic_state_put(state);
2954 	return ret;
2955 }
2956 EXPORT_SYMBOL(drm_atomic_helper_disable_plane);
2957 
2958 /**
2959  * drm_atomic_helper_set_config - set a new config from userspace
2960  * @set: mode set configuration
2961  * @ctx: lock acquisition context
2962  *
2963  * Provides a default CRTC set_config handler using the atomic driver interface.
2964  *
2965  * NOTE: For backwards compatibility with old userspace this automatically
2966  * resets the "link-status" property to GOOD, to force any link
2967  * re-training. The SETCRTC ioctl does not define whether an update does
2968  * need a full modeset or just a plane update, hence we're allowed to do
2969  * that. See also drm_connector_set_link_status_property().
2970  *
2971  * Returns:
2972  * Returns 0 on success, negative errno numbers on failure.
2973  */
2974 int drm_atomic_helper_set_config(struct drm_mode_set *set,
2975 				 struct drm_modeset_acquire_ctx *ctx)
2976 {
2977 	struct drm_atomic_state *state;
2978 	struct drm_crtc *crtc = set->crtc;
2979 	int ret = 0;
2980 
2981 	state = drm_atomic_state_alloc(crtc->dev);
2982 	if (!state)
2983 		return -ENOMEM;
2984 
2985 	state->acquire_ctx = ctx;
2986 	ret = __drm_atomic_helper_set_config(set, state);
2987 	if (ret != 0)
2988 		goto fail;
2989 
2990 	ret = handle_conflicting_encoders(state, true);
2991 	if (ret)
2992 		return ret;
2993 
2994 	ret = drm_atomic_commit(state);
2995 
2996 fail:
2997 	drm_atomic_state_put(state);
2998 	return ret;
2999 }
3000 EXPORT_SYMBOL(drm_atomic_helper_set_config);
3001 
3002 /**
3003  * drm_atomic_helper_disable_all - disable all currently active outputs
3004  * @dev: DRM device
3005  * @ctx: lock acquisition context
3006  *
3007  * Loops through all connectors, finding those that aren't turned off and then
3008  * turns them off by setting their DPMS mode to OFF and deactivating the CRTC
3009  * that they are connected to.
3010  *
3011  * This is used for example in suspend/resume to disable all currently active
3012  * functions when suspending. If you just want to shut down everything at e.g.
3013  * driver unload, look at drm_atomic_helper_shutdown().
3014  *
3015  * Note that if callers haven't already acquired all modeset locks this might
3016  * return -EDEADLK, which must be handled by calling drm_modeset_backoff().
3017  *
3018  * Returns:
3019  * 0 on success or a negative error code on failure.
3020  *
3021  * See also:
3022  * drm_atomic_helper_suspend(), drm_atomic_helper_resume() and
3023  * drm_atomic_helper_shutdown().
3024  */
3025 int drm_atomic_helper_disable_all(struct drm_device *dev,
3026 				  struct drm_modeset_acquire_ctx *ctx)
3027 {
3028 	struct drm_atomic_state *state;
3029 	struct drm_connector_state *conn_state;
3030 	struct drm_connector *conn;
3031 	struct drm_plane_state *plane_state;
3032 	struct drm_plane *plane;
3033 	struct drm_crtc_state *crtc_state;
3034 	struct drm_crtc *crtc;
3035 	int ret, i;
3036 
3037 	state = drm_atomic_state_alloc(dev);
3038 	if (!state)
3039 		return -ENOMEM;
3040 
3041 	state->acquire_ctx = ctx;
3042 
3043 	drm_for_each_crtc(crtc, dev) {
3044 		crtc_state = drm_atomic_get_crtc_state(state, crtc);
3045 		if (IS_ERR(crtc_state)) {
3046 			ret = PTR_ERR(crtc_state);
3047 			goto free;
3048 		}
3049 
3050 		crtc_state->active = false;
3051 
3052 		ret = drm_atomic_set_mode_prop_for_crtc(crtc_state, NULL);
3053 		if (ret < 0)
3054 			goto free;
3055 
3056 		ret = drm_atomic_add_affected_planes(state, crtc);
3057 		if (ret < 0)
3058 			goto free;
3059 
3060 		ret = drm_atomic_add_affected_connectors(state, crtc);
3061 		if (ret < 0)
3062 			goto free;
3063 	}
3064 
3065 	for_each_new_connector_in_state(state, conn, conn_state, i) {
3066 		ret = drm_atomic_set_crtc_for_connector(conn_state, NULL);
3067 		if (ret < 0)
3068 			goto free;
3069 	}
3070 
3071 	for_each_new_plane_in_state(state, plane, plane_state, i) {
3072 		ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
3073 		if (ret < 0)
3074 			goto free;
3075 
3076 		drm_atomic_set_fb_for_plane(plane_state, NULL);
3077 	}
3078 
3079 	ret = drm_atomic_commit(state);
3080 free:
3081 	drm_atomic_state_put(state);
3082 	return ret;
3083 }
3084 EXPORT_SYMBOL(drm_atomic_helper_disable_all);
3085 
3086 /**
3087  * drm_atomic_helper_shutdown - shutdown all CRTC
3088  * @dev: DRM device
3089  *
3090  * This shuts down all CRTC, which is useful for driver unloading. Shutdown on
3091  * suspend should instead be handled with drm_atomic_helper_suspend(), since
3092  * that also takes a snapshot of the modeset state to be restored on resume.
3093  *
3094  * This is just a convenience wrapper around drm_atomic_helper_disable_all(),
3095  * and it is the atomic version of drm_crtc_force_disable_all().
3096  */
3097 void drm_atomic_helper_shutdown(struct drm_device *dev)
3098 {
3099 	struct drm_modeset_acquire_ctx ctx;
3100 	int ret;
3101 
3102 	DRM_MODESET_LOCK_ALL_BEGIN(dev, ctx, 0, ret);
3103 
3104 	ret = drm_atomic_helper_disable_all(dev, &ctx);
3105 	if (ret)
3106 		DRM_ERROR("Disabling all crtc's during unload failed with %i\n", ret);
3107 
3108 	DRM_MODESET_LOCK_ALL_END(ctx, ret);
3109 }
3110 EXPORT_SYMBOL(drm_atomic_helper_shutdown);
3111 
3112 /**
3113  * drm_atomic_helper_duplicate_state - duplicate an atomic state object
3114  * @dev: DRM device
3115  * @ctx: lock acquisition context
3116  *
3117  * Makes a copy of the current atomic state by looping over all objects and
3118  * duplicating their respective states. This is used for example by suspend/
3119  * resume support code to save the state prior to suspend such that it can
3120  * be restored upon resume.
3121  *
3122  * Note that this treats atomic state as persistent between save and restore.
3123  * Drivers must make sure that this is possible and won't result in confusion
3124  * or erroneous behaviour.
3125  *
3126  * Note that if callers haven't already acquired all modeset locks this might
3127  * return -EDEADLK, which must be handled by calling drm_modeset_backoff().
3128  *
3129  * Returns:
3130  * A pointer to the copy of the atomic state object on success or an
3131  * ERR_PTR()-encoded error code on failure.
3132  *
3133  * See also:
3134  * drm_atomic_helper_suspend(), drm_atomic_helper_resume()
3135  */
3136 struct drm_atomic_state *
3137 drm_atomic_helper_duplicate_state(struct drm_device *dev,
3138 				  struct drm_modeset_acquire_ctx *ctx)
3139 {
3140 	struct drm_atomic_state *state;
3141 	struct drm_connector *conn;
3142 	struct drm_connector_list_iter conn_iter;
3143 	struct drm_plane *plane;
3144 	struct drm_crtc *crtc;
3145 	int err = 0;
3146 
3147 	state = drm_atomic_state_alloc(dev);
3148 	if (!state)
3149 		return ERR_PTR(-ENOMEM);
3150 
3151 	state->acquire_ctx = ctx;
3152 	state->duplicated = true;
3153 
3154 	drm_for_each_crtc(crtc, dev) {
3155 		struct drm_crtc_state *crtc_state;
3156 
3157 		crtc_state = drm_atomic_get_crtc_state(state, crtc);
3158 		if (IS_ERR(crtc_state)) {
3159 			err = PTR_ERR(crtc_state);
3160 			goto free;
3161 		}
3162 	}
3163 
3164 	drm_for_each_plane(plane, dev) {
3165 		struct drm_plane_state *plane_state;
3166 
3167 		plane_state = drm_atomic_get_plane_state(state, plane);
3168 		if (IS_ERR(plane_state)) {
3169 			err = PTR_ERR(plane_state);
3170 			goto free;
3171 		}
3172 	}
3173 
3174 	drm_connector_list_iter_begin(dev, &conn_iter);
3175 	drm_for_each_connector_iter(conn, &conn_iter) {
3176 		struct drm_connector_state *conn_state;
3177 
3178 		conn_state = drm_atomic_get_connector_state(state, conn);
3179 		if (IS_ERR(conn_state)) {
3180 			err = PTR_ERR(conn_state);
3181 			drm_connector_list_iter_end(&conn_iter);
3182 			goto free;
3183 		}
3184 	}
3185 	drm_connector_list_iter_end(&conn_iter);
3186 
3187 	/* clear the acquire context so that it isn't accidentally reused */
3188 	state->acquire_ctx = NULL;
3189 
3190 free:
3191 	if (err < 0) {
3192 		drm_atomic_state_put(state);
3193 		state = ERR_PTR(err);
3194 	}
3195 
3196 	return state;
3197 }
3198 EXPORT_SYMBOL(drm_atomic_helper_duplicate_state);
3199 
3200 /**
3201  * drm_atomic_helper_suspend - subsystem-level suspend helper
3202  * @dev: DRM device
3203  *
3204  * Duplicates the current atomic state, disables all active outputs and then
3205  * returns a pointer to the original atomic state to the caller. Drivers can
3206  * pass this pointer to the drm_atomic_helper_resume() helper upon resume to
3207  * restore the output configuration that was active at the time the system
3208  * entered suspend.
3209  *
3210  * Note that it is potentially unsafe to use this. The atomic state object
3211  * returned by this function is assumed to be persistent. Drivers must ensure
3212  * that this holds true. Before calling this function, drivers must make sure
3213  * to suspend fbdev emulation so that nothing can be using the device.
3214  *
3215  * Returns:
3216  * A pointer to a copy of the state before suspend on success or an ERR_PTR()-
3217  * encoded error code on failure. Drivers should store the returned atomic
3218  * state object and pass it to the drm_atomic_helper_resume() helper upon
3219  * resume.
3220  *
3221  * See also:
3222  * drm_atomic_helper_duplicate_state(), drm_atomic_helper_disable_all(),
3223  * drm_atomic_helper_resume(), drm_atomic_helper_commit_duplicated_state()
3224  */
3225 struct drm_atomic_state *drm_atomic_helper_suspend(struct drm_device *dev)
3226 {
3227 	struct drm_modeset_acquire_ctx ctx;
3228 	struct drm_atomic_state *state;
3229 	int err;
3230 
3231 	/* This can never be returned, but it makes the compiler happy */
3232 	state = ERR_PTR(-EINVAL);
3233 
3234 	DRM_MODESET_LOCK_ALL_BEGIN(dev, ctx, 0, err);
3235 
3236 	state = drm_atomic_helper_duplicate_state(dev, &ctx);
3237 	if (IS_ERR(state))
3238 		goto unlock;
3239 
3240 	err = drm_atomic_helper_disable_all(dev, &ctx);
3241 	if (err < 0) {
3242 		drm_atomic_state_put(state);
3243 		state = ERR_PTR(err);
3244 		goto unlock;
3245 	}
3246 
3247 unlock:
3248 	DRM_MODESET_LOCK_ALL_END(ctx, err);
3249 	if (err)
3250 		return ERR_PTR(err);
3251 
3252 	return state;
3253 }
3254 EXPORT_SYMBOL(drm_atomic_helper_suspend);
3255 
3256 /**
3257  * drm_atomic_helper_commit_duplicated_state - commit duplicated state
3258  * @state: duplicated atomic state to commit
3259  * @ctx: pointer to acquire_ctx to use for commit.
3260  *
3261  * The state returned by drm_atomic_helper_duplicate_state() and
3262  * drm_atomic_helper_suspend() is partially invalid, and needs to
3263  * be fixed up before commit.
3264  *
3265  * Returns:
3266  * 0 on success or a negative error code on failure.
3267  *
3268  * See also:
3269  * drm_atomic_helper_suspend()
3270  */
3271 int drm_atomic_helper_commit_duplicated_state(struct drm_atomic_state *state,
3272 					      struct drm_modeset_acquire_ctx *ctx)
3273 {
3274 	int i, ret;
3275 	struct drm_plane *plane;
3276 	struct drm_plane_state *new_plane_state;
3277 	struct drm_connector *connector;
3278 	struct drm_connector_state *new_conn_state;
3279 	struct drm_crtc *crtc;
3280 	struct drm_crtc_state *new_crtc_state;
3281 
3282 	state->acquire_ctx = ctx;
3283 
3284 	for_each_new_plane_in_state(state, plane, new_plane_state, i)
3285 		state->planes[i].old_state = plane->state;
3286 
3287 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
3288 		state->crtcs[i].old_state = crtc->state;
3289 
3290 	for_each_new_connector_in_state(state, connector, new_conn_state, i)
3291 		state->connectors[i].old_state = connector->state;
3292 
3293 	ret = drm_atomic_commit(state);
3294 
3295 	state->acquire_ctx = NULL;
3296 
3297 	return ret;
3298 }
3299 EXPORT_SYMBOL(drm_atomic_helper_commit_duplicated_state);
3300 
3301 /**
3302  * drm_atomic_helper_resume - subsystem-level resume helper
3303  * @dev: DRM device
3304  * @state: atomic state to resume to
3305  *
3306  * Calls drm_mode_config_reset() to synchronize hardware and software states,
3307  * grabs all modeset locks and commits the atomic state object. This can be
3308  * used in conjunction with the drm_atomic_helper_suspend() helper to
3309  * implement suspend/resume for drivers that support atomic mode-setting.
3310  *
3311  * Returns:
3312  * 0 on success or a negative error code on failure.
3313  *
3314  * See also:
3315  * drm_atomic_helper_suspend()
3316  */
3317 int drm_atomic_helper_resume(struct drm_device *dev,
3318 			     struct drm_atomic_state *state)
3319 {
3320 	struct drm_modeset_acquire_ctx ctx;
3321 	int err;
3322 
3323 	drm_mode_config_reset(dev);
3324 
3325 	DRM_MODESET_LOCK_ALL_BEGIN(dev, ctx, 0, err);
3326 
3327 	err = drm_atomic_helper_commit_duplicated_state(state, &ctx);
3328 
3329 	DRM_MODESET_LOCK_ALL_END(ctx, err);
3330 	drm_atomic_state_put(state);
3331 
3332 	return err;
3333 }
3334 EXPORT_SYMBOL(drm_atomic_helper_resume);
3335 
3336 static int page_flip_common(struct drm_atomic_state *state,
3337 			    struct drm_crtc *crtc,
3338 			    struct drm_framebuffer *fb,
3339 			    struct drm_pending_vblank_event *event,
3340 			    uint32_t flags)
3341 {
3342 	struct drm_plane *plane = crtc->primary;
3343 	struct drm_plane_state *plane_state;
3344 	struct drm_crtc_state *crtc_state;
3345 	int ret = 0;
3346 
3347 	crtc_state = drm_atomic_get_crtc_state(state, crtc);
3348 	if (IS_ERR(crtc_state))
3349 		return PTR_ERR(crtc_state);
3350 
3351 	crtc_state->event = event;
3352 	crtc_state->async_flip = flags & DRM_MODE_PAGE_FLIP_ASYNC;
3353 
3354 	plane_state = drm_atomic_get_plane_state(state, plane);
3355 	if (IS_ERR(plane_state))
3356 		return PTR_ERR(plane_state);
3357 
3358 	ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
3359 	if (ret != 0)
3360 		return ret;
3361 	drm_atomic_set_fb_for_plane(plane_state, fb);
3362 
3363 	/* Make sure we don't accidentally do a full modeset. */
3364 	state->allow_modeset = false;
3365 	if (!crtc_state->active) {
3366 		DRM_DEBUG_ATOMIC("[CRTC:%d:%s] disabled, rejecting legacy flip\n",
3367 				 crtc->base.id, crtc->name);
3368 		return -EINVAL;
3369 	}
3370 
3371 	return ret;
3372 }
3373 
3374 /**
3375  * drm_atomic_helper_page_flip - execute a legacy page flip
3376  * @crtc: DRM CRTC
3377  * @fb: DRM framebuffer
3378  * @event: optional DRM event to signal upon completion
3379  * @flags: flip flags for non-vblank sync'ed updates
3380  * @ctx: lock acquisition context
3381  *
3382  * Provides a default &drm_crtc_funcs.page_flip implementation
3383  * using the atomic driver interface.
3384  *
3385  * Returns:
3386  * Returns 0 on success, negative errno numbers on failure.
3387  *
3388  * See also:
3389  * drm_atomic_helper_page_flip_target()
3390  */
3391 int drm_atomic_helper_page_flip(struct drm_crtc *crtc,
3392 				struct drm_framebuffer *fb,
3393 				struct drm_pending_vblank_event *event,
3394 				uint32_t flags,
3395 				struct drm_modeset_acquire_ctx *ctx)
3396 {
3397 	struct drm_plane *plane = crtc->primary;
3398 	struct drm_atomic_state *state;
3399 	int ret = 0;
3400 
3401 	state = drm_atomic_state_alloc(plane->dev);
3402 	if (!state)
3403 		return -ENOMEM;
3404 
3405 	state->acquire_ctx = ctx;
3406 
3407 	ret = page_flip_common(state, crtc, fb, event, flags);
3408 	if (ret != 0)
3409 		goto fail;
3410 
3411 	ret = drm_atomic_nonblocking_commit(state);
3412 fail:
3413 	drm_atomic_state_put(state);
3414 	return ret;
3415 }
3416 EXPORT_SYMBOL(drm_atomic_helper_page_flip);
3417 
3418 /**
3419  * drm_atomic_helper_page_flip_target - do page flip on target vblank period.
3420  * @crtc: DRM CRTC
3421  * @fb: DRM framebuffer
3422  * @event: optional DRM event to signal upon completion
3423  * @flags: flip flags for non-vblank sync'ed updates
3424  * @target: specifying the target vblank period when the flip to take effect
3425  * @ctx: lock acquisition context
3426  *
3427  * Provides a default &drm_crtc_funcs.page_flip_target implementation.
3428  * Similar to drm_atomic_helper_page_flip() with extra parameter to specify
3429  * target vblank period to flip.
3430  *
3431  * Returns:
3432  * Returns 0 on success, negative errno numbers on failure.
3433  */
3434 int drm_atomic_helper_page_flip_target(struct drm_crtc *crtc,
3435 				       struct drm_framebuffer *fb,
3436 				       struct drm_pending_vblank_event *event,
3437 				       uint32_t flags,
3438 				       uint32_t target,
3439 				       struct drm_modeset_acquire_ctx *ctx)
3440 {
3441 	struct drm_plane *plane = crtc->primary;
3442 	struct drm_atomic_state *state;
3443 	struct drm_crtc_state *crtc_state;
3444 	int ret = 0;
3445 
3446 	state = drm_atomic_state_alloc(plane->dev);
3447 	if (!state)
3448 		return -ENOMEM;
3449 
3450 	state->acquire_ctx = ctx;
3451 
3452 	ret = page_flip_common(state, crtc, fb, event, flags);
3453 	if (ret != 0)
3454 		goto fail;
3455 
3456 	crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
3457 	if (WARN_ON(!crtc_state)) {
3458 		ret = -EINVAL;
3459 		goto fail;
3460 	}
3461 	crtc_state->target_vblank = target;
3462 
3463 	ret = drm_atomic_nonblocking_commit(state);
3464 fail:
3465 	drm_atomic_state_put(state);
3466 	return ret;
3467 }
3468 EXPORT_SYMBOL(drm_atomic_helper_page_flip_target);
3469 
3470 /**
3471  * drm_atomic_helper_legacy_gamma_set - set the legacy gamma correction table
3472  * @crtc: CRTC object
3473  * @red: red correction table
3474  * @green: green correction table
3475  * @blue: green correction table
3476  * @size: size of the tables
3477  * @ctx: lock acquire context
3478  *
3479  * Implements support for legacy gamma correction table for drivers
3480  * that support color management through the DEGAMMA_LUT/GAMMA_LUT
3481  * properties. See drm_crtc_enable_color_mgmt() and the containing chapter for
3482  * how the atomic color management and gamma tables work.
3483  */
3484 int drm_atomic_helper_legacy_gamma_set(struct drm_crtc *crtc,
3485 				       u16 *red, u16 *green, u16 *blue,
3486 				       uint32_t size,
3487 				       struct drm_modeset_acquire_ctx *ctx)
3488 {
3489 	struct drm_device *dev = crtc->dev;
3490 	struct drm_atomic_state *state;
3491 	struct drm_crtc_state *crtc_state;
3492 	struct drm_property_blob *blob = NULL;
3493 	struct drm_color_lut *blob_data;
3494 	int i, ret = 0;
3495 	bool replaced;
3496 
3497 	state = drm_atomic_state_alloc(crtc->dev);
3498 	if (!state)
3499 		return -ENOMEM;
3500 
3501 	blob = drm_property_create_blob(dev,
3502 					sizeof(struct drm_color_lut) * size,
3503 					NULL);
3504 	if (IS_ERR(blob)) {
3505 		ret = PTR_ERR(blob);
3506 		blob = NULL;
3507 		goto fail;
3508 	}
3509 
3510 	/* Prepare GAMMA_LUT with the legacy values. */
3511 	blob_data = blob->data;
3512 	for (i = 0; i < size; i++) {
3513 		blob_data[i].red = red[i];
3514 		blob_data[i].green = green[i];
3515 		blob_data[i].blue = blue[i];
3516 	}
3517 
3518 	state->acquire_ctx = ctx;
3519 	crtc_state = drm_atomic_get_crtc_state(state, crtc);
3520 	if (IS_ERR(crtc_state)) {
3521 		ret = PTR_ERR(crtc_state);
3522 		goto fail;
3523 	}
3524 
3525 	/* Reset DEGAMMA_LUT and CTM properties. */
3526 	replaced  = drm_property_replace_blob(&crtc_state->degamma_lut, NULL);
3527 	replaced |= drm_property_replace_blob(&crtc_state->ctm, NULL);
3528 	replaced |= drm_property_replace_blob(&crtc_state->gamma_lut, blob);
3529 	crtc_state->color_mgmt_changed |= replaced;
3530 
3531 	ret = drm_atomic_commit(state);
3532 
3533 fail:
3534 	drm_atomic_state_put(state);
3535 	drm_property_blob_put(blob);
3536 	return ret;
3537 }
3538 EXPORT_SYMBOL(drm_atomic_helper_legacy_gamma_set);
3539 
3540 /**
3541  * drm_atomic_helper_bridge_propagate_bus_fmt() - Propagate output format to
3542  *						  the input end of a bridge
3543  * @bridge: bridge control structure
3544  * @bridge_state: new bridge state
3545  * @crtc_state: new CRTC state
3546  * @conn_state: new connector state
3547  * @output_fmt: tested output bus format
3548  * @num_input_fmts: will contain the size of the returned array
3549  *
3550  * This helper is a pluggable implementation of the
3551  * &drm_bridge_funcs.atomic_get_input_bus_fmts operation for bridges that don't
3552  * modify the bus configuration between their input and their output. It
3553  * returns an array of input formats with a single element set to @output_fmt.
3554  *
3555  * RETURNS:
3556  * a valid format array of size @num_input_fmts, or NULL if the allocation
3557  * failed
3558  */
3559 u32 *
3560 drm_atomic_helper_bridge_propagate_bus_fmt(struct drm_bridge *bridge,
3561 					struct drm_bridge_state *bridge_state,
3562 					struct drm_crtc_state *crtc_state,
3563 					struct drm_connector_state *conn_state,
3564 					u32 output_fmt,
3565 					unsigned int *num_input_fmts)
3566 {
3567 	u32 *input_fmts;
3568 
3569 	input_fmts = kzalloc(sizeof(*input_fmts), GFP_KERNEL);
3570 	if (!input_fmts) {
3571 		*num_input_fmts = 0;
3572 		return NULL;
3573 	}
3574 
3575 	*num_input_fmts = 1;
3576 	input_fmts[0] = output_fmt;
3577 	return input_fmts;
3578 }
3579 EXPORT_SYMBOL(drm_atomic_helper_bridge_propagate_bus_fmt);
3580