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