1 /*
2  * Copyright (c) 2006-2008 Intel Corporation
3  * Copyright (c) 2007 Dave Airlie <airlied@linux.ie>
4  *
5  * DRM core CRTC related functions
6  *
7  * Permission to use, copy, modify, distribute, and sell this software and its
8  * documentation for any purpose is hereby granted without fee, provided that
9  * the above copyright notice appear in all copies and that both that copyright
10  * notice and this permission notice appear in supporting documentation, and
11  * that the name of the copyright holders not be used in advertising or
12  * publicity pertaining to distribution of the software without specific,
13  * written prior permission.  The copyright holders make no representations
14  * about the suitability of this software for any purpose.  It is provided "as
15  * is" without express or implied warranty.
16  *
17  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
18  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
19  * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
20  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
21  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
22  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
23  * OF THIS SOFTWARE.
24  *
25  * Authors:
26  *      Keith Packard
27  *	Eric Anholt <eric@anholt.net>
28  *      Dave Airlie <airlied@linux.ie>
29  *      Jesse Barnes <jesse.barnes@intel.com>
30  */
31 
32 #include <linux/export.h>
33 #include <linux/moduleparam.h>
34 
35 #include <drm/drm_bridge.h>
36 #include <drm/drm_client.h>
37 #include <drm/drm_crtc.h>
38 #include <drm/drm_edid.h>
39 #include <drm/drm_fourcc.h>
40 #include <drm/drm_modeset_helper_vtables.h>
41 #include <drm/drm_print.h>
42 #include <drm/drm_probe_helper.h>
43 #include <drm/drm_sysfs.h>
44 
45 #include "drm_crtc_helper_internal.h"
46 
47 /**
48  * DOC: output probing helper overview
49  *
50  * This library provides some helper code for output probing. It provides an
51  * implementation of the core &drm_connector_funcs.fill_modes interface with
52  * drm_helper_probe_single_connector_modes().
53  *
54  * It also provides support for polling connectors with a work item and for
55  * generic hotplug interrupt handling where the driver doesn't or cannot keep
56  * track of a per-connector hpd interrupt.
57  *
58  * This helper library can be used independently of the modeset helper library.
59  * Drivers can also overwrite different parts e.g. use their own hotplug
60  * handling code to avoid probing unrelated outputs.
61  *
62  * The probe helpers share the function table structures with other display
63  * helper libraries. See &struct drm_connector_helper_funcs for the details.
64  */
65 
66 static bool drm_kms_helper_poll = true;
67 module_param_named(poll, drm_kms_helper_poll, bool, 0600);
68 
69 static enum drm_mode_status
70 drm_mode_validate_flag(const struct drm_display_mode *mode,
71 		       int flags)
72 {
73 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) &&
74 	    !(flags & DRM_MODE_FLAG_INTERLACE))
75 		return MODE_NO_INTERLACE;
76 
77 	if ((mode->flags & DRM_MODE_FLAG_DBLSCAN) &&
78 	    !(flags & DRM_MODE_FLAG_DBLSCAN))
79 		return MODE_NO_DBLESCAN;
80 
81 	if ((mode->flags & DRM_MODE_FLAG_3D_MASK) &&
82 	    !(flags & DRM_MODE_FLAG_3D_MASK))
83 		return MODE_NO_STEREO;
84 
85 	return MODE_OK;
86 }
87 
88 static int
89 drm_mode_validate_pipeline(struct drm_display_mode *mode,
90 			   struct drm_connector *connector,
91 			   struct drm_modeset_acquire_ctx *ctx,
92 			   enum drm_mode_status *status)
93 {
94 	struct drm_device *dev = connector->dev;
95 	struct drm_encoder *encoder;
96 	int ret;
97 
98 	/* Step 1: Validate against connector */
99 	ret = drm_connector_mode_valid(connector, mode, ctx, status);
100 	if (ret || *status != MODE_OK)
101 		return ret;
102 
103 	/* Step 2: Validate against encoders and crtcs */
104 	drm_connector_for_each_possible_encoder(connector, encoder) {
105 		struct drm_bridge *bridge;
106 		struct drm_crtc *crtc;
107 
108 		*status = drm_encoder_mode_valid(encoder, mode);
109 		if (*status != MODE_OK) {
110 			/* No point in continuing for crtc check as this encoder
111 			 * will not accept the mode anyway. If all encoders
112 			 * reject the mode then, at exit, ret will not be
113 			 * MODE_OK. */
114 			continue;
115 		}
116 
117 		bridge = drm_bridge_chain_get_first_bridge(encoder);
118 		*status = drm_bridge_chain_mode_valid(bridge,
119 						      &connector->display_info,
120 						      mode);
121 		if (*status != MODE_OK) {
122 			/* There is also no point in continuing for crtc check
123 			 * here. */
124 			continue;
125 		}
126 
127 		drm_for_each_crtc(crtc, dev) {
128 			if (!drm_encoder_crtc_ok(encoder, crtc))
129 				continue;
130 
131 			*status = drm_crtc_mode_valid(crtc, mode);
132 			if (*status == MODE_OK) {
133 				/* If we get to this point there is at least
134 				 * one combination of encoder+crtc that works
135 				 * for this mode. Lets return now. */
136 				return 0;
137 			}
138 		}
139 	}
140 
141 	return 0;
142 }
143 
144 static int drm_helper_probe_add_cmdline_mode(struct drm_connector *connector)
145 {
146 	struct drm_cmdline_mode *cmdline_mode;
147 	struct drm_display_mode *mode;
148 
149 	cmdline_mode = &connector->cmdline_mode;
150 	if (!cmdline_mode->specified)
151 		return 0;
152 
153 	/* Only add a GTF mode if we find no matching probed modes */
154 	list_for_each_entry(mode, &connector->probed_modes, head) {
155 		if (mode->hdisplay != cmdline_mode->xres ||
156 		    mode->vdisplay != cmdline_mode->yres)
157 			continue;
158 
159 		if (cmdline_mode->refresh_specified) {
160 			/* The probed mode's vrefresh is set until later */
161 			if (drm_mode_vrefresh(mode) != cmdline_mode->refresh)
162 				continue;
163 		}
164 
165 		/* Mark the matching mode as being preferred by the user */
166 		mode->type |= DRM_MODE_TYPE_USERDEF;
167 		return 0;
168 	}
169 
170 	mode = drm_mode_create_from_cmdline_mode(connector->dev,
171 						 cmdline_mode);
172 	if (mode == NULL)
173 		return 0;
174 
175 	drm_mode_probed_add(connector, mode);
176 	return 1;
177 }
178 
179 enum drm_mode_status drm_crtc_mode_valid(struct drm_crtc *crtc,
180 					 const struct drm_display_mode *mode)
181 {
182 	const struct drm_crtc_helper_funcs *crtc_funcs = crtc->helper_private;
183 
184 	if (!crtc_funcs || !crtc_funcs->mode_valid)
185 		return MODE_OK;
186 
187 	return crtc_funcs->mode_valid(crtc, mode);
188 }
189 
190 enum drm_mode_status drm_encoder_mode_valid(struct drm_encoder *encoder,
191 					    const struct drm_display_mode *mode)
192 {
193 	const struct drm_encoder_helper_funcs *encoder_funcs =
194 		encoder->helper_private;
195 
196 	if (!encoder_funcs || !encoder_funcs->mode_valid)
197 		return MODE_OK;
198 
199 	return encoder_funcs->mode_valid(encoder, mode);
200 }
201 
202 int
203 drm_connector_mode_valid(struct drm_connector *connector,
204 			 struct drm_display_mode *mode,
205 			 struct drm_modeset_acquire_ctx *ctx,
206 			 enum drm_mode_status *status)
207 {
208 	const struct drm_connector_helper_funcs *connector_funcs =
209 		connector->helper_private;
210 	int ret = 0;
211 
212 	if (!connector_funcs)
213 		*status = MODE_OK;
214 	else if (connector_funcs->mode_valid_ctx)
215 		ret = connector_funcs->mode_valid_ctx(connector, mode, ctx,
216 						      status);
217 	else if (connector_funcs->mode_valid)
218 		*status = connector_funcs->mode_valid(connector, mode);
219 	else
220 		*status = MODE_OK;
221 
222 	return ret;
223 }
224 
225 #define DRM_OUTPUT_POLL_PERIOD (10*HZ)
226 /**
227  * drm_kms_helper_poll_enable - re-enable output polling.
228  * @dev: drm_device
229  *
230  * This function re-enables the output polling work, after it has been
231  * temporarily disabled using drm_kms_helper_poll_disable(), for example over
232  * suspend/resume.
233  *
234  * Drivers can call this helper from their device resume implementation. It is
235  * not an error to call this even when output polling isn't enabled.
236  *
237  * Note that calls to enable and disable polling must be strictly ordered, which
238  * is automatically the case when they're only call from suspend/resume
239  * callbacks.
240  */
241 void drm_kms_helper_poll_enable(struct drm_device *dev)
242 {
243 	bool poll = false;
244 	struct drm_connector *connector;
245 	struct drm_connector_list_iter conn_iter;
246 	unsigned long delay = DRM_OUTPUT_POLL_PERIOD;
247 
248 	if (!dev->mode_config.poll_enabled || !drm_kms_helper_poll)
249 		return;
250 
251 	drm_connector_list_iter_begin(dev, &conn_iter);
252 	drm_for_each_connector_iter(connector, &conn_iter) {
253 		const struct drm_connector_helper_funcs *funcs =
254 			connector->helper_private;
255 
256 		if (funcs && funcs->enable_hpd)
257 			funcs->enable_hpd(connector);
258 
259 		if (connector->polled & (DRM_CONNECTOR_POLL_CONNECT |
260 					 DRM_CONNECTOR_POLL_DISCONNECT))
261 			poll = true;
262 	}
263 	drm_connector_list_iter_end(&conn_iter);
264 
265 	if (dev->mode_config.delayed_event) {
266 		/*
267 		 * FIXME:
268 		 *
269 		 * Use short (1s) delay to handle the initial delayed event.
270 		 * This delay should not be needed, but Optimus/nouveau will
271 		 * fail in a mysterious way if the delayed event is handled as
272 		 * soon as possible like it is done in
273 		 * drm_helper_probe_single_connector_modes() in case the poll
274 		 * was enabled before.
275 		 */
276 		poll = true;
277 		delay = HZ;
278 	}
279 
280 	if (poll)
281 		schedule_delayed_work(&dev->mode_config.output_poll_work, delay);
282 }
283 EXPORT_SYMBOL(drm_kms_helper_poll_enable);
284 
285 static enum drm_connector_status
286 drm_helper_probe_detect_ctx(struct drm_connector *connector, bool force)
287 {
288 	const struct drm_connector_helper_funcs *funcs = connector->helper_private;
289 	struct drm_modeset_acquire_ctx ctx;
290 	int ret;
291 
292 	drm_modeset_acquire_init(&ctx, 0);
293 
294 retry:
295 	ret = drm_modeset_lock(&connector->dev->mode_config.connection_mutex, &ctx);
296 	if (!ret) {
297 		if (funcs->detect_ctx)
298 			ret = funcs->detect_ctx(connector, &ctx, force);
299 		else if (connector->funcs->detect)
300 			ret = connector->funcs->detect(connector, force);
301 		else
302 			ret = connector_status_connected;
303 	}
304 
305 	if (ret == -EDEADLK) {
306 		drm_modeset_backoff(&ctx);
307 		goto retry;
308 	}
309 
310 	if (WARN_ON(ret < 0))
311 		ret = connector_status_unknown;
312 
313 	if (ret != connector->status)
314 		connector->epoch_counter += 1;
315 
316 	drm_modeset_drop_locks(&ctx);
317 	drm_modeset_acquire_fini(&ctx);
318 
319 	return ret;
320 }
321 
322 /**
323  * drm_helper_probe_detect - probe connector status
324  * @connector: connector to probe
325  * @ctx: acquire_ctx, or NULL to let this function handle locking.
326  * @force: Whether destructive probe operations should be performed.
327  *
328  * This function calls the detect callbacks of the connector.
329  * This function returns &drm_connector_status, or
330  * if @ctx is set, it might also return -EDEADLK.
331  */
332 int
333 drm_helper_probe_detect(struct drm_connector *connector,
334 			struct drm_modeset_acquire_ctx *ctx,
335 			bool force)
336 {
337 	const struct drm_connector_helper_funcs *funcs = connector->helper_private;
338 	struct drm_device *dev = connector->dev;
339 	int ret;
340 
341 	if (!ctx)
342 		return drm_helper_probe_detect_ctx(connector, force);
343 
344 	ret = drm_modeset_lock(&dev->mode_config.connection_mutex, ctx);
345 	if (ret)
346 		return ret;
347 
348 	if (funcs->detect_ctx)
349 		ret = funcs->detect_ctx(connector, ctx, force);
350 	else if (connector->funcs->detect)
351 		ret = connector->funcs->detect(connector, force);
352 	else
353 		ret = connector_status_connected;
354 
355 	if (ret != connector->status)
356 		connector->epoch_counter += 1;
357 
358 	return ret;
359 }
360 EXPORT_SYMBOL(drm_helper_probe_detect);
361 
362 static int drm_helper_probe_get_modes(struct drm_connector *connector)
363 {
364 	const struct drm_connector_helper_funcs *connector_funcs =
365 		connector->helper_private;
366 	int count;
367 
368 	count = connector_funcs->get_modes(connector);
369 
370 	/*
371 	 * Fallback for when DDC probe failed in drm_get_edid() and thus skipped
372 	 * override/firmware EDID.
373 	 */
374 	if (count == 0 && connector->status == connector_status_connected)
375 		count = drm_edid_override_connector_update(connector);
376 
377 	return count;
378 }
379 
380 static int __drm_helper_update_and_validate(struct drm_connector *connector,
381 					    uint32_t maxX, uint32_t maxY,
382 					    struct drm_modeset_acquire_ctx *ctx)
383 {
384 	struct drm_device *dev = connector->dev;
385 	struct drm_display_mode *mode;
386 	int mode_flags = 0;
387 	int ret;
388 
389 	drm_connector_list_update(connector);
390 
391 	if (connector->interlace_allowed)
392 		mode_flags |= DRM_MODE_FLAG_INTERLACE;
393 	if (connector->doublescan_allowed)
394 		mode_flags |= DRM_MODE_FLAG_DBLSCAN;
395 	if (connector->stereo_allowed)
396 		mode_flags |= DRM_MODE_FLAG_3D_MASK;
397 
398 	list_for_each_entry(mode, &connector->modes, head) {
399 		if (mode->status != MODE_OK)
400 			continue;
401 
402 		mode->status = drm_mode_validate_driver(dev, mode);
403 		if (mode->status != MODE_OK)
404 			continue;
405 
406 		mode->status = drm_mode_validate_size(mode, maxX, maxY);
407 		if (mode->status != MODE_OK)
408 			continue;
409 
410 		mode->status = drm_mode_validate_flag(mode, mode_flags);
411 		if (mode->status != MODE_OK)
412 			continue;
413 
414 		ret = drm_mode_validate_pipeline(mode, connector, ctx,
415 						 &mode->status);
416 		if (ret) {
417 			drm_dbg_kms(dev,
418 				    "drm_mode_validate_pipeline failed: %d\n",
419 				    ret);
420 
421 			if (drm_WARN_ON_ONCE(dev, ret != -EDEADLK))
422 				mode->status = MODE_ERROR;
423 			else
424 				return -EDEADLK;
425 		}
426 
427 		if (mode->status != MODE_OK)
428 			continue;
429 		mode->status = drm_mode_validate_ycbcr420(mode, connector);
430 	}
431 
432 	return 0;
433 }
434 
435 /**
436  * drm_helper_probe_single_connector_modes - get complete set of display modes
437  * @connector: connector to probe
438  * @maxX: max width for modes
439  * @maxY: max height for modes
440  *
441  * Based on the helper callbacks implemented by @connector in struct
442  * &drm_connector_helper_funcs try to detect all valid modes.  Modes will first
443  * be added to the connector's probed_modes list, then culled (based on validity
444  * and the @maxX, @maxY parameters) and put into the normal modes list.
445  *
446  * Intended to be used as a generic implementation of the
447  * &drm_connector_funcs.fill_modes() vfunc for drivers that use the CRTC helpers
448  * for output mode filtering and detection.
449  *
450  * The basic procedure is as follows
451  *
452  * 1. All modes currently on the connector's modes list are marked as stale
453  *
454  * 2. New modes are added to the connector's probed_modes list with
455  *    drm_mode_probed_add(). New modes start their life with status as OK.
456  *    Modes are added from a single source using the following priority order.
457  *
458  *    - &drm_connector_helper_funcs.get_modes vfunc
459  *    - if the connector status is connector_status_connected, standard
460  *      VESA DMT modes up to 1024x768 are automatically added
461  *      (drm_add_modes_noedid())
462  *
463  *    Finally modes specified via the kernel command line (video=...) are
464  *    added in addition to what the earlier probes produced
465  *    (drm_helper_probe_add_cmdline_mode()). These modes are generated
466  *    using the VESA GTF/CVT formulas.
467  *
468  * 3. Modes are moved from the probed_modes list to the modes list. Potential
469  *    duplicates are merged together (see drm_connector_list_update()).
470  *    After this step the probed_modes list will be empty again.
471  *
472  * 4. Any non-stale mode on the modes list then undergoes validation
473  *
474  *    - drm_mode_validate_basic() performs basic sanity checks
475  *    - drm_mode_validate_size() filters out modes larger than @maxX and @maxY
476  *      (if specified)
477  *    - drm_mode_validate_flag() checks the modes against basic connector
478  *      capabilities (interlace_allowed,doublescan_allowed,stereo_allowed)
479  *    - the optional &drm_connector_helper_funcs.mode_valid or
480  *      &drm_connector_helper_funcs.mode_valid_ctx helpers can perform driver
481  *      and/or sink specific checks
482  *    - the optional &drm_crtc_helper_funcs.mode_valid,
483  *      &drm_bridge_funcs.mode_valid and &drm_encoder_helper_funcs.mode_valid
484  *      helpers can perform driver and/or source specific checks which are also
485  *      enforced by the modeset/atomic helpers
486  *
487  * 5. Any mode whose status is not OK is pruned from the connector's modes list,
488  *    accompanied by a debug message indicating the reason for the mode's
489  *    rejection (see drm_mode_prune_invalid()).
490  *
491  * Returns:
492  * The number of modes found on @connector.
493  */
494 int drm_helper_probe_single_connector_modes(struct drm_connector *connector,
495 					    uint32_t maxX, uint32_t maxY)
496 {
497 	struct drm_device *dev = connector->dev;
498 	struct drm_display_mode *mode;
499 	int count = 0, ret;
500 	enum drm_connector_status old_status;
501 	struct drm_modeset_acquire_ctx ctx;
502 
503 	WARN_ON(!mutex_is_locked(&dev->mode_config.mutex));
504 
505 	drm_modeset_acquire_init(&ctx, 0);
506 
507 	DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n", connector->base.id,
508 			connector->name);
509 
510 retry:
511 	ret = drm_modeset_lock(&dev->mode_config.connection_mutex, &ctx);
512 	if (ret == -EDEADLK) {
513 		drm_modeset_backoff(&ctx);
514 		goto retry;
515 	} else
516 		WARN_ON(ret < 0);
517 
518 	/* set all old modes to the stale state */
519 	list_for_each_entry(mode, &connector->modes, head)
520 		mode->status = MODE_STALE;
521 
522 	old_status = connector->status;
523 
524 	if (connector->force) {
525 		if (connector->force == DRM_FORCE_ON ||
526 		    connector->force == DRM_FORCE_ON_DIGITAL)
527 			connector->status = connector_status_connected;
528 		else
529 			connector->status = connector_status_disconnected;
530 		if (connector->funcs->force)
531 			connector->funcs->force(connector);
532 	} else {
533 		ret = drm_helper_probe_detect(connector, &ctx, true);
534 
535 		if (ret == -EDEADLK) {
536 			drm_modeset_backoff(&ctx);
537 			goto retry;
538 		} else if (WARN(ret < 0, "Invalid return value %i for connector detection\n", ret))
539 			ret = connector_status_unknown;
540 
541 		connector->status = ret;
542 	}
543 
544 	/*
545 	 * Normally either the driver's hpd code or the poll loop should
546 	 * pick up any changes and fire the hotplug event. But if
547 	 * userspace sneaks in a probe, we might miss a change. Hence
548 	 * check here, and if anything changed start the hotplug code.
549 	 */
550 	if (old_status != connector->status) {
551 		DRM_DEBUG_KMS("[CONNECTOR:%d:%s] status updated from %s to %s\n",
552 			      connector->base.id,
553 			      connector->name,
554 			      drm_get_connector_status_name(old_status),
555 			      drm_get_connector_status_name(connector->status));
556 
557 		/*
558 		 * The hotplug event code might call into the fb
559 		 * helpers, and so expects that we do not hold any
560 		 * locks. Fire up the poll struct instead, it will
561 		 * disable itself again.
562 		 */
563 		dev->mode_config.delayed_event = true;
564 		if (dev->mode_config.poll_enabled)
565 			schedule_delayed_work(&dev->mode_config.output_poll_work,
566 					      0);
567 	}
568 
569 	/* Re-enable polling in case the global poll config changed. */
570 	if (drm_kms_helper_poll != dev->mode_config.poll_running)
571 		drm_kms_helper_poll_enable(dev);
572 
573 	dev->mode_config.poll_running = drm_kms_helper_poll;
574 
575 	if (connector->status == connector_status_disconnected) {
576 		DRM_DEBUG_KMS("[CONNECTOR:%d:%s] disconnected\n",
577 			connector->base.id, connector->name);
578 		drm_connector_update_edid_property(connector, NULL);
579 		drm_mode_prune_invalid(dev, &connector->modes, false);
580 		goto exit;
581 	}
582 
583 	count = drm_helper_probe_get_modes(connector);
584 
585 	if (count == 0 && (connector->status == connector_status_connected ||
586 			   connector->status == connector_status_unknown)) {
587 		count = drm_add_modes_noedid(connector, 1024, 768);
588 
589 		/*
590 		 * Section 4.2.2.6 (EDID Corruption Detection) of the DP 1.4a
591 		 * Link CTS specifies that 640x480 (the official "failsafe"
592 		 * mode) needs to be the default if there's no EDID.
593 		 */
594 		if (connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort)
595 			drm_set_preferred_mode(connector, 640, 480);
596 	}
597 	count += drm_helper_probe_add_cmdline_mode(connector);
598 	if (count != 0) {
599 		ret = __drm_helper_update_and_validate(connector, maxX, maxY, &ctx);
600 		if (ret == -EDEADLK) {
601 			drm_modeset_backoff(&ctx);
602 			goto retry;
603 		}
604 	}
605 
606 	drm_mode_prune_invalid(dev, &connector->modes, true);
607 
608 	/*
609 	 * Displayport spec section 5.2.1.2 ("Video Timing Format") says that
610 	 * all detachable sinks shall support 640x480 @60Hz as a fail safe
611 	 * mode. If all modes were pruned, perhaps because they need more
612 	 * lanes or a higher pixel clock than available, at least try to add
613 	 * in 640x480.
614 	 */
615 	if (list_empty(&connector->modes) &&
616 	    connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
617 		count = drm_add_modes_noedid(connector, 640, 480);
618 		ret = __drm_helper_update_and_validate(connector, maxX, maxY, &ctx);
619 		if (ret == -EDEADLK) {
620 			drm_modeset_backoff(&ctx);
621 			goto retry;
622 		}
623 		drm_mode_prune_invalid(dev, &connector->modes, true);
624 	}
625 
626 exit:
627 	drm_modeset_drop_locks(&ctx);
628 	drm_modeset_acquire_fini(&ctx);
629 
630 	if (list_empty(&connector->modes))
631 		return 0;
632 
633 	drm_mode_sort(&connector->modes);
634 
635 	DRM_DEBUG_KMS("[CONNECTOR:%d:%s] probed modes :\n", connector->base.id,
636 			connector->name);
637 	list_for_each_entry(mode, &connector->modes, head) {
638 		drm_mode_set_crtcinfo(mode, CRTC_INTERLACE_HALVE_V);
639 		drm_mode_debug_printmodeline(mode);
640 	}
641 
642 	return count;
643 }
644 EXPORT_SYMBOL(drm_helper_probe_single_connector_modes);
645 
646 /**
647  * drm_kms_helper_hotplug_event - fire off KMS hotplug events
648  * @dev: drm_device whose connector state changed
649  *
650  * This function fires off the uevent for userspace and also calls the
651  * output_poll_changed function, which is most commonly used to inform the fbdev
652  * emulation code and allow it to update the fbcon output configuration.
653  *
654  * Drivers should call this from their hotplug handling code when a change is
655  * detected. Note that this function does not do any output detection of its
656  * own, like drm_helper_hpd_irq_event() does - this is assumed to be done by the
657  * driver already.
658  *
659  * This function must be called from process context with no mode
660  * setting locks held.
661  *
662  * If only a single connector has changed, consider calling
663  * drm_kms_helper_connector_hotplug_event() instead.
664  */
665 void drm_kms_helper_hotplug_event(struct drm_device *dev)
666 {
667 	/* send a uevent + call fbdev */
668 	drm_sysfs_hotplug_event(dev);
669 	if (dev->mode_config.funcs->output_poll_changed)
670 		dev->mode_config.funcs->output_poll_changed(dev);
671 
672 	drm_client_dev_hotplug(dev);
673 }
674 EXPORT_SYMBOL(drm_kms_helper_hotplug_event);
675 
676 /**
677  * drm_kms_helper_connector_hotplug_event - fire off a KMS connector hotplug event
678  * @connector: drm_connector which has changed
679  *
680  * This is the same as drm_kms_helper_hotplug_event(), except it fires a more
681  * fine-grained uevent for a single connector.
682  */
683 void drm_kms_helper_connector_hotplug_event(struct drm_connector *connector)
684 {
685 	struct drm_device *dev = connector->dev;
686 
687 	/* send a uevent + call fbdev */
688 	drm_sysfs_connector_hotplug_event(connector);
689 	if (dev->mode_config.funcs->output_poll_changed)
690 		dev->mode_config.funcs->output_poll_changed(dev);
691 
692 	drm_client_dev_hotplug(dev);
693 }
694 EXPORT_SYMBOL(drm_kms_helper_connector_hotplug_event);
695 
696 static void output_poll_execute(struct work_struct *work)
697 {
698 	struct delayed_work *delayed_work = to_delayed_work(work);
699 	struct drm_device *dev = container_of(delayed_work, struct drm_device, mode_config.output_poll_work);
700 	struct drm_connector *connector;
701 	struct drm_connector_list_iter conn_iter;
702 	enum drm_connector_status old_status;
703 	bool repoll = false, changed;
704 	u64 old_epoch_counter;
705 
706 	if (!dev->mode_config.poll_enabled)
707 		return;
708 
709 	/* Pick up any changes detected by the probe functions. */
710 	changed = dev->mode_config.delayed_event;
711 	dev->mode_config.delayed_event = false;
712 
713 	if (!drm_kms_helper_poll)
714 		goto out;
715 
716 	if (!mutex_trylock(&dev->mode_config.mutex)) {
717 		repoll = true;
718 		goto out;
719 	}
720 
721 	drm_connector_list_iter_begin(dev, &conn_iter);
722 	drm_for_each_connector_iter(connector, &conn_iter) {
723 		/* Ignore forced connectors. */
724 		if (connector->force)
725 			continue;
726 
727 		/* Ignore HPD capable connectors and connectors where we don't
728 		 * want any hotplug detection at all for polling. */
729 		if (!connector->polled || connector->polled == DRM_CONNECTOR_POLL_HPD)
730 			continue;
731 
732 		old_status = connector->status;
733 		/* if we are connected and don't want to poll for disconnect
734 		   skip it */
735 		if (old_status == connector_status_connected &&
736 		    !(connector->polled & DRM_CONNECTOR_POLL_DISCONNECT))
737 			continue;
738 
739 		repoll = true;
740 
741 		old_epoch_counter = connector->epoch_counter;
742 		connector->status = drm_helper_probe_detect(connector, NULL, false);
743 		if (old_epoch_counter != connector->epoch_counter) {
744 			const char *old, *new;
745 
746 			/*
747 			 * The poll work sets force=false when calling detect so
748 			 * that drivers can avoid to do disruptive tests (e.g.
749 			 * when load detect cycles could cause flickering on
750 			 * other, running displays). This bears the risk that we
751 			 * flip-flop between unknown here in the poll work and
752 			 * the real state when userspace forces a full detect
753 			 * call after receiving a hotplug event due to this
754 			 * change.
755 			 *
756 			 * Hence clamp an unknown detect status to the old
757 			 * value.
758 			 */
759 			if (connector->status == connector_status_unknown) {
760 				connector->status = old_status;
761 				continue;
762 			}
763 
764 			old = drm_get_connector_status_name(old_status);
765 			new = drm_get_connector_status_name(connector->status);
766 
767 			DRM_DEBUG_KMS("[CONNECTOR:%d:%s] "
768 				      "status updated from %s to %s\n",
769 				      connector->base.id,
770 				      connector->name,
771 				      old, new);
772 			DRM_DEBUG_KMS("[CONNECTOR:%d:%s] epoch counter %llu -> %llu\n",
773 				      connector->base.id, connector->name,
774 				      old_epoch_counter, connector->epoch_counter);
775 
776 			changed = true;
777 		}
778 	}
779 	drm_connector_list_iter_end(&conn_iter);
780 
781 	mutex_unlock(&dev->mode_config.mutex);
782 
783 out:
784 	if (changed)
785 		drm_kms_helper_hotplug_event(dev);
786 
787 	if (repoll)
788 		schedule_delayed_work(delayed_work, DRM_OUTPUT_POLL_PERIOD);
789 }
790 
791 /**
792  * drm_kms_helper_is_poll_worker - is %current task an output poll worker?
793  *
794  * Determine if %current task is an output poll worker.  This can be used
795  * to select distinct code paths for output polling versus other contexts.
796  *
797  * One use case is to avoid a deadlock between the output poll worker and
798  * the autosuspend worker wherein the latter waits for polling to finish
799  * upon calling drm_kms_helper_poll_disable(), while the former waits for
800  * runtime suspend to finish upon calling pm_runtime_get_sync() in a
801  * connector ->detect hook.
802  */
803 bool drm_kms_helper_is_poll_worker(void)
804 {
805 	struct work_struct *work = current_work();
806 
807 	return work && work->func == output_poll_execute;
808 }
809 EXPORT_SYMBOL(drm_kms_helper_is_poll_worker);
810 
811 static void drm_kms_helper_poll_disable_fini(struct drm_device *dev, bool fini)
812 {
813 	struct drm_connector *connector;
814 	struct drm_connector_list_iter conn_iter;
815 
816 	if (!dev->mode_config.poll_enabled)
817 		return;
818 
819 	if (fini)
820 		dev->mode_config.poll_enabled = false;
821 
822 	drm_connector_list_iter_begin(dev, &conn_iter);
823 	drm_for_each_connector_iter(connector, &conn_iter) {
824 		const struct drm_connector_helper_funcs *funcs =
825 			connector->helper_private;
826 
827 		if (funcs && funcs->disable_hpd)
828 			funcs->disable_hpd(connector);
829 	}
830 	drm_connector_list_iter_end(&conn_iter);
831 
832 	cancel_delayed_work_sync(&dev->mode_config.output_poll_work);
833 }
834 
835 /**
836  * drm_kms_helper_poll_disable - disable output polling
837  * @dev: drm_device
838  *
839  * This function disables the output polling work.
840  *
841  * Drivers can call this helper from their device suspend implementation. It is
842  * not an error to call this even when output polling isn't enabled or already
843  * disabled. Polling is re-enabled by calling drm_kms_helper_poll_enable().
844  *
845  * Note that calls to enable and disable polling must be strictly ordered, which
846  * is automatically the case when they're only call from suspend/resume
847  * callbacks.
848  */
849 void drm_kms_helper_poll_disable(struct drm_device *dev)
850 {
851 	drm_kms_helper_poll_disable_fini(dev, false);
852 }
853 EXPORT_SYMBOL(drm_kms_helper_poll_disable);
854 
855 /**
856  * drm_kms_helper_poll_init - initialize and enable output polling
857  * @dev: drm_device
858  *
859  * This function initializes and then also enables output polling support for
860  * @dev. Drivers which do not have reliable hotplug support in hardware can use
861  * this helper infrastructure to regularly poll such connectors for changes in
862  * their connection state.
863  *
864  * Drivers can control which connectors are polled by setting the
865  * DRM_CONNECTOR_POLL_CONNECT and DRM_CONNECTOR_POLL_DISCONNECT flags. On
866  * connectors where probing live outputs can result in visual distortion drivers
867  * should not set the DRM_CONNECTOR_POLL_DISCONNECT flag to avoid this.
868  * Connectors which have no flag or only DRM_CONNECTOR_POLL_HPD set are
869  * completely ignored by the polling logic.
870  *
871  * Note that a connector can be both polled and probed from the hotplug handler,
872  * in case the hotplug interrupt is known to be unreliable.
873  */
874 void drm_kms_helper_poll_init(struct drm_device *dev)
875 {
876 	INIT_DELAYED_WORK(&dev->mode_config.output_poll_work, output_poll_execute);
877 	dev->mode_config.poll_enabled = true;
878 
879 	drm_kms_helper_poll_enable(dev);
880 }
881 EXPORT_SYMBOL(drm_kms_helper_poll_init);
882 
883 /**
884  * drm_kms_helper_poll_fini - disable output polling and clean it up
885  * @dev: drm_device
886  */
887 void drm_kms_helper_poll_fini(struct drm_device *dev)
888 {
889 	drm_kms_helper_poll_disable_fini(dev, true);
890 }
891 EXPORT_SYMBOL(drm_kms_helper_poll_fini);
892 
893 static bool check_connector_changed(struct drm_connector *connector)
894 {
895 	struct drm_device *dev = connector->dev;
896 	enum drm_connector_status old_status;
897 	u64 old_epoch_counter;
898 
899 	/* Only handle HPD capable connectors. */
900 	drm_WARN_ON(dev, !(connector->polled & DRM_CONNECTOR_POLL_HPD));
901 
902 	drm_WARN_ON(dev, !mutex_is_locked(&dev->mode_config.mutex));
903 
904 	old_status = connector->status;
905 	old_epoch_counter = connector->epoch_counter;
906 	connector->status = drm_helper_probe_detect(connector, NULL, false);
907 
908 	if (old_epoch_counter == connector->epoch_counter) {
909 		drm_dbg_kms(dev, "[CONNECTOR:%d:%s] Same epoch counter %llu\n",
910 			    connector->base.id,
911 			    connector->name,
912 			    connector->epoch_counter);
913 
914 		return false;
915 	}
916 
917 	drm_dbg_kms(dev, "[CONNECTOR:%d:%s] status updated from %s to %s\n",
918 		    connector->base.id,
919 		    connector->name,
920 		    drm_get_connector_status_name(old_status),
921 		    drm_get_connector_status_name(connector->status));
922 
923 	drm_dbg_kms(dev, "[CONNECTOR:%d:%s] Changed epoch counter %llu => %llu\n",
924 		    connector->base.id,
925 		    connector->name,
926 		    old_epoch_counter,
927 		    connector->epoch_counter);
928 
929 	return true;
930 }
931 
932 /**
933  * drm_connector_helper_hpd_irq_event - hotplug processing
934  * @connector: drm_connector
935  *
936  * Drivers can use this helper function to run a detect cycle on a connector
937  * which has the DRM_CONNECTOR_POLL_HPD flag set in its &polled member.
938  *
939  * This helper function is useful for drivers which can track hotplug
940  * interrupts for a single connector. Drivers that want to send a
941  * hotplug event for all connectors or can't track hotplug interrupts
942  * per connector need to use drm_helper_hpd_irq_event().
943  *
944  * This function must be called from process context with no mode
945  * setting locks held.
946  *
947  * Note that a connector can be both polled and probed from the hotplug
948  * handler, in case the hotplug interrupt is known to be unreliable.
949  *
950  * Returns:
951  * A boolean indicating whether the connector status changed or not
952  */
953 bool drm_connector_helper_hpd_irq_event(struct drm_connector *connector)
954 {
955 	struct drm_device *dev = connector->dev;
956 	bool changed;
957 
958 	mutex_lock(&dev->mode_config.mutex);
959 	changed = check_connector_changed(connector);
960 	mutex_unlock(&dev->mode_config.mutex);
961 
962 	if (changed) {
963 		drm_kms_helper_connector_hotplug_event(connector);
964 		drm_dbg_kms(dev, "[CONNECTOR:%d:%s] Sent hotplug event\n",
965 			    connector->base.id,
966 			    connector->name);
967 	}
968 
969 	return changed;
970 }
971 EXPORT_SYMBOL(drm_connector_helper_hpd_irq_event);
972 
973 /**
974  * drm_helper_hpd_irq_event - hotplug processing
975  * @dev: drm_device
976  *
977  * Drivers can use this helper function to run a detect cycle on all connectors
978  * which have the DRM_CONNECTOR_POLL_HPD flag set in their &polled member. All
979  * other connectors are ignored, which is useful to avoid reprobing fixed
980  * panels.
981  *
982  * This helper function is useful for drivers which can't or don't track hotplug
983  * interrupts for each connector.
984  *
985  * Drivers which support hotplug interrupts for each connector individually and
986  * which have a more fine-grained detect logic can use
987  * drm_connector_helper_hpd_irq_event(). Alternatively, they should bypass this
988  * code and directly call drm_kms_helper_hotplug_event() in case the connector
989  * state changed.
990  *
991  * This function must be called from process context with no mode
992  * setting locks held.
993  *
994  * Note that a connector can be both polled and probed from the hotplug handler,
995  * in case the hotplug interrupt is known to be unreliable.
996  *
997  * Returns:
998  * A boolean indicating whether the connector status changed or not
999  */
1000 bool drm_helper_hpd_irq_event(struct drm_device *dev)
1001 {
1002 	struct drm_connector *connector, *first_changed_connector = NULL;
1003 	struct drm_connector_list_iter conn_iter;
1004 	int changed = 0;
1005 
1006 	if (!dev->mode_config.poll_enabled)
1007 		return false;
1008 
1009 	mutex_lock(&dev->mode_config.mutex);
1010 	drm_connector_list_iter_begin(dev, &conn_iter);
1011 	drm_for_each_connector_iter(connector, &conn_iter) {
1012 		/* Only handle HPD capable connectors. */
1013 		if (!(connector->polled & DRM_CONNECTOR_POLL_HPD))
1014 			continue;
1015 
1016 		if (check_connector_changed(connector)) {
1017 			if (!first_changed_connector) {
1018 				drm_connector_get(connector);
1019 				first_changed_connector = connector;
1020 			}
1021 
1022 			changed++;
1023 		}
1024 	}
1025 	drm_connector_list_iter_end(&conn_iter);
1026 	mutex_unlock(&dev->mode_config.mutex);
1027 
1028 	if (changed == 1)
1029 		drm_kms_helper_connector_hotplug_event(first_changed_connector);
1030 	else if (changed > 0)
1031 		drm_kms_helper_hotplug_event(dev);
1032 
1033 	if (first_changed_connector)
1034 		drm_connector_put(first_changed_connector);
1035 
1036 	return changed;
1037 }
1038 EXPORT_SYMBOL(drm_helper_hpd_irq_event);
1039 
1040 /**
1041  * drm_crtc_helper_mode_valid_fixed - Validates a display mode
1042  * @crtc: the crtc
1043  * @mode: the mode to validate
1044  * @fixed_mode: the display hardware's mode
1045  *
1046  * Returns:
1047  * MODE_OK on success, or another mode-status code otherwise.
1048  */
1049 enum drm_mode_status drm_crtc_helper_mode_valid_fixed(struct drm_crtc *crtc,
1050 						      const struct drm_display_mode *mode,
1051 						      const struct drm_display_mode *fixed_mode)
1052 {
1053 	if (mode->hdisplay != fixed_mode->hdisplay && mode->vdisplay != fixed_mode->vdisplay)
1054 		return MODE_ONE_SIZE;
1055 	else if (mode->hdisplay != fixed_mode->hdisplay)
1056 		return MODE_ONE_WIDTH;
1057 	else if (mode->vdisplay != fixed_mode->vdisplay)
1058 		return MODE_ONE_HEIGHT;
1059 
1060 	return MODE_OK;
1061 }
1062 EXPORT_SYMBOL(drm_crtc_helper_mode_valid_fixed);
1063 
1064 /**
1065  * drm_connector_helper_get_modes_from_ddc - Updates the connector's EDID
1066  *                                           property from the connector's
1067  *                                           DDC channel
1068  * @connector: The connector
1069  *
1070  * Returns:
1071  * The number of detected display modes.
1072  *
1073  * Uses a connector's DDC channel to retrieve EDID data and update the
1074  * connector's EDID property and display modes. Drivers can use this
1075  * function to implement struct &drm_connector_helper_funcs.get_modes
1076  * for connectors with a DDC channel.
1077  */
1078 int drm_connector_helper_get_modes_from_ddc(struct drm_connector *connector)
1079 {
1080 	struct edid *edid;
1081 	int count = 0;
1082 
1083 	if (!connector->ddc)
1084 		return 0;
1085 
1086 	edid = drm_get_edid(connector, connector->ddc);
1087 
1088 	// clears property if EDID is NULL
1089 	drm_connector_update_edid_property(connector, edid);
1090 
1091 	if (edid) {
1092 		count = drm_add_edid_modes(connector, edid);
1093 		kfree(edid);
1094 	}
1095 
1096 	return count;
1097 }
1098 EXPORT_SYMBOL(drm_connector_helper_get_modes_from_ddc);
1099 
1100 /**
1101  * drm_connector_helper_get_modes_fixed - Duplicates a display mode for a connector
1102  * @connector: the connector
1103  * @fixed_mode: the display hardware's mode
1104  *
1105  * This function duplicates a display modes for a connector. Drivers for hardware
1106  * that only supports a single fixed mode can use this function in their connector's
1107  * get_modes helper.
1108  *
1109  * Returns:
1110  * The number of created modes.
1111  */
1112 int drm_connector_helper_get_modes_fixed(struct drm_connector *connector,
1113 					 const struct drm_display_mode *fixed_mode)
1114 {
1115 	struct drm_device *dev = connector->dev;
1116 	struct drm_display_mode *mode;
1117 
1118 	mode = drm_mode_duplicate(dev, fixed_mode);
1119 	if (!mode) {
1120 		drm_err(dev, "Failed to duplicate mode " DRM_MODE_FMT "\n",
1121 			DRM_MODE_ARG(fixed_mode));
1122 		return 0;
1123 	}
1124 
1125 	if (mode->name[0] == '\0')
1126 		drm_mode_set_name(mode);
1127 
1128 	mode->type |= DRM_MODE_TYPE_PREFERRED;
1129 	drm_mode_probed_add(connector, mode);
1130 
1131 	if (mode->width_mm)
1132 		connector->display_info.width_mm = mode->width_mm;
1133 	if (mode->height_mm)
1134 		connector->display_info.height_mm = mode->height_mm;
1135 
1136 	return 1;
1137 }
1138 EXPORT_SYMBOL(drm_connector_helper_get_modes_fixed);
1139 
1140 /**
1141  * drm_connector_helper_get_modes - Read EDID and update connector.
1142  * @connector: The connector
1143  *
1144  * Read the EDID using drm_edid_read() (which requires that connector->ddc is
1145  * set), and update the connector using the EDID.
1146  *
1147  * This can be used as the "default" connector helper .get_modes() hook if the
1148  * driver does not need any special processing. This is sets the example what
1149  * custom .get_modes() hooks should do regarding EDID read and connector update.
1150  *
1151  * Returns: Number of modes.
1152  */
1153 int drm_connector_helper_get_modes(struct drm_connector *connector)
1154 {
1155 	const struct drm_edid *drm_edid;
1156 	int count;
1157 
1158 	drm_edid = drm_edid_read(connector);
1159 
1160 	/*
1161 	 * Unconditionally update the connector. If the EDID was read
1162 	 * successfully, fill in the connector information derived from the
1163 	 * EDID. Otherwise, if the EDID is NULL, clear the connector
1164 	 * information.
1165 	 */
1166 	count = drm_edid_connector_update(connector, drm_edid);
1167 
1168 	drm_edid_free(drm_edid);
1169 
1170 	return count;
1171 }
1172 EXPORT_SYMBOL(drm_connector_helper_get_modes);
1173 
1174 /**
1175  * drm_connector_helper_tv_get_modes - Fills the modes availables to a TV connector
1176  * @connector: The connector
1177  *
1178  * Fills the available modes for a TV connector based on the supported
1179  * TV modes, and the default mode expressed by the kernel command line.
1180  *
1181  * This can be used as the default TV connector helper .get_modes() hook
1182  * if the driver does not need any special processing.
1183  *
1184  * Returns:
1185  * The number of modes added to the connector.
1186  */
1187 int drm_connector_helper_tv_get_modes(struct drm_connector *connector)
1188 {
1189 	struct drm_device *dev = connector->dev;
1190 	struct drm_property *tv_mode_property =
1191 		dev->mode_config.tv_mode_property;
1192 	struct drm_cmdline_mode *cmdline = &connector->cmdline_mode;
1193 	unsigned int ntsc_modes = BIT(DRM_MODE_TV_MODE_NTSC) |
1194 		BIT(DRM_MODE_TV_MODE_NTSC_443) |
1195 		BIT(DRM_MODE_TV_MODE_NTSC_J) |
1196 		BIT(DRM_MODE_TV_MODE_PAL_M);
1197 	unsigned int pal_modes = BIT(DRM_MODE_TV_MODE_PAL) |
1198 		BIT(DRM_MODE_TV_MODE_PAL_N) |
1199 		BIT(DRM_MODE_TV_MODE_SECAM);
1200 	unsigned int tv_modes[2] = { UINT_MAX, UINT_MAX };
1201 	unsigned int i, supported_tv_modes = 0;
1202 
1203 	if (!tv_mode_property)
1204 		return 0;
1205 
1206 	for (i = 0; i < tv_mode_property->num_values; i++)
1207 		supported_tv_modes |= BIT(tv_mode_property->values[i]);
1208 
1209 	if ((supported_tv_modes & ntsc_modes) &&
1210 	    (supported_tv_modes & pal_modes)) {
1211 		uint64_t default_mode;
1212 
1213 		if (drm_object_property_get_default_value(&connector->base,
1214 							  tv_mode_property,
1215 							  &default_mode))
1216 			return 0;
1217 
1218 		if (cmdline->tv_mode_specified)
1219 			default_mode = cmdline->tv_mode;
1220 
1221 		if (BIT(default_mode) & ntsc_modes) {
1222 			tv_modes[0] = DRM_MODE_TV_MODE_NTSC;
1223 			tv_modes[1] = DRM_MODE_TV_MODE_PAL;
1224 		} else {
1225 			tv_modes[0] = DRM_MODE_TV_MODE_PAL;
1226 			tv_modes[1] = DRM_MODE_TV_MODE_NTSC;
1227 		}
1228 	} else if (supported_tv_modes & ntsc_modes) {
1229 		tv_modes[0] = DRM_MODE_TV_MODE_NTSC;
1230 	} else if (supported_tv_modes & pal_modes) {
1231 		tv_modes[0] = DRM_MODE_TV_MODE_PAL;
1232 	} else {
1233 		return 0;
1234 	}
1235 
1236 	for (i = 0; i < ARRAY_SIZE(tv_modes); i++) {
1237 		struct drm_display_mode *mode;
1238 
1239 		if (tv_modes[i] == DRM_MODE_TV_MODE_NTSC)
1240 			mode = drm_mode_analog_ntsc_480i(dev);
1241 		else if (tv_modes[i] == DRM_MODE_TV_MODE_PAL)
1242 			mode = drm_mode_analog_pal_576i(dev);
1243 		else
1244 			break;
1245 		if (!mode)
1246 			return i;
1247 		if (!i)
1248 			mode->type |= DRM_MODE_TYPE_PREFERRED;
1249 		drm_mode_probed_add(connector, mode);
1250 	}
1251 
1252 	return i;
1253 }
1254 EXPORT_SYMBOL(drm_connector_helper_tv_get_modes);
1255