Linux Audio

Check our new training course

In-person Linux kernel drivers training

Jun 16-20, 2025
Register
Loading...
Note: File does not exist in v3.1.
    1/*
    2 * Copyright 2015 Advanced Micro Devices, Inc.
    3 *
    4 * Permission is hereby granted, free of charge, to any person obtaining a
    5 * copy of this software and associated documentation files (the "Software"),
    6 * to deal in the Software without restriction, including without limitation
    7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
    8 * and/or sell copies of the Software, and to permit persons to whom the
    9 * Software is furnished to do so, subject to the following conditions:
   10 *
   11 * The above copyright notice and this permission notice shall be included in
   12 * all copies or substantial portions of the Software.
   13 *
   14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
   17 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
   18 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
   19 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
   20 * OTHER DEALINGS IN THE SOFTWARE.
   21 *
   22 * Authors: AMD
   23 *
   24 */
   25
   26/* The caprices of the preprocessor require that this be declared right here */
   27#define CREATE_TRACE_POINTS
   28
   29#include "dm_services_types.h"
   30#include "dc.h"
   31#include "link_enc_cfg.h"
   32#include "dc/inc/core_types.h"
   33#include "dal_asic_id.h"
   34#include "dmub/dmub_srv.h"
   35#include "dc/inc/hw/dmcu.h"
   36#include "dc/inc/hw/abm.h"
   37#include "dc/dc_dmub_srv.h"
   38#include "dc/dc_edid_parser.h"
   39#include "dc/dc_stat.h"
   40#include "dc/dc_state.h"
   41#include "amdgpu_dm_trace.h"
   42#include "dpcd_defs.h"
   43#include "link/protocols/link_dpcd.h"
   44#include "link_service_types.h"
   45#include "link/protocols/link_dp_capability.h"
   46#include "link/protocols/link_ddc.h"
   47
   48#include "vid.h"
   49#include "amdgpu.h"
   50#include "amdgpu_display.h"
   51#include "amdgpu_ucode.h"
   52#include "atom.h"
   53#include "amdgpu_dm.h"
   54#include "amdgpu_dm_plane.h"
   55#include "amdgpu_dm_crtc.h"
   56#include "amdgpu_dm_hdcp.h"
   57#include <drm/display/drm_hdcp_helper.h>
   58#include "amdgpu_dm_wb.h"
   59#include "amdgpu_pm.h"
   60#include "amdgpu_atombios.h"
   61
   62#include "amd_shared.h"
   63#include "amdgpu_dm_irq.h"
   64#include "dm_helpers.h"
   65#include "amdgpu_dm_mst_types.h"
   66#if defined(CONFIG_DEBUG_FS)
   67#include "amdgpu_dm_debugfs.h"
   68#endif
   69#include "amdgpu_dm_psr.h"
   70
   71#include "ivsrcid/ivsrcid_vislands30.h"
   72
   73#include <linux/backlight.h>
   74#include <linux/module.h>
   75#include <linux/moduleparam.h>
   76#include <linux/types.h>
   77#include <linux/pm_runtime.h>
   78#include <linux/pci.h>
   79#include <linux/firmware.h>
   80#include <linux/component.h>
   81#include <linux/dmi.h>
   82
   83#include <drm/display/drm_dp_mst_helper.h>
   84#include <drm/display/drm_hdmi_helper.h>
   85#include <drm/drm_atomic.h>
   86#include <drm/drm_atomic_uapi.h>
   87#include <drm/drm_atomic_helper.h>
   88#include <drm/drm_blend.h>
   89#include <drm/drm_fixed.h>
   90#include <drm/drm_fourcc.h>
   91#include <drm/drm_edid.h>
   92#include <drm/drm_eld.h>
   93#include <drm/drm_vblank.h>
   94#include <drm/drm_audio_component.h>
   95#include <drm/drm_gem_atomic_helper.h>
   96
   97#include <acpi/video.h>
   98
   99#include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
  100
  101#include "dcn/dcn_1_0_offset.h"
  102#include "dcn/dcn_1_0_sh_mask.h"
  103#include "soc15_hw_ip.h"
  104#include "soc15_common.h"
  105#include "vega10_ip_offset.h"
  106
  107#include "gc/gc_11_0_0_offset.h"
  108#include "gc/gc_11_0_0_sh_mask.h"
  109
  110#include "modules/inc/mod_freesync.h"
  111#include "modules/power/power_helpers.h"
  112
  113#define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
  114MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
  115#define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
  116MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
  117#define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
  118MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
  119#define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
  120MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
  121#define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
  122MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
  123#define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
  124MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
  125#define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
  126MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
  127#define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
  128MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
  129#define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
  130MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
  131#define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
  132MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
  133#define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
  134MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
  135
  136#define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
  137MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
  138#define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
  139MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
  140
  141#define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
  142MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
  143
  144#define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
  145MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
  146
  147#define FIRMWARE_DCN_35_DMUB "amdgpu/dcn_3_5_dmcub.bin"
  148MODULE_FIRMWARE(FIRMWARE_DCN_35_DMUB);
  149
  150/* Number of bytes in PSP header for firmware. */
  151#define PSP_HEADER_BYTES 0x100
  152
  153/* Number of bytes in PSP footer for firmware. */
  154#define PSP_FOOTER_BYTES 0x100
  155
  156/**
  157 * DOC: overview
  158 *
  159 * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
  160 * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
  161 * requests into DC requests, and DC responses into DRM responses.
  162 *
  163 * The root control structure is &struct amdgpu_display_manager.
  164 */
  165
  166/* basic init/fini API */
  167static int amdgpu_dm_init(struct amdgpu_device *adev);
  168static void amdgpu_dm_fini(struct amdgpu_device *adev);
  169static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
  170
  171static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
  172{
  173	switch (link->dpcd_caps.dongle_type) {
  174	case DISPLAY_DONGLE_NONE:
  175		return DRM_MODE_SUBCONNECTOR_Native;
  176	case DISPLAY_DONGLE_DP_VGA_CONVERTER:
  177		return DRM_MODE_SUBCONNECTOR_VGA;
  178	case DISPLAY_DONGLE_DP_DVI_CONVERTER:
  179	case DISPLAY_DONGLE_DP_DVI_DONGLE:
  180		return DRM_MODE_SUBCONNECTOR_DVID;
  181	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
  182	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
  183		return DRM_MODE_SUBCONNECTOR_HDMIA;
  184	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
  185	default:
  186		return DRM_MODE_SUBCONNECTOR_Unknown;
  187	}
  188}
  189
  190static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
  191{
  192	struct dc_link *link = aconnector->dc_link;
  193	struct drm_connector *connector = &aconnector->base;
  194	enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
  195
  196	if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
  197		return;
  198
  199	if (aconnector->dc_sink)
  200		subconnector = get_subconnector_type(link);
  201
  202	drm_object_property_set_value(&connector->base,
  203			connector->dev->mode_config.dp_subconnector_property,
  204			subconnector);
  205}
  206
  207/*
  208 * initializes drm_device display related structures, based on the information
  209 * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
  210 * drm_encoder, drm_mode_config
  211 *
  212 * Returns 0 on success
  213 */
  214static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
  215/* removes and deallocates the drm structures, created by the above function */
  216static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
  217
  218static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
  219				    struct amdgpu_dm_connector *amdgpu_dm_connector,
  220				    u32 link_index,
  221				    struct amdgpu_encoder *amdgpu_encoder);
  222static int amdgpu_dm_encoder_init(struct drm_device *dev,
  223				  struct amdgpu_encoder *aencoder,
  224				  uint32_t link_index);
  225
  226static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
  227
  228static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
  229
  230static int amdgpu_dm_atomic_check(struct drm_device *dev,
  231				  struct drm_atomic_state *state);
  232
  233static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
  234static void handle_hpd_rx_irq(void *param);
  235
  236static bool
  237is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
  238				 struct drm_crtc_state *new_crtc_state);
  239/*
  240 * dm_vblank_get_counter
  241 *
  242 * @brief
  243 * Get counter for number of vertical blanks
  244 *
  245 * @param
  246 * struct amdgpu_device *adev - [in] desired amdgpu device
  247 * int disp_idx - [in] which CRTC to get the counter from
  248 *
  249 * @return
  250 * Counter for vertical blanks
  251 */
  252static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
  253{
  254	struct amdgpu_crtc *acrtc = NULL;
  255
  256	if (crtc >= adev->mode_info.num_crtc)
  257		return 0;
  258
  259	acrtc = adev->mode_info.crtcs[crtc];
  260
  261	if (!acrtc->dm_irq_params.stream) {
  262		DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
  263			  crtc);
  264		return 0;
  265	}
  266
  267	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
  268}
  269
  270static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
  271				  u32 *vbl, u32 *position)
  272{
  273	u32 v_blank_start, v_blank_end, h_position, v_position;
  274	struct amdgpu_crtc *acrtc = NULL;
  275	struct dc *dc = adev->dm.dc;
  276
  277	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
  278		return -EINVAL;
  279
  280	acrtc = adev->mode_info.crtcs[crtc];
  281
  282	if (!acrtc->dm_irq_params.stream) {
  283		DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
  284			  crtc);
  285		return 0;
  286	}
  287
  288	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
  289		dc_allow_idle_optimizations(dc, false);
  290
  291	/*
  292	 * TODO rework base driver to use values directly.
  293	 * for now parse it back into reg-format
  294	 */
  295	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
  296				 &v_blank_start,
  297				 &v_blank_end,
  298				 &h_position,
  299				 &v_position);
  300
  301	*position = v_position | (h_position << 16);
  302	*vbl = v_blank_start | (v_blank_end << 16);
  303
  304	return 0;
  305}
  306
  307static bool dm_is_idle(void *handle)
  308{
  309	/* XXX todo */
  310	return true;
  311}
  312
  313static int dm_wait_for_idle(void *handle)
  314{
  315	/* XXX todo */
  316	return 0;
  317}
  318
  319static bool dm_check_soft_reset(void *handle)
  320{
  321	return false;
  322}
  323
  324static int dm_soft_reset(void *handle)
  325{
  326	/* XXX todo */
  327	return 0;
  328}
  329
  330static struct amdgpu_crtc *
  331get_crtc_by_otg_inst(struct amdgpu_device *adev,
  332		     int otg_inst)
  333{
  334	struct drm_device *dev = adev_to_drm(adev);
  335	struct drm_crtc *crtc;
  336	struct amdgpu_crtc *amdgpu_crtc;
  337
  338	if (WARN_ON(otg_inst == -1))
  339		return adev->mode_info.crtcs[0];
  340
  341	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
  342		amdgpu_crtc = to_amdgpu_crtc(crtc);
  343
  344		if (amdgpu_crtc->otg_inst == otg_inst)
  345			return amdgpu_crtc;
  346	}
  347
  348	return NULL;
  349}
  350
  351static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
  352					      struct dm_crtc_state *new_state)
  353{
  354	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
  355		return true;
  356	else if (amdgpu_dm_crtc_vrr_active(old_state) != amdgpu_dm_crtc_vrr_active(new_state))
  357		return true;
  358	else
  359		return false;
  360}
  361
  362static inline void reverse_planes_order(struct dc_surface_update *array_of_surface_update,
  363					int planes_count)
  364{
  365	int i, j;
  366
  367	for (i = 0, j = planes_count - 1; i < j; i++, j--)
  368		swap(array_of_surface_update[i], array_of_surface_update[j]);
  369}
  370
  371/**
  372 * update_planes_and_stream_adapter() - Send planes to be updated in DC
  373 *
  374 * DC has a generic way to update planes and stream via
  375 * dc_update_planes_and_stream function; however, DM might need some
  376 * adjustments and preparation before calling it. This function is a wrapper
  377 * for the dc_update_planes_and_stream that does any required configuration
  378 * before passing control to DC.
  379 *
  380 * @dc: Display Core control structure
  381 * @update_type: specify whether it is FULL/MEDIUM/FAST update
  382 * @planes_count: planes count to update
  383 * @stream: stream state
  384 * @stream_update: stream update
  385 * @array_of_surface_update: dc surface update pointer
  386 *
  387 */
  388static inline bool update_planes_and_stream_adapter(struct dc *dc,
  389						    int update_type,
  390						    int planes_count,
  391						    struct dc_stream_state *stream,
  392						    struct dc_stream_update *stream_update,
  393						    struct dc_surface_update *array_of_surface_update)
  394{
  395	reverse_planes_order(array_of_surface_update, planes_count);
  396
  397	/*
  398	 * Previous frame finished and HW is ready for optimization.
  399	 */
  400	if (update_type == UPDATE_TYPE_FAST)
  401		dc_post_update_surfaces_to_stream(dc);
  402
  403	return dc_update_planes_and_stream(dc,
  404					   array_of_surface_update,
  405					   planes_count,
  406					   stream,
  407					   stream_update);
  408}
  409
  410/**
  411 * dm_pflip_high_irq() - Handle pageflip interrupt
  412 * @interrupt_params: ignored
  413 *
  414 * Handles the pageflip interrupt by notifying all interested parties
  415 * that the pageflip has been completed.
  416 */
  417static void dm_pflip_high_irq(void *interrupt_params)
  418{
  419	struct amdgpu_crtc *amdgpu_crtc;
  420	struct common_irq_params *irq_params = interrupt_params;
  421	struct amdgpu_device *adev = irq_params->adev;
  422	struct drm_device *dev = adev_to_drm(adev);
  423	unsigned long flags;
  424	struct drm_pending_vblank_event *e;
  425	u32 vpos, hpos, v_blank_start, v_blank_end;
  426	bool vrr_active;
  427
  428	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
  429
  430	/* IRQ could occur when in initial stage */
  431	/* TODO work and BO cleanup */
  432	if (amdgpu_crtc == NULL) {
  433		drm_dbg_state(dev, "CRTC is null, returning.\n");
  434		return;
  435	}
  436
  437	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
  438
  439	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED) {
  440		drm_dbg_state(dev,
  441			      "amdgpu_crtc->pflip_status = %d != AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p]\n",
  442			      amdgpu_crtc->pflip_status, AMDGPU_FLIP_SUBMITTED,
  443			      amdgpu_crtc->crtc_id, amdgpu_crtc);
  444		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
  445		return;
  446	}
  447
  448	/* page flip completed. */
  449	e = amdgpu_crtc->event;
  450	amdgpu_crtc->event = NULL;
  451
  452	WARN_ON(!e);
  453
  454	vrr_active = amdgpu_dm_crtc_vrr_active_irq(amdgpu_crtc);
  455
  456	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
  457	if (!vrr_active ||
  458	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
  459				      &v_blank_end, &hpos, &vpos) ||
  460	    (vpos < v_blank_start)) {
  461		/* Update to correct count and vblank timestamp if racing with
  462		 * vblank irq. This also updates to the correct vblank timestamp
  463		 * even in VRR mode, as scanout is past the front-porch atm.
  464		 */
  465		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
  466
  467		/* Wake up userspace by sending the pageflip event with proper
  468		 * count and timestamp of vblank of flip completion.
  469		 */
  470		if (e) {
  471			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
  472
  473			/* Event sent, so done with vblank for this flip */
  474			drm_crtc_vblank_put(&amdgpu_crtc->base);
  475		}
  476	} else if (e) {
  477		/* VRR active and inside front-porch: vblank count and
  478		 * timestamp for pageflip event will only be up to date after
  479		 * drm_crtc_handle_vblank() has been executed from late vblank
  480		 * irq handler after start of back-porch (vline 0). We queue the
  481		 * pageflip event for send-out by drm_crtc_handle_vblank() with
  482		 * updated timestamp and count, once it runs after us.
  483		 *
  484		 * We need to open-code this instead of using the helper
  485		 * drm_crtc_arm_vblank_event(), as that helper would
  486		 * call drm_crtc_accurate_vblank_count(), which we must
  487		 * not call in VRR mode while we are in front-porch!
  488		 */
  489
  490		/* sequence will be replaced by real count during send-out. */
  491		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
  492		e->pipe = amdgpu_crtc->crtc_id;
  493
  494		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
  495		e = NULL;
  496	}
  497
  498	/* Keep track of vblank of this flip for flip throttling. We use the
  499	 * cooked hw counter, as that one incremented at start of this vblank
  500	 * of pageflip completion, so last_flip_vblank is the forbidden count
  501	 * for queueing new pageflips if vsync + VRR is enabled.
  502	 */
  503	amdgpu_crtc->dm_irq_params.last_flip_vblank =
  504		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
  505
  506	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
  507	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
  508
  509	drm_dbg_state(dev,
  510		      "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
  511		      amdgpu_crtc->crtc_id, amdgpu_crtc, vrr_active, (int)!e);
  512}
  513
  514static void dm_vupdate_high_irq(void *interrupt_params)
  515{
  516	struct common_irq_params *irq_params = interrupt_params;
  517	struct amdgpu_device *adev = irq_params->adev;
  518	struct amdgpu_crtc *acrtc;
  519	struct drm_device *drm_dev;
  520	struct drm_vblank_crtc *vblank;
  521	ktime_t frame_duration_ns, previous_timestamp;
  522	unsigned long flags;
  523	int vrr_active;
  524
  525	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
  526
  527	if (acrtc) {
  528		vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
  529		drm_dev = acrtc->base.dev;
  530		vblank = &drm_dev->vblank[acrtc->base.index];
  531		previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
  532		frame_duration_ns = vblank->time - previous_timestamp;
  533
  534		if (frame_duration_ns > 0) {
  535			trace_amdgpu_refresh_rate_track(acrtc->base.index,
  536						frame_duration_ns,
  537						ktime_divns(NSEC_PER_SEC, frame_duration_ns));
  538			atomic64_set(&irq_params->previous_timestamp, vblank->time);
  539		}
  540
  541		drm_dbg_vbl(drm_dev,
  542			    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
  543			    vrr_active);
  544
  545		/* Core vblank handling is done here after end of front-porch in
  546		 * vrr mode, as vblank timestamping will give valid results
  547		 * while now done after front-porch. This will also deliver
  548		 * page-flip completion events that have been queued to us
  549		 * if a pageflip happened inside front-porch.
  550		 */
  551		if (vrr_active) {
  552			amdgpu_dm_crtc_handle_vblank(acrtc);
  553
  554			/* BTR processing for pre-DCE12 ASICs */
  555			if (acrtc->dm_irq_params.stream &&
  556			    adev->family < AMDGPU_FAMILY_AI) {
  557				spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
  558				mod_freesync_handle_v_update(
  559				    adev->dm.freesync_module,
  560				    acrtc->dm_irq_params.stream,
  561				    &acrtc->dm_irq_params.vrr_params);
  562
  563				dc_stream_adjust_vmin_vmax(
  564				    adev->dm.dc,
  565				    acrtc->dm_irq_params.stream,
  566				    &acrtc->dm_irq_params.vrr_params.adjust);
  567				spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
  568			}
  569		}
  570	}
  571}
  572
  573/**
  574 * dm_crtc_high_irq() - Handles CRTC interrupt
  575 * @interrupt_params: used for determining the CRTC instance
  576 *
  577 * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
  578 * event handler.
  579 */
  580static void dm_crtc_high_irq(void *interrupt_params)
  581{
  582	struct common_irq_params *irq_params = interrupt_params;
  583	struct amdgpu_device *adev = irq_params->adev;
  584	struct drm_writeback_job *job;
  585	struct amdgpu_crtc *acrtc;
  586	unsigned long flags;
  587	int vrr_active;
  588
  589	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
  590	if (!acrtc)
  591		return;
  592
  593	if (acrtc->wb_pending) {
  594		if (acrtc->wb_conn) {
  595			spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
  596			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
  597						       struct drm_writeback_job,
  598						       list_entry);
  599			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
  600
  601			if (job) {
  602				unsigned int v_total, refresh_hz;
  603				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
  604
  605				v_total = stream->adjust.v_total_max ?
  606					  stream->adjust.v_total_max : stream->timing.v_total;
  607				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
  608					     100LL, (v_total * stream->timing.h_total));
  609				mdelay(1000 / refresh_hz);
  610
  611				drm_writeback_signal_completion(acrtc->wb_conn, 0);
  612				dc_stream_fc_disable_writeback(adev->dm.dc,
  613							       acrtc->dm_irq_params.stream, 0);
  614			}
  615		} else
  616			DRM_ERROR("%s: no amdgpu_crtc wb_conn\n", __func__);
  617		acrtc->wb_pending = false;
  618	}
  619
  620	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
  621
  622	drm_dbg_vbl(adev_to_drm(adev),
  623		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
  624		    vrr_active, acrtc->dm_irq_params.active_planes);
  625
  626	/**
  627	 * Core vblank handling at start of front-porch is only possible
  628	 * in non-vrr mode, as only there vblank timestamping will give
  629	 * valid results while done in front-porch. Otherwise defer it
  630	 * to dm_vupdate_high_irq after end of front-porch.
  631	 */
  632	if (!vrr_active)
  633		amdgpu_dm_crtc_handle_vblank(acrtc);
  634
  635	/**
  636	 * Following stuff must happen at start of vblank, for crc
  637	 * computation and below-the-range btr support in vrr mode.
  638	 */
  639	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
  640
  641	/* BTR updates need to happen before VUPDATE on Vega and above. */
  642	if (adev->family < AMDGPU_FAMILY_AI)
  643		return;
  644
  645	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
  646
  647	if (acrtc->dm_irq_params.stream &&
  648	    acrtc->dm_irq_params.vrr_params.supported &&
  649	    acrtc->dm_irq_params.freesync_config.state ==
  650		    VRR_STATE_ACTIVE_VARIABLE) {
  651		mod_freesync_handle_v_update(adev->dm.freesync_module,
  652					     acrtc->dm_irq_params.stream,
  653					     &acrtc->dm_irq_params.vrr_params);
  654
  655		dc_stream_adjust_vmin_vmax(adev->dm.dc, acrtc->dm_irq_params.stream,
  656					   &acrtc->dm_irq_params.vrr_params.adjust);
  657	}
  658
  659	/*
  660	 * If there aren't any active_planes then DCH HUBP may be clock-gated.
  661	 * In that case, pageflip completion interrupts won't fire and pageflip
  662	 * completion events won't get delivered. Prevent this by sending
  663	 * pending pageflip events from here if a flip is still pending.
  664	 *
  665	 * If any planes are enabled, use dm_pflip_high_irq() instead, to
  666	 * avoid race conditions between flip programming and completion,
  667	 * which could cause too early flip completion events.
  668	 */
  669	if (adev->family >= AMDGPU_FAMILY_RV &&
  670	    acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
  671	    acrtc->dm_irq_params.active_planes == 0) {
  672		if (acrtc->event) {
  673			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
  674			acrtc->event = NULL;
  675			drm_crtc_vblank_put(&acrtc->base);
  676		}
  677		acrtc->pflip_status = AMDGPU_FLIP_NONE;
  678	}
  679
  680	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
  681}
  682
  683#if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
  684/**
  685 * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
  686 * DCN generation ASICs
  687 * @interrupt_params: interrupt parameters
  688 *
  689 * Used to set crc window/read out crc value at vertical line 0 position
  690 */
  691static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
  692{
  693	struct common_irq_params *irq_params = interrupt_params;
  694	struct amdgpu_device *adev = irq_params->adev;
  695	struct amdgpu_crtc *acrtc;
  696
  697	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
  698
  699	if (!acrtc)
  700		return;
  701
  702	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
  703}
  704#endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
  705
  706/**
  707 * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
  708 * @adev: amdgpu_device pointer
  709 * @notify: dmub notification structure
  710 *
  711 * Dmub AUX or SET_CONFIG command completion processing callback
  712 * Copies dmub notification to DM which is to be read by AUX command.
  713 * issuing thread and also signals the event to wake up the thread.
  714 */
  715static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
  716					struct dmub_notification *notify)
  717{
  718	if (adev->dm.dmub_notify)
  719		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
  720	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
  721		complete(&adev->dm.dmub_aux_transfer_done);
  722}
  723
  724/**
  725 * dmub_hpd_callback - DMUB HPD interrupt processing callback.
  726 * @adev: amdgpu_device pointer
  727 * @notify: dmub notification structure
  728 *
  729 * Dmub Hpd interrupt processing callback. Gets displayindex through the
  730 * ink index and calls helper to do the processing.
  731 */
  732static void dmub_hpd_callback(struct amdgpu_device *adev,
  733			      struct dmub_notification *notify)
  734{
  735	struct amdgpu_dm_connector *aconnector;
  736	struct amdgpu_dm_connector *hpd_aconnector = NULL;
  737	struct drm_connector *connector;
  738	struct drm_connector_list_iter iter;
  739	struct dc_link *link;
  740	u8 link_index = 0;
  741	struct drm_device *dev;
  742
  743	if (adev == NULL)
  744		return;
  745
  746	if (notify == NULL) {
  747		DRM_ERROR("DMUB HPD callback notification was NULL");
  748		return;
  749	}
  750
  751	if (notify->link_index > adev->dm.dc->link_count) {
  752		DRM_ERROR("DMUB HPD index (%u)is abnormal", notify->link_index);
  753		return;
  754	}
  755
  756	link_index = notify->link_index;
  757	link = adev->dm.dc->links[link_index];
  758	dev = adev->dm.ddev;
  759
  760	drm_connector_list_iter_begin(dev, &iter);
  761	drm_for_each_connector_iter(connector, &iter) {
  762
  763		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
  764			continue;
  765
  766		aconnector = to_amdgpu_dm_connector(connector);
  767		if (link && aconnector->dc_link == link) {
  768			if (notify->type == DMUB_NOTIFICATION_HPD)
  769				DRM_INFO("DMUB HPD callback: link_index=%u\n", link_index);
  770			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
  771				DRM_INFO("DMUB HPD IRQ callback: link_index=%u\n", link_index);
  772			else
  773				DRM_WARN("DMUB Unknown HPD callback type %d, link_index=%u\n",
  774						notify->type, link_index);
  775
  776			hpd_aconnector = aconnector;
  777			break;
  778		}
  779	}
  780	drm_connector_list_iter_end(&iter);
  781
  782	if (hpd_aconnector) {
  783		if (notify->type == DMUB_NOTIFICATION_HPD)
  784			handle_hpd_irq_helper(hpd_aconnector);
  785		else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
  786			handle_hpd_rx_irq(hpd_aconnector);
  787	}
  788}
  789
  790/**
  791 * register_dmub_notify_callback - Sets callback for DMUB notify
  792 * @adev: amdgpu_device pointer
  793 * @type: Type of dmub notification
  794 * @callback: Dmub interrupt callback function
  795 * @dmub_int_thread_offload: offload indicator
  796 *
  797 * API to register a dmub callback handler for a dmub notification
  798 * Also sets indicator whether callback processing to be offloaded.
  799 * to dmub interrupt handling thread
  800 * Return: true if successfully registered, false if there is existing registration
  801 */
  802static bool register_dmub_notify_callback(struct amdgpu_device *adev,
  803					  enum dmub_notification_type type,
  804					  dmub_notify_interrupt_callback_t callback,
  805					  bool dmub_int_thread_offload)
  806{
  807	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
  808		adev->dm.dmub_callback[type] = callback;
  809		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
  810	} else
  811		return false;
  812
  813	return true;
  814}
  815
  816static void dm_handle_hpd_work(struct work_struct *work)
  817{
  818	struct dmub_hpd_work *dmub_hpd_wrk;
  819
  820	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
  821
  822	if (!dmub_hpd_wrk->dmub_notify) {
  823		DRM_ERROR("dmub_hpd_wrk dmub_notify is NULL");
  824		return;
  825	}
  826
  827	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
  828		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
  829		dmub_hpd_wrk->dmub_notify);
  830	}
  831
  832	kfree(dmub_hpd_wrk->dmub_notify);
  833	kfree(dmub_hpd_wrk);
  834
  835}
  836
  837#define DMUB_TRACE_MAX_READ 64
  838/**
  839 * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
  840 * @interrupt_params: used for determining the Outbox instance
  841 *
  842 * Handles the Outbox Interrupt
  843 * event handler.
  844 */
  845static void dm_dmub_outbox1_low_irq(void *interrupt_params)
  846{
  847	struct dmub_notification notify;
  848	struct common_irq_params *irq_params = interrupt_params;
  849	struct amdgpu_device *adev = irq_params->adev;
  850	struct amdgpu_display_manager *dm = &adev->dm;
  851	struct dmcub_trace_buf_entry entry = { 0 };
  852	u32 count = 0;
  853	struct dmub_hpd_work *dmub_hpd_wrk;
  854	struct dc_link *plink = NULL;
  855
  856	if (dc_enable_dmub_notifications(adev->dm.dc) &&
  857		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
  858
  859		do {
  860			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
  861			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
  862				DRM_ERROR("DM: notify type %d invalid!", notify.type);
  863				continue;
  864			}
  865			if (!dm->dmub_callback[notify.type]) {
  866				DRM_DEBUG_DRIVER("DMUB notification skipped, no handler: type=%d\n", notify.type);
  867				continue;
  868			}
  869			if (dm->dmub_thread_offload[notify.type] == true) {
  870				dmub_hpd_wrk = kzalloc(sizeof(*dmub_hpd_wrk), GFP_ATOMIC);
  871				if (!dmub_hpd_wrk) {
  872					DRM_ERROR("Failed to allocate dmub_hpd_wrk");
  873					return;
  874				}
  875				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
  876								    GFP_ATOMIC);
  877				if (!dmub_hpd_wrk->dmub_notify) {
  878					kfree(dmub_hpd_wrk);
  879					DRM_ERROR("Failed to allocate dmub_hpd_wrk->dmub_notify");
  880					return;
  881				}
  882				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
  883				dmub_hpd_wrk->adev = adev;
  884				if (notify.type == DMUB_NOTIFICATION_HPD) {
  885					plink = adev->dm.dc->links[notify.link_index];
  886					if (plink) {
  887						plink->hpd_status =
  888							notify.hpd_status == DP_HPD_PLUG;
  889					}
  890				}
  891				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
  892			} else {
  893				dm->dmub_callback[notify.type](adev, &notify);
  894			}
  895		} while (notify.pending_notification);
  896	}
  897
  898
  899	do {
  900		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
  901			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
  902							entry.param0, entry.param1);
  903
  904			DRM_DEBUG_DRIVER("trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
  905				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
  906		} else
  907			break;
  908
  909		count++;
  910
  911	} while (count <= DMUB_TRACE_MAX_READ);
  912
  913	if (count > DMUB_TRACE_MAX_READ)
  914		DRM_DEBUG_DRIVER("Warning : count > DMUB_TRACE_MAX_READ");
  915}
  916
  917static int dm_set_clockgating_state(void *handle,
  918		  enum amd_clockgating_state state)
  919{
  920	return 0;
  921}
  922
  923static int dm_set_powergating_state(void *handle,
  924		  enum amd_powergating_state state)
  925{
  926	return 0;
  927}
  928
  929/* Prototypes of private functions */
  930static int dm_early_init(void *handle);
  931
  932/* Allocate memory for FBC compressed data  */
  933static void amdgpu_dm_fbc_init(struct drm_connector *connector)
  934{
  935	struct amdgpu_device *adev = drm_to_adev(connector->dev);
  936	struct dm_compressor_info *compressor = &adev->dm.compressor;
  937	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
  938	struct drm_display_mode *mode;
  939	unsigned long max_size = 0;
  940
  941	if (adev->dm.dc->fbc_compressor == NULL)
  942		return;
  943
  944	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
  945		return;
  946
  947	if (compressor->bo_ptr)
  948		return;
  949
  950
  951	list_for_each_entry(mode, &connector->modes, head) {
  952		if (max_size < mode->htotal * mode->vtotal)
  953			max_size = mode->htotal * mode->vtotal;
  954	}
  955
  956	if (max_size) {
  957		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
  958			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
  959			    &compressor->gpu_addr, &compressor->cpu_addr);
  960
  961		if (r)
  962			DRM_ERROR("DM: Failed to initialize FBC\n");
  963		else {
  964			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
  965			DRM_INFO("DM: FBC alloc %lu\n", max_size*4);
  966		}
  967
  968	}
  969
  970}
  971
  972static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
  973					  int pipe, bool *enabled,
  974					  unsigned char *buf, int max_bytes)
  975{
  976	struct drm_device *dev = dev_get_drvdata(kdev);
  977	struct amdgpu_device *adev = drm_to_adev(dev);
  978	struct drm_connector *connector;
  979	struct drm_connector_list_iter conn_iter;
  980	struct amdgpu_dm_connector *aconnector;
  981	int ret = 0;
  982
  983	*enabled = false;
  984
  985	mutex_lock(&adev->dm.audio_lock);
  986
  987	drm_connector_list_iter_begin(dev, &conn_iter);
  988	drm_for_each_connector_iter(connector, &conn_iter) {
  989
  990		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
  991			continue;
  992
  993		aconnector = to_amdgpu_dm_connector(connector);
  994		if (aconnector->audio_inst != port)
  995			continue;
  996
  997		*enabled = true;
  998		ret = drm_eld_size(connector->eld);
  999		memcpy(buf, connector->eld, min(max_bytes, ret));
 1000
 1001		break;
 1002	}
 1003	drm_connector_list_iter_end(&conn_iter);
 1004
 1005	mutex_unlock(&adev->dm.audio_lock);
 1006
 1007	DRM_DEBUG_KMS("Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
 1008
 1009	return ret;
 1010}
 1011
 1012static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
 1013	.get_eld = amdgpu_dm_audio_component_get_eld,
 1014};
 1015
 1016static int amdgpu_dm_audio_component_bind(struct device *kdev,
 1017				       struct device *hda_kdev, void *data)
 1018{
 1019	struct drm_device *dev = dev_get_drvdata(kdev);
 1020	struct amdgpu_device *adev = drm_to_adev(dev);
 1021	struct drm_audio_component *acomp = data;
 1022
 1023	acomp->ops = &amdgpu_dm_audio_component_ops;
 1024	acomp->dev = kdev;
 1025	adev->dm.audio_component = acomp;
 1026
 1027	return 0;
 1028}
 1029
 1030static void amdgpu_dm_audio_component_unbind(struct device *kdev,
 1031					  struct device *hda_kdev, void *data)
 1032{
 1033	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
 1034	struct drm_audio_component *acomp = data;
 1035
 1036	acomp->ops = NULL;
 1037	acomp->dev = NULL;
 1038	adev->dm.audio_component = NULL;
 1039}
 1040
 1041static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
 1042	.bind	= amdgpu_dm_audio_component_bind,
 1043	.unbind	= amdgpu_dm_audio_component_unbind,
 1044};
 1045
 1046static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
 1047{
 1048	int i, ret;
 1049
 1050	if (!amdgpu_audio)
 1051		return 0;
 1052
 1053	adev->mode_info.audio.enabled = true;
 1054
 1055	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
 1056
 1057	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
 1058		adev->mode_info.audio.pin[i].channels = -1;
 1059		adev->mode_info.audio.pin[i].rate = -1;
 1060		adev->mode_info.audio.pin[i].bits_per_sample = -1;
 1061		adev->mode_info.audio.pin[i].status_bits = 0;
 1062		adev->mode_info.audio.pin[i].category_code = 0;
 1063		adev->mode_info.audio.pin[i].connected = false;
 1064		adev->mode_info.audio.pin[i].id =
 1065			adev->dm.dc->res_pool->audios[i]->inst;
 1066		adev->mode_info.audio.pin[i].offset = 0;
 1067	}
 1068
 1069	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
 1070	if (ret < 0)
 1071		return ret;
 1072
 1073	adev->dm.audio_registered = true;
 1074
 1075	return 0;
 1076}
 1077
 1078static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
 1079{
 1080	if (!amdgpu_audio)
 1081		return;
 1082
 1083	if (!adev->mode_info.audio.enabled)
 1084		return;
 1085
 1086	if (adev->dm.audio_registered) {
 1087		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
 1088		adev->dm.audio_registered = false;
 1089	}
 1090
 1091	/* TODO: Disable audio? */
 1092
 1093	adev->mode_info.audio.enabled = false;
 1094}
 1095
 1096static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
 1097{
 1098	struct drm_audio_component *acomp = adev->dm.audio_component;
 1099
 1100	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
 1101		DRM_DEBUG_KMS("Notify ELD: %d\n", pin);
 1102
 1103		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
 1104						 pin, -1);
 1105	}
 1106}
 1107
 1108static int dm_dmub_hw_init(struct amdgpu_device *adev)
 1109{
 1110	const struct dmcub_firmware_header_v1_0 *hdr;
 1111	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
 1112	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
 1113	const struct firmware *dmub_fw = adev->dm.dmub_fw;
 1114	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
 1115	struct abm *abm = adev->dm.dc->res_pool->abm;
 1116	struct dc_context *ctx = adev->dm.dc->ctx;
 1117	struct dmub_srv_hw_params hw_params;
 1118	enum dmub_status status;
 1119	const unsigned char *fw_inst_const, *fw_bss_data;
 1120	u32 i, fw_inst_const_size, fw_bss_data_size;
 1121	bool has_hw_support;
 1122
 1123	if (!dmub_srv)
 1124		/* DMUB isn't supported on the ASIC. */
 1125		return 0;
 1126
 1127	if (!fb_info) {
 1128		DRM_ERROR("No framebuffer info for DMUB service.\n");
 1129		return -EINVAL;
 1130	}
 1131
 1132	if (!dmub_fw) {
 1133		/* Firmware required for DMUB support. */
 1134		DRM_ERROR("No firmware provided for DMUB.\n");
 1135		return -EINVAL;
 1136	}
 1137
 1138	/* initialize register offsets for ASICs with runtime initialization available */
 1139	if (dmub_srv->hw_funcs.init_reg_offsets)
 1140		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
 1141
 1142	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
 1143	if (status != DMUB_STATUS_OK) {
 1144		DRM_ERROR("Error checking HW support for DMUB: %d\n", status);
 1145		return -EINVAL;
 1146	}
 1147
 1148	if (!has_hw_support) {
 1149		DRM_INFO("DMUB unsupported on ASIC\n");
 1150		return 0;
 1151	}
 1152
 1153	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
 1154	status = dmub_srv_hw_reset(dmub_srv);
 1155	if (status != DMUB_STATUS_OK)
 1156		DRM_WARN("Error resetting DMUB HW: %d\n", status);
 1157
 1158	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
 1159
 1160	fw_inst_const = dmub_fw->data +
 1161			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
 1162			PSP_HEADER_BYTES;
 1163
 1164	fw_bss_data = dmub_fw->data +
 1165		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
 1166		      le32_to_cpu(hdr->inst_const_bytes);
 1167
 1168	/* Copy firmware and bios info into FB memory. */
 1169	fw_inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
 1170			     PSP_HEADER_BYTES - PSP_FOOTER_BYTES;
 1171
 1172	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
 1173
 1174	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
 1175	 * amdgpu_ucode_init_single_fw will load dmub firmware
 1176	 * fw_inst_const part to cw0; otherwise, the firmware back door load
 1177	 * will be done by dm_dmub_hw_init
 1178	 */
 1179	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
 1180		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
 1181				fw_inst_const_size);
 1182	}
 1183
 1184	if (fw_bss_data_size)
 1185		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
 1186		       fw_bss_data, fw_bss_data_size);
 1187
 1188	/* Copy firmware bios info into FB memory. */
 1189	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
 1190	       adev->bios_size);
 1191
 1192	/* Reset regions that need to be reset. */
 1193	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
 1194	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
 1195
 1196	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
 1197	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
 1198
 1199	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
 1200	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
 1201
 1202	/* Initialize hardware. */
 1203	memset(&hw_params, 0, sizeof(hw_params));
 1204	hw_params.fb_base = adev->gmc.fb_start;
 1205	hw_params.fb_offset = adev->vm_manager.vram_base_offset;
 1206
 1207	/* backdoor load firmware and trigger dmub running */
 1208	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
 1209		hw_params.load_inst_const = true;
 1210
 1211	if (dmcu)
 1212		hw_params.psp_version = dmcu->psp_version;
 1213
 1214	for (i = 0; i < fb_info->num_fb; ++i)
 1215		hw_params.fb[i] = &fb_info->fb[i];
 1216
 1217	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
 1218	case IP_VERSION(3, 1, 3):
 1219	case IP_VERSION(3, 1, 4):
 1220	case IP_VERSION(3, 5, 0):
 1221		hw_params.dpia_supported = true;
 1222		hw_params.disable_dpia = adev->dm.dc->debug.dpia_debug.bits.disable_dpia;
 1223		break;
 1224	default:
 1225		break;
 1226	}
 1227
 1228	status = dmub_srv_hw_init(dmub_srv, &hw_params);
 1229	if (status != DMUB_STATUS_OK) {
 1230		DRM_ERROR("Error initializing DMUB HW: %d\n", status);
 1231		return -EINVAL;
 1232	}
 1233
 1234	/* Wait for firmware load to finish. */
 1235	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
 1236	if (status != DMUB_STATUS_OK)
 1237		DRM_WARN("Wait for DMUB auto-load failed: %d\n", status);
 1238
 1239	/* Init DMCU and ABM if available. */
 1240	if (dmcu && abm) {
 1241		dmcu->funcs->dmcu_init(dmcu);
 1242		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
 1243	}
 1244
 1245	if (!adev->dm.dc->ctx->dmub_srv)
 1246		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
 1247	if (!adev->dm.dc->ctx->dmub_srv) {
 1248		DRM_ERROR("Couldn't allocate DC DMUB server!\n");
 1249		return -ENOMEM;
 1250	}
 1251
 1252	DRM_INFO("DMUB hardware initialized: version=0x%08X\n",
 1253		 adev->dm.dmcub_fw_version);
 1254
 1255	return 0;
 1256}
 1257
 1258static void dm_dmub_hw_resume(struct amdgpu_device *adev)
 1259{
 1260	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
 1261	enum dmub_status status;
 1262	bool init;
 1263
 1264	if (!dmub_srv) {
 1265		/* DMUB isn't supported on the ASIC. */
 1266		return;
 1267	}
 1268
 1269	status = dmub_srv_is_hw_init(dmub_srv, &init);
 1270	if (status != DMUB_STATUS_OK)
 1271		DRM_WARN("DMUB hardware init check failed: %d\n", status);
 1272
 1273	if (status == DMUB_STATUS_OK && init) {
 1274		/* Wait for firmware load to finish. */
 1275		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
 1276		if (status != DMUB_STATUS_OK)
 1277			DRM_WARN("Wait for DMUB auto-load failed: %d\n", status);
 1278	} else {
 1279		/* Perform the full hardware initialization. */
 1280		dm_dmub_hw_init(adev);
 1281	}
 1282}
 1283
 1284static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
 1285{
 1286	u64 pt_base;
 1287	u32 logical_addr_low;
 1288	u32 logical_addr_high;
 1289	u32 agp_base, agp_bot, agp_top;
 1290	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
 1291
 1292	memset(pa_config, 0, sizeof(*pa_config));
 1293
 1294	agp_base = 0;
 1295	agp_bot = adev->gmc.agp_start >> 24;
 1296	agp_top = adev->gmc.agp_end >> 24;
 1297
 1298	/* AGP aperture is disabled */
 1299	if (agp_bot > agp_top) {
 1300		logical_addr_low = adev->gmc.fb_start >> 18;
 1301		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
 1302				       AMD_APU_IS_RENOIR |
 1303				       AMD_APU_IS_GREEN_SARDINE))
 1304			/*
 1305			 * Raven2 has a HW issue that it is unable to use the vram which
 1306			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
 1307			 * workaround that increase system aperture high address (add 1)
 1308			 * to get rid of the VM fault and hardware hang.
 1309			 */
 1310			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
 1311		else
 1312			logical_addr_high = adev->gmc.fb_end >> 18;
 1313	} else {
 1314		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
 1315		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
 1316				       AMD_APU_IS_RENOIR |
 1317				       AMD_APU_IS_GREEN_SARDINE))
 1318			/*
 1319			 * Raven2 has a HW issue that it is unable to use the vram which
 1320			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
 1321			 * workaround that increase system aperture high address (add 1)
 1322			 * to get rid of the VM fault and hardware hang.
 1323			 */
 1324			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
 1325		else
 1326			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
 1327	}
 1328
 1329	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
 1330
 1331	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
 1332						   AMDGPU_GPU_PAGE_SHIFT);
 1333	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
 1334						  AMDGPU_GPU_PAGE_SHIFT);
 1335	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
 1336						 AMDGPU_GPU_PAGE_SHIFT);
 1337	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
 1338						AMDGPU_GPU_PAGE_SHIFT);
 1339	page_table_base.high_part = upper_32_bits(pt_base);
 1340	page_table_base.low_part = lower_32_bits(pt_base);
 1341
 1342	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
 1343	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
 1344
 1345	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
 1346	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
 1347	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
 1348
 1349	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
 1350	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
 1351	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
 1352
 1353	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
 1354	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
 1355	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
 1356
 1357	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
 1358
 1359}
 1360
 1361static void force_connector_state(
 1362	struct amdgpu_dm_connector *aconnector,
 1363	enum drm_connector_force force_state)
 1364{
 1365	struct drm_connector *connector = &aconnector->base;
 1366
 1367	mutex_lock(&connector->dev->mode_config.mutex);
 1368	aconnector->base.force = force_state;
 1369	mutex_unlock(&connector->dev->mode_config.mutex);
 1370
 1371	mutex_lock(&aconnector->hpd_lock);
 1372	drm_kms_helper_connector_hotplug_event(connector);
 1373	mutex_unlock(&aconnector->hpd_lock);
 1374}
 1375
 1376static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
 1377{
 1378	struct hpd_rx_irq_offload_work *offload_work;
 1379	struct amdgpu_dm_connector *aconnector;
 1380	struct dc_link *dc_link;
 1381	struct amdgpu_device *adev;
 1382	enum dc_connection_type new_connection_type = dc_connection_none;
 1383	unsigned long flags;
 1384	union test_response test_response;
 1385
 1386	memset(&test_response, 0, sizeof(test_response));
 1387
 1388	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
 1389	aconnector = offload_work->offload_wq->aconnector;
 1390
 1391	if (!aconnector) {
 1392		DRM_ERROR("Can't retrieve aconnector in hpd_rx_irq_offload_work");
 1393		goto skip;
 1394	}
 1395
 1396	adev = drm_to_adev(aconnector->base.dev);
 1397	dc_link = aconnector->dc_link;
 1398
 1399	mutex_lock(&aconnector->hpd_lock);
 1400	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
 1401		DRM_ERROR("KMS: Failed to detect connector\n");
 1402	mutex_unlock(&aconnector->hpd_lock);
 1403
 1404	if (new_connection_type == dc_connection_none)
 1405		goto skip;
 1406
 1407	if (amdgpu_in_reset(adev))
 1408		goto skip;
 1409
 1410	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
 1411		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
 1412		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
 1413		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
 1414		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
 1415		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
 1416		goto skip;
 1417	}
 1418
 1419	mutex_lock(&adev->dm.dc_lock);
 1420	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
 1421		dc_link_dp_handle_automated_test(dc_link);
 1422
 1423		if (aconnector->timing_changed) {
 1424			/* force connector disconnect and reconnect */
 1425			force_connector_state(aconnector, DRM_FORCE_OFF);
 1426			msleep(100);
 1427			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
 1428		}
 1429
 1430		test_response.bits.ACK = 1;
 1431
 1432		core_link_write_dpcd(
 1433		dc_link,
 1434		DP_TEST_RESPONSE,
 1435		&test_response.raw,
 1436		sizeof(test_response));
 1437	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
 1438			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
 1439			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
 1440		/* offload_work->data is from handle_hpd_rx_irq->
 1441		 * schedule_hpd_rx_offload_work.this is defer handle
 1442		 * for hpd short pulse. upon here, link status may be
 1443		 * changed, need get latest link status from dpcd
 1444		 * registers. if link status is good, skip run link
 1445		 * training again.
 1446		 */
 1447		union hpd_irq_data irq_data;
 1448
 1449		memset(&irq_data, 0, sizeof(irq_data));
 1450
 1451		/* before dc_link_dp_handle_link_loss, allow new link lost handle
 1452		 * request be added to work queue if link lost at end of dc_link_
 1453		 * dp_handle_link_loss
 1454		 */
 1455		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
 1456		offload_work->offload_wq->is_handling_link_loss = false;
 1457		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
 1458
 1459		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
 1460			dc_link_check_link_loss_status(dc_link, &irq_data))
 1461			dc_link_dp_handle_link_loss(dc_link);
 1462	}
 1463	mutex_unlock(&adev->dm.dc_lock);
 1464
 1465skip:
 1466	kfree(offload_work);
 1467
 1468}
 1469
 1470static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct dc *dc)
 1471{
 1472	int max_caps = dc->caps.max_links;
 1473	int i = 0;
 1474	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
 1475
 1476	hpd_rx_offload_wq = kcalloc(max_caps, sizeof(*hpd_rx_offload_wq), GFP_KERNEL);
 1477
 1478	if (!hpd_rx_offload_wq)
 1479		return NULL;
 1480
 1481
 1482	for (i = 0; i < max_caps; i++) {
 1483		hpd_rx_offload_wq[i].wq =
 1484				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
 1485
 1486		if (hpd_rx_offload_wq[i].wq == NULL) {
 1487			DRM_ERROR("create amdgpu_dm_hpd_rx_offload_wq fail!");
 1488			goto out_err;
 1489		}
 1490
 1491		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
 1492	}
 1493
 1494	return hpd_rx_offload_wq;
 1495
 1496out_err:
 1497	for (i = 0; i < max_caps; i++) {
 1498		if (hpd_rx_offload_wq[i].wq)
 1499			destroy_workqueue(hpd_rx_offload_wq[i].wq);
 1500	}
 1501	kfree(hpd_rx_offload_wq);
 1502	return NULL;
 1503}
 1504
 1505struct amdgpu_stutter_quirk {
 1506	u16 chip_vendor;
 1507	u16 chip_device;
 1508	u16 subsys_vendor;
 1509	u16 subsys_device;
 1510	u8 revision;
 1511};
 1512
 1513static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
 1514	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
 1515	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
 1516	{ 0, 0, 0, 0, 0 },
 1517};
 1518
 1519static bool dm_should_disable_stutter(struct pci_dev *pdev)
 1520{
 1521	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
 1522
 1523	while (p && p->chip_device != 0) {
 1524		if (pdev->vendor == p->chip_vendor &&
 1525		    pdev->device == p->chip_device &&
 1526		    pdev->subsystem_vendor == p->subsys_vendor &&
 1527		    pdev->subsystem_device == p->subsys_device &&
 1528		    pdev->revision == p->revision) {
 1529			return true;
 1530		}
 1531		++p;
 1532	}
 1533	return false;
 1534}
 1535
 1536static const struct dmi_system_id hpd_disconnect_quirk_table[] = {
 1537	{
 1538		.matches = {
 1539			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
 1540			DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3660"),
 1541		},
 1542	},
 1543	{
 1544		.matches = {
 1545			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
 1546			DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3260"),
 1547		},
 1548	},
 1549	{
 1550		.matches = {
 1551			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
 1552			DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3460"),
 1553		},
 1554	},
 1555	{
 1556		.matches = {
 1557			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
 1558			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Tower Plus 7010"),
 1559		},
 1560	},
 1561	{
 1562		.matches = {
 1563			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
 1564			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Tower 7010"),
 1565		},
 1566	},
 1567	{
 1568		.matches = {
 1569			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
 1570			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex SFF Plus 7010"),
 1571		},
 1572	},
 1573	{
 1574		.matches = {
 1575			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
 1576			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex SFF 7010"),
 1577		},
 1578	},
 1579	{
 1580		.matches = {
 1581			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
 1582			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Micro Plus 7010"),
 1583		},
 1584	},
 1585	{
 1586		.matches = {
 1587			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
 1588			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Micro 7010"),
 1589		},
 1590	},
 1591	{}
 1592	/* TODO: refactor this from a fixed table to a dynamic option */
 1593};
 1594
 1595static void retrieve_dmi_info(struct amdgpu_display_manager *dm)
 1596{
 1597	const struct dmi_system_id *dmi_id;
 1598
 1599	dm->aux_hpd_discon_quirk = false;
 1600
 1601	dmi_id = dmi_first_match(hpd_disconnect_quirk_table);
 1602	if (dmi_id) {
 1603		dm->aux_hpd_discon_quirk = true;
 1604		DRM_INFO("aux_hpd_discon_quirk attached\n");
 1605	}
 1606}
 1607
 1608static int amdgpu_dm_init(struct amdgpu_device *adev)
 1609{
 1610	struct dc_init_data init_data;
 1611	struct dc_callback_init init_params;
 1612	int r;
 1613
 1614	adev->dm.ddev = adev_to_drm(adev);
 1615	adev->dm.adev = adev;
 1616
 1617	/* Zero all the fields */
 1618	memset(&init_data, 0, sizeof(init_data));
 1619	memset(&init_params, 0, sizeof(init_params));
 1620
 1621	mutex_init(&adev->dm.dpia_aux_lock);
 1622	mutex_init(&adev->dm.dc_lock);
 1623	mutex_init(&adev->dm.audio_lock);
 1624
 1625	if (amdgpu_dm_irq_init(adev)) {
 1626		DRM_ERROR("amdgpu: failed to initialize DM IRQ support.\n");
 1627		goto error;
 1628	}
 1629
 1630	init_data.asic_id.chip_family = adev->family;
 1631
 1632	init_data.asic_id.pci_revision_id = adev->pdev->revision;
 1633	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
 1634	init_data.asic_id.chip_id = adev->pdev->device;
 1635
 1636	init_data.asic_id.vram_width = adev->gmc.vram_width;
 1637	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
 1638	init_data.asic_id.atombios_base_address =
 1639		adev->mode_info.atom_context->bios;
 1640
 1641	init_data.driver = adev;
 1642
 1643	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
 1644
 1645	if (!adev->dm.cgs_device) {
 1646		DRM_ERROR("amdgpu: failed to create cgs device.\n");
 1647		goto error;
 1648	}
 1649
 1650	init_data.cgs_device = adev->dm.cgs_device;
 1651
 1652	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
 1653
 1654	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
 1655	case IP_VERSION(2, 1, 0):
 1656		switch (adev->dm.dmcub_fw_version) {
 1657		case 0: /* development */
 1658		case 0x1: /* linux-firmware.git hash 6d9f399 */
 1659		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
 1660			init_data.flags.disable_dmcu = false;
 1661			break;
 1662		default:
 1663			init_data.flags.disable_dmcu = true;
 1664		}
 1665		break;
 1666	case IP_VERSION(2, 0, 3):
 1667		init_data.flags.disable_dmcu = true;
 1668		break;
 1669	default:
 1670		break;
 1671	}
 1672
 1673	/* APU support S/G display by default except:
 1674	 * ASICs before Carrizo,
 1675	 * RAVEN1 (Users reported stability issue)
 1676	 */
 1677
 1678	if (adev->asic_type < CHIP_CARRIZO) {
 1679		init_data.flags.gpu_vm_support = false;
 1680	} else if (adev->asic_type == CHIP_RAVEN) {
 1681		if (adev->apu_flags & AMD_APU_IS_RAVEN)
 1682			init_data.flags.gpu_vm_support = false;
 1683		else
 1684			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
 1685	} else {
 1686		init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
 1687	}
 1688
 1689	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
 1690
 1691	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
 1692		init_data.flags.fbc_support = true;
 1693
 1694	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
 1695		init_data.flags.multi_mon_pp_mclk_switch = true;
 1696
 1697	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
 1698		init_data.flags.disable_fractional_pwm = true;
 1699
 1700	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
 1701		init_data.flags.edp_no_power_sequencing = true;
 1702
 1703	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
 1704		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
 1705	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
 1706		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
 1707
 1708	init_data.flags.seamless_boot_edp_requested = false;
 1709
 1710	if (amdgpu_device_seamless_boot_supported(adev)) {
 1711		init_data.flags.seamless_boot_edp_requested = true;
 1712		init_data.flags.allow_seamless_boot_optimization = true;
 1713		DRM_INFO("Seamless boot condition check passed\n");
 1714	}
 1715
 1716	init_data.flags.enable_mipi_converter_optimization = true;
 1717
 1718	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
 1719	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
 1720	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
 1721
 1722	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
 1723		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
 1724
 1725	init_data.flags.disable_ips_in_vpb = 1;
 1726
 1727	/* Enable DWB for tested platforms only */
 1728	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
 1729		init_data.num_virtual_links = 1;
 1730
 1731	INIT_LIST_HEAD(&adev->dm.da_list);
 1732
 1733	retrieve_dmi_info(&adev->dm);
 1734
 1735	/* Display Core create. */
 1736	adev->dm.dc = dc_create(&init_data);
 1737
 1738	if (adev->dm.dc) {
 1739		DRM_INFO("Display Core v%s initialized on %s\n", DC_VER,
 1740			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
 1741	} else {
 1742		DRM_INFO("Display Core failed to initialize with v%s!\n", DC_VER);
 1743		goto error;
 1744	}
 1745
 1746	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
 1747		adev->dm.dc->debug.force_single_disp_pipe_split = false;
 1748		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
 1749	}
 1750
 1751	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
 1752		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
 1753	if (dm_should_disable_stutter(adev->pdev))
 1754		adev->dm.dc->debug.disable_stutter = true;
 1755
 1756	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
 1757		adev->dm.dc->debug.disable_stutter = true;
 1758
 1759	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
 1760		adev->dm.dc->debug.disable_dsc = true;
 1761
 1762	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
 1763		adev->dm.dc->debug.disable_clock_gate = true;
 1764
 1765	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
 1766		adev->dm.dc->debug.force_subvp_mclk_switch = true;
 1767
 1768	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
 1769
 1770	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
 1771	adev->dm.dc->debug.ignore_cable_id = true;
 1772
 1773	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
 1774		DRM_INFO("DP-HDMI FRL PCON supported\n");
 1775
 1776	r = dm_dmub_hw_init(adev);
 1777	if (r) {
 1778		DRM_ERROR("DMUB interface failed to initialize: status=%d\n", r);
 1779		goto error;
 1780	}
 1781
 1782	dc_hardware_init(adev->dm.dc);
 1783
 1784	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev->dm.dc);
 1785	if (!adev->dm.hpd_rx_offload_wq) {
 1786		DRM_ERROR("amdgpu: failed to create hpd rx offload workqueue.\n");
 1787		goto error;
 1788	}
 1789
 1790	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
 1791		struct dc_phy_addr_space_config pa_config;
 1792
 1793		mmhub_read_system_context(adev, &pa_config);
 1794
 1795		// Call the DC init_memory func
 1796		dc_setup_system_context(adev->dm.dc, &pa_config);
 1797	}
 1798
 1799	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
 1800	if (!adev->dm.freesync_module) {
 1801		DRM_ERROR(
 1802		"amdgpu: failed to initialize freesync_module.\n");
 1803	} else
 1804		DRM_DEBUG_DRIVER("amdgpu: freesync_module init done %p.\n",
 1805				adev->dm.freesync_module);
 1806
 1807	amdgpu_dm_init_color_mod();
 1808
 1809	if (adev->dm.dc->caps.max_links > 0) {
 1810		adev->dm.vblank_control_workqueue =
 1811			create_singlethread_workqueue("dm_vblank_control_workqueue");
 1812		if (!adev->dm.vblank_control_workqueue)
 1813			DRM_ERROR("amdgpu: failed to initialize vblank_workqueue.\n");
 1814	}
 1815
 1816	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
 1817		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
 1818
 1819		if (!adev->dm.hdcp_workqueue)
 1820			DRM_ERROR("amdgpu: failed to initialize hdcp_workqueue.\n");
 1821		else
 1822			DRM_DEBUG_DRIVER("amdgpu: hdcp_workqueue init done %p.\n", adev->dm.hdcp_workqueue);
 1823
 1824		dc_init_callbacks(adev->dm.dc, &init_params);
 1825	}
 1826	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
 1827		init_completion(&adev->dm.dmub_aux_transfer_done);
 1828		adev->dm.dmub_notify = kzalloc(sizeof(struct dmub_notification), GFP_KERNEL);
 1829		if (!adev->dm.dmub_notify) {
 1830			DRM_INFO("amdgpu: fail to allocate adev->dm.dmub_notify");
 1831			goto error;
 1832		}
 1833
 1834		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
 1835		if (!adev->dm.delayed_hpd_wq) {
 1836			DRM_ERROR("amdgpu: failed to create hpd offload workqueue.\n");
 1837			goto error;
 1838		}
 1839
 1840		amdgpu_dm_outbox_init(adev);
 1841		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
 1842			dmub_aux_setconfig_callback, false)) {
 1843			DRM_ERROR("amdgpu: fail to register dmub aux callback");
 1844			goto error;
 1845		}
 1846		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
 1847		 * It is expected that DMUB will resend any pending notifications at this point. Note
 1848		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
 1849		 * align legacy interface initialization sequence. Connection status will be proactivly
 1850		 * detected once in the amdgpu_dm_initialize_drm_device.
 1851		 */
 1852		dc_enable_dmub_outbox(adev->dm.dc);
 1853
 1854		/* DPIA trace goes to dmesg logs only if outbox is enabled */
 1855		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
 1856			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
 1857	}
 1858
 1859	if (amdgpu_dm_initialize_drm_device(adev)) {
 1860		DRM_ERROR(
 1861		"amdgpu: failed to initialize sw for display support.\n");
 1862		goto error;
 1863	}
 1864
 1865	/* create fake encoders for MST */
 1866	dm_dp_create_fake_mst_encoders(adev);
 1867
 1868	/* TODO: Add_display_info? */
 1869
 1870	/* TODO use dynamic cursor width */
 1871	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
 1872	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
 1873
 1874	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
 1875		DRM_ERROR(
 1876		"amdgpu: failed to initialize sw for display support.\n");
 1877		goto error;
 1878	}
 1879
 1880#if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
 1881	adev->dm.secure_display_ctxs = amdgpu_dm_crtc_secure_display_create_contexts(adev);
 1882	if (!adev->dm.secure_display_ctxs)
 1883		DRM_ERROR("amdgpu: failed to initialize secure display contexts.\n");
 1884#endif
 1885
 1886	DRM_DEBUG_DRIVER("KMS initialized.\n");
 1887
 1888	return 0;
 1889error:
 1890	amdgpu_dm_fini(adev);
 1891
 1892	return -EINVAL;
 1893}
 1894
 1895static int amdgpu_dm_early_fini(void *handle)
 1896{
 1897	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
 1898
 1899	amdgpu_dm_audio_fini(adev);
 1900
 1901	return 0;
 1902}
 1903
 1904static void amdgpu_dm_fini(struct amdgpu_device *adev)
 1905{
 1906	int i;
 1907
 1908	if (adev->dm.vblank_control_workqueue) {
 1909		destroy_workqueue(adev->dm.vblank_control_workqueue);
 1910		adev->dm.vblank_control_workqueue = NULL;
 1911	}
 1912
 1913	amdgpu_dm_destroy_drm_device(&adev->dm);
 1914
 1915#if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
 1916	if (adev->dm.secure_display_ctxs) {
 1917		for (i = 0; i < adev->mode_info.num_crtc; i++) {
 1918			if (adev->dm.secure_display_ctxs[i].crtc) {
 1919				flush_work(&adev->dm.secure_display_ctxs[i].notify_ta_work);
 1920				flush_work(&adev->dm.secure_display_ctxs[i].forward_roi_work);
 1921			}
 1922		}
 1923		kfree(adev->dm.secure_display_ctxs);
 1924		adev->dm.secure_display_ctxs = NULL;
 1925	}
 1926#endif
 1927	if (adev->dm.hdcp_workqueue) {
 1928		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
 1929		adev->dm.hdcp_workqueue = NULL;
 1930	}
 1931
 1932	if (adev->dm.dc)
 1933		dc_deinit_callbacks(adev->dm.dc);
 1934
 1935	if (adev->dm.dc)
 1936		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
 1937
 1938	if (dc_enable_dmub_notifications(adev->dm.dc)) {
 1939		kfree(adev->dm.dmub_notify);
 1940		adev->dm.dmub_notify = NULL;
 1941		destroy_workqueue(adev->dm.delayed_hpd_wq);
 1942		adev->dm.delayed_hpd_wq = NULL;
 1943	}
 1944
 1945	if (adev->dm.dmub_bo)
 1946		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
 1947				      &adev->dm.dmub_bo_gpu_addr,
 1948				      &adev->dm.dmub_bo_cpu_addr);
 1949
 1950	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
 1951		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
 1952			if (adev->dm.hpd_rx_offload_wq[i].wq) {
 1953				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
 1954				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
 1955			}
 1956		}
 1957
 1958		kfree(adev->dm.hpd_rx_offload_wq);
 1959		adev->dm.hpd_rx_offload_wq = NULL;
 1960	}
 1961
 1962	/* DC Destroy TODO: Replace destroy DAL */
 1963	if (adev->dm.dc)
 1964		dc_destroy(&adev->dm.dc);
 1965	/*
 1966	 * TODO: pageflip, vlank interrupt
 1967	 *
 1968	 * amdgpu_dm_irq_fini(adev);
 1969	 */
 1970
 1971	if (adev->dm.cgs_device) {
 1972		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
 1973		adev->dm.cgs_device = NULL;
 1974	}
 1975	if (adev->dm.freesync_module) {
 1976		mod_freesync_destroy(adev->dm.freesync_module);
 1977		adev->dm.freesync_module = NULL;
 1978	}
 1979
 1980	mutex_destroy(&adev->dm.audio_lock);
 1981	mutex_destroy(&adev->dm.dc_lock);
 1982	mutex_destroy(&adev->dm.dpia_aux_lock);
 1983}
 1984
 1985static int load_dmcu_fw(struct amdgpu_device *adev)
 1986{
 1987	const char *fw_name_dmcu = NULL;
 1988	int r;
 1989	const struct dmcu_firmware_header_v1_0 *hdr;
 1990
 1991	switch (adev->asic_type) {
 1992#if defined(CONFIG_DRM_AMD_DC_SI)
 1993	case CHIP_TAHITI:
 1994	case CHIP_PITCAIRN:
 1995	case CHIP_VERDE:
 1996	case CHIP_OLAND:
 1997#endif
 1998	case CHIP_BONAIRE:
 1999	case CHIP_HAWAII:
 2000	case CHIP_KAVERI:
 2001	case CHIP_KABINI:
 2002	case CHIP_MULLINS:
 2003	case CHIP_TONGA:
 2004	case CHIP_FIJI:
 2005	case CHIP_CARRIZO:
 2006	case CHIP_STONEY:
 2007	case CHIP_POLARIS11:
 2008	case CHIP_POLARIS10:
 2009	case CHIP_POLARIS12:
 2010	case CHIP_VEGAM:
 2011	case CHIP_VEGA10:
 2012	case CHIP_VEGA12:
 2013	case CHIP_VEGA20:
 2014		return 0;
 2015	case CHIP_NAVI12:
 2016		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
 2017		break;
 2018	case CHIP_RAVEN:
 2019		if (ASICREV_IS_PICASSO(adev->external_rev_id))
 2020			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
 2021		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
 2022			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
 2023		else
 2024			return 0;
 2025		break;
 2026	default:
 2027		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
 2028		case IP_VERSION(2, 0, 2):
 2029		case IP_VERSION(2, 0, 3):
 2030		case IP_VERSION(2, 0, 0):
 2031		case IP_VERSION(2, 1, 0):
 2032		case IP_VERSION(3, 0, 0):
 2033		case IP_VERSION(3, 0, 2):
 2034		case IP_VERSION(3, 0, 3):
 2035		case IP_VERSION(3, 0, 1):
 2036		case IP_VERSION(3, 1, 2):
 2037		case IP_VERSION(3, 1, 3):
 2038		case IP_VERSION(3, 1, 4):
 2039		case IP_VERSION(3, 1, 5):
 2040		case IP_VERSION(3, 1, 6):
 2041		case IP_VERSION(3, 2, 0):
 2042		case IP_VERSION(3, 2, 1):
 2043		case IP_VERSION(3, 5, 0):
 2044			return 0;
 2045		default:
 2046			break;
 2047		}
 2048		DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
 2049		return -EINVAL;
 2050	}
 2051
 2052	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
 2053		DRM_DEBUG_KMS("dm: DMCU firmware not supported on direct or SMU loading\n");
 2054		return 0;
 2055	}
 2056
 2057	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, fw_name_dmcu);
 2058	if (r == -ENODEV) {
 2059		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
 2060		DRM_DEBUG_KMS("dm: DMCU firmware not found\n");
 2061		adev->dm.fw_dmcu = NULL;
 2062		return 0;
 2063	}
 2064	if (r) {
 2065		dev_err(adev->dev, "amdgpu_dm: Can't validate firmware \"%s\"\n",
 2066			fw_name_dmcu);
 2067		amdgpu_ucode_release(&adev->dm.fw_dmcu);
 2068		return r;
 2069	}
 2070
 2071	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
 2072	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
 2073	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
 2074	adev->firmware.fw_size +=
 2075		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
 2076
 2077	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
 2078	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
 2079	adev->firmware.fw_size +=
 2080		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
 2081
 2082	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
 2083
 2084	DRM_DEBUG_KMS("PSP loading DMCU firmware\n");
 2085
 2086	return 0;
 2087}
 2088
 2089static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
 2090{
 2091	struct amdgpu_device *adev = ctx;
 2092
 2093	return dm_read_reg(adev->dm.dc->ctx, address);
 2094}
 2095
 2096static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
 2097				     uint32_t value)
 2098{
 2099	struct amdgpu_device *adev = ctx;
 2100
 2101	return dm_write_reg(adev->dm.dc->ctx, address, value);
 2102}
 2103
 2104static int dm_dmub_sw_init(struct amdgpu_device *adev)
 2105{
 2106	struct dmub_srv_create_params create_params;
 2107	struct dmub_srv_region_params region_params;
 2108	struct dmub_srv_region_info region_info;
 2109	struct dmub_srv_memory_params memory_params;
 2110	struct dmub_srv_fb_info *fb_info;
 2111	struct dmub_srv *dmub_srv;
 2112	const struct dmcub_firmware_header_v1_0 *hdr;
 2113	enum dmub_asic dmub_asic;
 2114	enum dmub_status status;
 2115	int r;
 2116
 2117	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
 2118	case IP_VERSION(2, 1, 0):
 2119		dmub_asic = DMUB_ASIC_DCN21;
 2120		break;
 2121	case IP_VERSION(3, 0, 0):
 2122		dmub_asic = DMUB_ASIC_DCN30;
 2123		break;
 2124	case IP_VERSION(3, 0, 1):
 2125		dmub_asic = DMUB_ASIC_DCN301;
 2126		break;
 2127	case IP_VERSION(3, 0, 2):
 2128		dmub_asic = DMUB_ASIC_DCN302;
 2129		break;
 2130	case IP_VERSION(3, 0, 3):
 2131		dmub_asic = DMUB_ASIC_DCN303;
 2132		break;
 2133	case IP_VERSION(3, 1, 2):
 2134	case IP_VERSION(3, 1, 3):
 2135		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
 2136		break;
 2137	case IP_VERSION(3, 1, 4):
 2138		dmub_asic = DMUB_ASIC_DCN314;
 2139		break;
 2140	case IP_VERSION(3, 1, 5):
 2141		dmub_asic = DMUB_ASIC_DCN315;
 2142		break;
 2143	case IP_VERSION(3, 1, 6):
 2144		dmub_asic = DMUB_ASIC_DCN316;
 2145		break;
 2146	case IP_VERSION(3, 2, 0):
 2147		dmub_asic = DMUB_ASIC_DCN32;
 2148		break;
 2149	case IP_VERSION(3, 2, 1):
 2150		dmub_asic = DMUB_ASIC_DCN321;
 2151		break;
 2152	case IP_VERSION(3, 5, 0):
 2153		dmub_asic = DMUB_ASIC_DCN35;
 2154		break;
 2155	default:
 2156		/* ASIC doesn't support DMUB. */
 2157		return 0;
 2158	}
 2159
 2160	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
 2161	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
 2162
 2163	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
 2164		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
 2165			AMDGPU_UCODE_ID_DMCUB;
 2166		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
 2167			adev->dm.dmub_fw;
 2168		adev->firmware.fw_size +=
 2169			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
 2170
 2171		DRM_INFO("Loading DMUB firmware via PSP: version=0x%08X\n",
 2172			 adev->dm.dmcub_fw_version);
 2173	}
 2174
 2175
 2176	adev->dm.dmub_srv = kzalloc(sizeof(*adev->dm.dmub_srv), GFP_KERNEL);
 2177	dmub_srv = adev->dm.dmub_srv;
 2178
 2179	if (!dmub_srv) {
 2180		DRM_ERROR("Failed to allocate DMUB service!\n");
 2181		return -ENOMEM;
 2182	}
 2183
 2184	memset(&create_params, 0, sizeof(create_params));
 2185	create_params.user_ctx = adev;
 2186	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
 2187	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
 2188	create_params.asic = dmub_asic;
 2189
 2190	/* Create the DMUB service. */
 2191	status = dmub_srv_create(dmub_srv, &create_params);
 2192	if (status != DMUB_STATUS_OK) {
 2193		DRM_ERROR("Error creating DMUB service: %d\n", status);
 2194		return -EINVAL;
 2195	}
 2196
 2197	/* Calculate the size of all the regions for the DMUB service. */
 2198	memset(&region_params, 0, sizeof(region_params));
 2199
 2200	region_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
 2201					PSP_HEADER_BYTES - PSP_FOOTER_BYTES;
 2202	region_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
 2203	region_params.vbios_size = adev->bios_size;
 2204	region_params.fw_bss_data = region_params.bss_data_size ?
 2205		adev->dm.dmub_fw->data +
 2206		le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
 2207		le32_to_cpu(hdr->inst_const_bytes) : NULL;
 2208	region_params.fw_inst_const =
 2209		adev->dm.dmub_fw->data +
 2210		le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
 2211		PSP_HEADER_BYTES;
 2212	region_params.is_mailbox_in_inbox = false;
 2213
 2214	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
 2215					   &region_info);
 2216
 2217	if (status != DMUB_STATUS_OK) {
 2218		DRM_ERROR("Error calculating DMUB region info: %d\n", status);
 2219		return -EINVAL;
 2220	}
 2221
 2222	/*
 2223	 * Allocate a framebuffer based on the total size of all the regions.
 2224	 * TODO: Move this into GART.
 2225	 */
 2226	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
 2227				    AMDGPU_GEM_DOMAIN_VRAM |
 2228				    AMDGPU_GEM_DOMAIN_GTT,
 2229				    &adev->dm.dmub_bo,
 2230				    &adev->dm.dmub_bo_gpu_addr,
 2231				    &adev->dm.dmub_bo_cpu_addr);
 2232	if (r)
 2233		return r;
 2234
 2235	/* Rebase the regions on the framebuffer address. */
 2236	memset(&memory_params, 0, sizeof(memory_params));
 2237	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
 2238	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
 2239	memory_params.region_info = &region_info;
 2240
 2241	adev->dm.dmub_fb_info =
 2242		kzalloc(sizeof(*adev->dm.dmub_fb_info), GFP_KERNEL);
 2243	fb_info = adev->dm.dmub_fb_info;
 2244
 2245	if (!fb_info) {
 2246		DRM_ERROR(
 2247			"Failed to allocate framebuffer info for DMUB service!\n");
 2248		return -ENOMEM;
 2249	}
 2250
 2251	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
 2252	if (status != DMUB_STATUS_OK) {
 2253		DRM_ERROR("Error calculating DMUB FB info: %d\n", status);
 2254		return -EINVAL;
 2255	}
 2256
 2257	return 0;
 2258}
 2259
 2260static int dm_sw_init(void *handle)
 2261{
 2262	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
 2263	int r;
 2264
 2265	r = dm_dmub_sw_init(adev);
 2266	if (r)
 2267		return r;
 2268
 2269	return load_dmcu_fw(adev);
 2270}
 2271
 2272static int dm_sw_fini(void *handle)
 2273{
 2274	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
 2275
 2276	kfree(adev->dm.dmub_fb_info);
 2277	adev->dm.dmub_fb_info = NULL;
 2278
 2279	if (adev->dm.dmub_srv) {
 2280		dmub_srv_destroy(adev->dm.dmub_srv);
 2281		kfree(adev->dm.dmub_srv);
 2282		adev->dm.dmub_srv = NULL;
 2283	}
 2284
 2285	amdgpu_ucode_release(&adev->dm.dmub_fw);
 2286	amdgpu_ucode_release(&adev->dm.fw_dmcu);
 2287
 2288	return 0;
 2289}
 2290
 2291static int detect_mst_link_for_all_connectors(struct drm_device *dev)
 2292{
 2293	struct amdgpu_dm_connector *aconnector;
 2294	struct drm_connector *connector;
 2295	struct drm_connector_list_iter iter;
 2296	int ret = 0;
 2297
 2298	drm_connector_list_iter_begin(dev, &iter);
 2299	drm_for_each_connector_iter(connector, &iter) {
 2300
 2301		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
 2302			continue;
 2303
 2304		aconnector = to_amdgpu_dm_connector(connector);
 2305		if (aconnector->dc_link->type == dc_connection_mst_branch &&
 2306		    aconnector->mst_mgr.aux) {
 2307			DRM_DEBUG_DRIVER("DM_MST: starting TM on aconnector: %p [id: %d]\n",
 2308					 aconnector,
 2309					 aconnector->base.base.id);
 2310
 2311			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
 2312			if (ret < 0) {
 2313				DRM_ERROR("DM_MST: Failed to start MST\n");
 2314				aconnector->dc_link->type =
 2315					dc_connection_single;
 2316				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
 2317								     aconnector->dc_link);
 2318				break;
 2319			}
 2320		}
 2321	}
 2322	drm_connector_list_iter_end(&iter);
 2323
 2324	return ret;
 2325}
 2326
 2327static int dm_late_init(void *handle)
 2328{
 2329	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
 2330
 2331	struct dmcu_iram_parameters params;
 2332	unsigned int linear_lut[16];
 2333	int i;
 2334	struct dmcu *dmcu = NULL;
 2335
 2336	dmcu = adev->dm.dc->res_pool->dmcu;
 2337
 2338	for (i = 0; i < 16; i++)
 2339		linear_lut[i] = 0xFFFF * i / 15;
 2340
 2341	params.set = 0;
 2342	params.backlight_ramping_override = false;
 2343	params.backlight_ramping_start = 0xCCCC;
 2344	params.backlight_ramping_reduction = 0xCCCCCCCC;
 2345	params.backlight_lut_array_size = 16;
 2346	params.backlight_lut_array = linear_lut;
 2347
 2348	/* Min backlight level after ABM reduction,  Don't allow below 1%
 2349	 * 0xFFFF x 0.01 = 0x28F
 2350	 */
 2351	params.min_abm_backlight = 0x28F;
 2352	/* In the case where abm is implemented on dmcub,
 2353	 * dmcu object will be null.
 2354	 * ABM 2.4 and up are implemented on dmcub.
 2355	 */
 2356	if (dmcu) {
 2357		if (!dmcu_load_iram(dmcu, params))
 2358			return -EINVAL;
 2359	} else if (adev->dm.dc->ctx->dmub_srv) {
 2360		struct dc_link *edp_links[MAX_NUM_EDP];
 2361		int edp_num;
 2362
 2363		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
 2364		for (i = 0; i < edp_num; i++) {
 2365			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
 2366				return -EINVAL;
 2367		}
 2368	}
 2369
 2370	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
 2371}
 2372
 2373static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
 2374{
 2375	int ret;
 2376	u8 guid[16];
 2377	u64 tmp64;
 2378
 2379	mutex_lock(&mgr->lock);
 2380	if (!mgr->mst_primary)
 2381		goto out_fail;
 2382
 2383	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
 2384		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
 2385		goto out_fail;
 2386	}
 2387
 2388	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
 2389				 DP_MST_EN |
 2390				 DP_UP_REQ_EN |
 2391				 DP_UPSTREAM_IS_SRC);
 2392	if (ret < 0) {
 2393		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
 2394		goto out_fail;
 2395	}
 2396
 2397	/* Some hubs forget their guids after they resume */
 2398	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, guid, 16);
 2399	if (ret != 16) {
 2400		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
 2401		goto out_fail;
 2402	}
 2403
 2404	if (memchr_inv(guid, 0, 16) == NULL) {
 2405		tmp64 = get_jiffies_64();
 2406		memcpy(&guid[0], &tmp64, sizeof(u64));
 2407		memcpy(&guid[8], &tmp64, sizeof(u64));
 2408
 2409		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, guid, 16);
 2410
 2411		if (ret != 16) {
 2412			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
 2413			goto out_fail;
 2414		}
 2415	}
 2416
 2417	memcpy(mgr->mst_primary->guid, guid, 16);
 2418
 2419out_fail:
 2420	mutex_unlock(&mgr->lock);
 2421}
 2422
 2423static void s3_handle_mst(struct drm_device *dev, bool suspend)
 2424{
 2425	struct amdgpu_dm_connector *aconnector;
 2426	struct drm_connector *connector;
 2427	struct drm_connector_list_iter iter;
 2428	struct drm_dp_mst_topology_mgr *mgr;
 2429
 2430	drm_connector_list_iter_begin(dev, &iter);
 2431	drm_for_each_connector_iter(connector, &iter) {
 2432
 2433		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
 2434			continue;
 2435
 2436		aconnector = to_amdgpu_dm_connector(connector);
 2437		if (aconnector->dc_link->type != dc_connection_mst_branch ||
 2438		    aconnector->mst_root)
 2439			continue;
 2440
 2441		mgr = &aconnector->mst_mgr;
 2442
 2443		if (suspend) {
 2444			drm_dp_mst_topology_mgr_suspend(mgr);
 2445		} else {
 2446			/* if extended timeout is supported in hardware,
 2447			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
 2448			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
 2449			 */
 2450			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
 2451			if (!dp_is_lttpr_present(aconnector->dc_link))
 2452				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
 2453
 2454			/* TODO: move resume_mst_branch_status() into drm mst resume again
 2455			 * once topology probing work is pulled out from mst resume into mst
 2456			 * resume 2nd step. mst resume 2nd step should be called after old
 2457			 * state getting restored (i.e. drm_atomic_helper_resume()).
 2458			 */
 2459			resume_mst_branch_status(mgr);
 2460		}
 2461	}
 2462	drm_connector_list_iter_end(&iter);
 2463}
 2464
 2465static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
 2466{
 2467	int ret = 0;
 2468
 2469	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
 2470	 * on window driver dc implementation.
 2471	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
 2472	 * should be passed to smu during boot up and resume from s3.
 2473	 * boot up: dc calculate dcn watermark clock settings within dc_create,
 2474	 * dcn20_resource_construct
 2475	 * then call pplib functions below to pass the settings to smu:
 2476	 * smu_set_watermarks_for_clock_ranges
 2477	 * smu_set_watermarks_table
 2478	 * navi10_set_watermarks_table
 2479	 * smu_write_watermarks_table
 2480	 *
 2481	 * For Renoir, clock settings of dcn watermark are also fixed values.
 2482	 * dc has implemented different flow for window driver:
 2483	 * dc_hardware_init / dc_set_power_state
 2484	 * dcn10_init_hw
 2485	 * notify_wm_ranges
 2486	 * set_wm_ranges
 2487	 * -- Linux
 2488	 * smu_set_watermarks_for_clock_ranges
 2489	 * renoir_set_watermarks_table
 2490	 * smu_write_watermarks_table
 2491	 *
 2492	 * For Linux,
 2493	 * dc_hardware_init -> amdgpu_dm_init
 2494	 * dc_set_power_state --> dm_resume
 2495	 *
 2496	 * therefore, this function apply to navi10/12/14 but not Renoir
 2497	 * *
 2498	 */
 2499	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
 2500	case IP_VERSION(2, 0, 2):
 2501	case IP_VERSION(2, 0, 0):
 2502		break;
 2503	default:
 2504		return 0;
 2505	}
 2506
 2507	ret = amdgpu_dpm_write_watermarks_table(adev);
 2508	if (ret) {
 2509		DRM_ERROR("Failed to update WMTABLE!\n");
 2510		return ret;
 2511	}
 2512
 2513	return 0;
 2514}
 2515
 2516/**
 2517 * dm_hw_init() - Initialize DC device
 2518 * @handle: The base driver device containing the amdgpu_dm device.
 2519 *
 2520 * Initialize the &struct amdgpu_display_manager device. This involves calling
 2521 * the initializers of each DM component, then populating the struct with them.
 2522 *
 2523 * Although the function implies hardware initialization, both hardware and
 2524 * software are initialized here. Splitting them out to their relevant init
 2525 * hooks is a future TODO item.
 2526 *
 2527 * Some notable things that are initialized here:
 2528 *
 2529 * - Display Core, both software and hardware
 2530 * - DC modules that we need (freesync and color management)
 2531 * - DRM software states
 2532 * - Interrupt sources and handlers
 2533 * - Vblank support
 2534 * - Debug FS entries, if enabled
 2535 */
 2536static int dm_hw_init(void *handle)
 2537{
 2538	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
 2539	/* Create DAL display manager */
 2540	amdgpu_dm_init(adev);
 2541	amdgpu_dm_hpd_init(adev);
 2542
 2543	return 0;
 2544}
 2545
 2546/**
 2547 * dm_hw_fini() - Teardown DC device
 2548 * @handle: The base driver device containing the amdgpu_dm device.
 2549 *
 2550 * Teardown components within &struct amdgpu_display_manager that require
 2551 * cleanup. This involves cleaning up the DRM device, DC, and any modules that
 2552 * were loaded. Also flush IRQ workqueues and disable them.
 2553 */
 2554static int dm_hw_fini(void *handle)
 2555{
 2556	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
 2557
 2558	amdgpu_dm_hpd_fini(adev);
 2559
 2560	amdgpu_dm_irq_fini(adev);
 2561	amdgpu_dm_fini(adev);
 2562	return 0;
 2563}
 2564
 2565
 2566static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
 2567				 struct dc_state *state, bool enable)
 2568{
 2569	enum dc_irq_source irq_source;
 2570	struct amdgpu_crtc *acrtc;
 2571	int rc = -EBUSY;
 2572	int i = 0;
 2573
 2574	for (i = 0; i < state->stream_count; i++) {
 2575		acrtc = get_crtc_by_otg_inst(
 2576				adev, state->stream_status[i].primary_otg_inst);
 2577
 2578		if (acrtc && state->stream_status[i].plane_count != 0) {
 2579			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
 2580			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
 2581			if (rc)
 2582				DRM_WARN("Failed to %s pflip interrupts\n",
 2583					 enable ? "enable" : "disable");
 2584
 2585			if (enable) {
 2586				if (amdgpu_dm_crtc_vrr_active(to_dm_crtc_state(acrtc->base.state)))
 2587					rc = amdgpu_dm_crtc_set_vupdate_irq(&acrtc->base, true);
 2588			} else
 2589				rc = amdgpu_dm_crtc_set_vupdate_irq(&acrtc->base, false);
 2590
 2591			if (rc)
 2592				DRM_WARN("Failed to %sable vupdate interrupt\n", enable ? "en" : "dis");
 2593
 2594			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
 2595			/* During gpu-reset we disable and then enable vblank irq, so
 2596			 * don't use amdgpu_irq_get/put() to avoid refcount change.
 2597			 */
 2598			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
 2599				DRM_WARN("Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
 2600		}
 2601	}
 2602
 2603}
 2604
 2605static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
 2606{
 2607	struct dc_state *context = NULL;
 2608	enum dc_status res = DC_ERROR_UNEXPECTED;
 2609	int i;
 2610	struct dc_stream_state *del_streams[MAX_PIPES];
 2611	int del_streams_count = 0;
 2612
 2613	memset(del_streams, 0, sizeof(del_streams));
 2614
 2615	context = dc_state_create_current_copy(dc);
 2616	if (context == NULL)
 2617		goto context_alloc_fail;
 2618
 2619	/* First remove from context all streams */
 2620	for (i = 0; i < context->stream_count; i++) {
 2621		struct dc_stream_state *stream = context->streams[i];
 2622
 2623		del_streams[del_streams_count++] = stream;
 2624	}
 2625
 2626	/* Remove all planes for removed streams and then remove the streams */
 2627	for (i = 0; i < del_streams_count; i++) {
 2628		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context)) {
 2629			res = DC_FAIL_DETACH_SURFACES;
 2630			goto fail;
 2631		}
 2632
 2633		res = dc_state_remove_stream(dc, context, del_streams[i]);
 2634		if (res != DC_OK)
 2635			goto fail;
 2636	}
 2637
 2638	res = dc_commit_streams(dc, context->streams, context->stream_count);
 2639
 2640fail:
 2641	dc_state_release(context);
 2642
 2643context_alloc_fail:
 2644	return res;
 2645}
 2646
 2647static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
 2648{
 2649	int i;
 2650
 2651	if (dm->hpd_rx_offload_wq) {
 2652		for (i = 0; i < dm->dc->caps.max_links; i++)
 2653			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
 2654	}
 2655}
 2656
 2657static int dm_suspend(void *handle)
 2658{
 2659	struct amdgpu_device *adev = handle;
 2660	struct amdgpu_display_manager *dm = &adev->dm;
 2661	int ret = 0;
 2662
 2663	if (amdgpu_in_reset(adev)) {
 2664		mutex_lock(&dm->dc_lock);
 2665
 2666		dc_allow_idle_optimizations(adev->dm.dc, false);
 2667
 2668		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
 2669
 2670		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
 2671
 2672		amdgpu_dm_commit_zero_streams(dm->dc);
 2673
 2674		amdgpu_dm_irq_suspend(adev);
 2675
 2676		hpd_rx_irq_work_suspend(dm);
 2677
 2678		return ret;
 2679	}
 2680
 2681	WARN_ON(adev->dm.cached_state);
 2682	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
 2683	if (IS_ERR(adev->dm.cached_state))
 2684		return PTR_ERR(adev->dm.cached_state);
 2685
 2686	s3_handle_mst(adev_to_drm(adev), true);
 2687
 2688	amdgpu_dm_irq_suspend(adev);
 2689
 2690	hpd_rx_irq_work_suspend(dm);
 2691
 2692	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
 2693	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
 2694
 2695	return 0;
 2696}
 2697
 2698struct drm_connector *
 2699amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
 2700					     struct drm_crtc *crtc)
 2701{
 2702	u32 i;
 2703	struct drm_connector_state *new_con_state;
 2704	struct drm_connector *connector;
 2705	struct drm_crtc *crtc_from_state;
 2706
 2707	for_each_new_connector_in_state(state, connector, new_con_state, i) {
 2708		crtc_from_state = new_con_state->crtc;
 2709
 2710		if (crtc_from_state == crtc)
 2711			return connector;
 2712	}
 2713
 2714	return NULL;
 2715}
 2716
 2717static void emulated_link_detect(struct dc_link *link)
 2718{
 2719	struct dc_sink_init_data sink_init_data = { 0 };
 2720	struct display_sink_capability sink_caps = { 0 };
 2721	enum dc_edid_status edid_status;
 2722	struct dc_context *dc_ctx = link->ctx;
 2723	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
 2724	struct dc_sink *sink = NULL;
 2725	struct dc_sink *prev_sink = NULL;
 2726
 2727	link->type = dc_connection_none;
 2728	prev_sink = link->local_sink;
 2729
 2730	if (prev_sink)
 2731		dc_sink_release(prev_sink);
 2732
 2733	switch (link->connector_signal) {
 2734	case SIGNAL_TYPE_HDMI_TYPE_A: {
 2735		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
 2736		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
 2737		break;
 2738	}
 2739
 2740	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
 2741		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
 2742		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
 2743		break;
 2744	}
 2745
 2746	case SIGNAL_TYPE_DVI_DUAL_LINK: {
 2747		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
 2748		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
 2749		break;
 2750	}
 2751
 2752	case SIGNAL_TYPE_LVDS: {
 2753		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
 2754		sink_caps.signal = SIGNAL_TYPE_LVDS;
 2755		break;
 2756	}
 2757
 2758	case SIGNAL_TYPE_EDP: {
 2759		sink_caps.transaction_type =
 2760			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
 2761		sink_caps.signal = SIGNAL_TYPE_EDP;
 2762		break;
 2763	}
 2764
 2765	case SIGNAL_TYPE_DISPLAY_PORT: {
 2766		sink_caps.transaction_type =
 2767			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
 2768		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
 2769		break;
 2770	}
 2771
 2772	default:
 2773		drm_err(dev, "Invalid connector type! signal:%d\n",
 2774			link->connector_signal);
 2775		return;
 2776	}
 2777
 2778	sink_init_data.link = link;
 2779	sink_init_data.sink_signal = sink_caps.signal;
 2780
 2781	sink = dc_sink_create(&sink_init_data);
 2782	if (!sink) {
 2783		drm_err(dev, "Failed to create sink!\n");
 2784		return;
 2785	}
 2786
 2787	/* dc_sink_create returns a new reference */
 2788	link->local_sink = sink;
 2789
 2790	edid_status = dm_helpers_read_local_edid(
 2791			link->ctx,
 2792			link,
 2793			sink);
 2794
 2795	if (edid_status != EDID_OK)
 2796		drm_err(dev, "Failed to read EDID\n");
 2797
 2798}
 2799
 2800static void dm_gpureset_commit_state(struct dc_state *dc_state,
 2801				     struct amdgpu_display_manager *dm)
 2802{
 2803	struct {
 2804		struct dc_surface_update surface_updates[MAX_SURFACES];
 2805		struct dc_plane_info plane_infos[MAX_SURFACES];
 2806		struct dc_scaling_info scaling_infos[MAX_SURFACES];
 2807		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
 2808		struct dc_stream_update stream_update;
 2809	} *bundle;
 2810	int k, m;
 2811
 2812	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
 2813
 2814	if (!bundle) {
 2815		drm_err(dm->ddev, "Failed to allocate update bundle\n");
 2816		goto cleanup;
 2817	}
 2818
 2819	for (k = 0; k < dc_state->stream_count; k++) {
 2820		bundle->stream_update.stream = dc_state->streams[k];
 2821
 2822		for (m = 0; m < dc_state->stream_status->plane_count; m++) {
 2823			bundle->surface_updates[m].surface =
 2824				dc_state->stream_status->plane_states[m];
 2825			bundle->surface_updates[m].surface->force_full_update =
 2826				true;
 2827		}
 2828
 2829		update_planes_and_stream_adapter(dm->dc,
 2830					 UPDATE_TYPE_FULL,
 2831					 dc_state->stream_status->plane_count,
 2832					 dc_state->streams[k],
 2833					 &bundle->stream_update,
 2834					 bundle->surface_updates);
 2835	}
 2836
 2837cleanup:
 2838	kfree(bundle);
 2839}
 2840
 2841static int dm_resume(void *handle)
 2842{
 2843	struct amdgpu_device *adev = handle;
 2844	struct drm_device *ddev = adev_to_drm(adev);
 2845	struct amdgpu_display_manager *dm = &adev->dm;
 2846	struct amdgpu_dm_connector *aconnector;
 2847	struct drm_connector *connector;
 2848	struct drm_connector_list_iter iter;
 2849	struct drm_crtc *crtc;
 2850	struct drm_crtc_state *new_crtc_state;
 2851	struct dm_crtc_state *dm_new_crtc_state;
 2852	struct drm_plane *plane;
 2853	struct drm_plane_state *new_plane_state;
 2854	struct dm_plane_state *dm_new_plane_state;
 2855	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
 2856	enum dc_connection_type new_connection_type = dc_connection_none;
 2857	struct dc_state *dc_state;
 2858	int i, r, j, ret;
 2859	bool need_hotplug = false;
 2860
 2861	if (dm->dc->caps.ips_support) {
 2862		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
 2863	}
 2864
 2865	if (amdgpu_in_reset(adev)) {
 2866		dc_state = dm->cached_dc_state;
 2867
 2868		/*
 2869		 * The dc->current_state is backed up into dm->cached_dc_state
 2870		 * before we commit 0 streams.
 2871		 *
 2872		 * DC will clear link encoder assignments on the real state
 2873		 * but the changes won't propagate over to the copy we made
 2874		 * before the 0 streams commit.
 2875		 *
 2876		 * DC expects that link encoder assignments are *not* valid
 2877		 * when committing a state, so as a workaround we can copy
 2878		 * off of the current state.
 2879		 *
 2880		 * We lose the previous assignments, but we had already
 2881		 * commit 0 streams anyway.
 2882		 */
 2883		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
 2884
 2885		r = dm_dmub_hw_init(adev);
 2886		if (r)
 2887			DRM_ERROR("DMUB interface failed to initialize: status=%d\n", r);
 2888
 2889		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
 2890		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
 2891
 2892		dc_resume(dm->dc);
 2893
 2894		amdgpu_dm_irq_resume_early(adev);
 2895
 2896		for (i = 0; i < dc_state->stream_count; i++) {
 2897			dc_state->streams[i]->mode_changed = true;
 2898			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
 2899				dc_state->stream_status[i].plane_states[j]->update_flags.raw
 2900					= 0xffffffff;
 2901			}
 2902		}
 2903
 2904		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
 2905			amdgpu_dm_outbox_init(adev);
 2906			dc_enable_dmub_outbox(adev->dm.dc);
 2907		}
 2908
 2909		WARN_ON(!dc_commit_streams(dm->dc, dc_state->streams, dc_state->stream_count));
 2910
 2911		dm_gpureset_commit_state(dm->cached_dc_state, dm);
 2912
 2913		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
 2914
 2915		dc_state_release(dm->cached_dc_state);
 2916		dm->cached_dc_state = NULL;
 2917
 2918		amdgpu_dm_irq_resume_late(adev);
 2919
 2920		mutex_unlock(&dm->dc_lock);
 2921
 2922		return 0;
 2923	}
 2924	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
 2925	dc_state_release(dm_state->context);
 2926	dm_state->context = dc_state_create(dm->dc);
 2927	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
 2928
 2929	/* Before powering on DC we need to re-initialize DMUB. */
 2930	dm_dmub_hw_resume(adev);
 2931
 2932	/* Re-enable outbox interrupts for DPIA. */
 2933	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
 2934		amdgpu_dm_outbox_init(adev);
 2935		dc_enable_dmub_outbox(adev->dm.dc);
 2936	}
 2937
 2938	/* power on hardware */
 2939	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
 2940	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
 2941
 2942	/* program HPD filter */
 2943	dc_resume(dm->dc);
 2944
 2945	/*
 2946	 * early enable HPD Rx IRQ, should be done before set mode as short
 2947	 * pulse interrupts are used for MST
 2948	 */
 2949	amdgpu_dm_irq_resume_early(adev);
 2950
 2951	/* On resume we need to rewrite the MSTM control bits to enable MST*/
 2952	s3_handle_mst(ddev, false);
 2953
 2954	/* Do detection*/
 2955	drm_connector_list_iter_begin(ddev, &iter);
 2956	drm_for_each_connector_iter(connector, &iter) {
 2957
 2958		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
 2959			continue;
 2960
 2961		aconnector = to_amdgpu_dm_connector(connector);
 2962
 2963		if (!aconnector->dc_link)
 2964			continue;
 2965
 2966		/*
 2967		 * this is the case when traversing through already created end sink
 2968		 * MST connectors, should be skipped
 2969		 */
 2970		if (aconnector && aconnector->mst_root)
 2971			continue;
 2972
 2973		mutex_lock(&aconnector->hpd_lock);
 2974		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
 2975			DRM_ERROR("KMS: Failed to detect connector\n");
 2976
 2977		if (aconnector->base.force && new_connection_type == dc_connection_none) {
 2978			emulated_link_detect(aconnector->dc_link);
 2979		} else {
 2980			mutex_lock(&dm->dc_lock);
 2981			dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
 2982			mutex_unlock(&dm->dc_lock);
 2983		}
 2984
 2985		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
 2986			aconnector->fake_enable = false;
 2987
 2988		if (aconnector->dc_sink)
 2989			dc_sink_release(aconnector->dc_sink);
 2990		aconnector->dc_sink = NULL;
 2991		amdgpu_dm_update_connector_after_detect(aconnector);
 2992		mutex_unlock(&aconnector->hpd_lock);
 2993	}
 2994	drm_connector_list_iter_end(&iter);
 2995
 2996	/* Force mode set in atomic commit */
 2997	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i)
 2998		new_crtc_state->active_changed = true;
 2999
 3000	/*
 3001	 * atomic_check is expected to create the dc states. We need to release
 3002	 * them here, since they were duplicated as part of the suspend
 3003	 * procedure.
 3004	 */
 3005	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
 3006		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
 3007		if (dm_new_crtc_state->stream) {
 3008			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
 3009			dc_stream_release(dm_new_crtc_state->stream);
 3010			dm_new_crtc_state->stream = NULL;
 3011		}
 3012	}
 3013
 3014	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
 3015		dm_new_plane_state = to_dm_plane_state(new_plane_state);
 3016		if (dm_new_plane_state->dc_state) {
 3017			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
 3018			dc_plane_state_release(dm_new_plane_state->dc_state);
 3019			dm_new_plane_state->dc_state = NULL;
 3020		}
 3021	}
 3022
 3023	drm_atomic_helper_resume(ddev, dm->cached_state);
 3024
 3025	dm->cached_state = NULL;
 3026
 3027	/* Do mst topology probing after resuming cached state*/
 3028	drm_connector_list_iter_begin(ddev, &iter);
 3029	drm_for_each_connector_iter(connector, &iter) {
 3030		aconnector = to_amdgpu_dm_connector(connector);
 3031		if (aconnector->dc_link->type != dc_connection_mst_branch ||
 3032		    aconnector->mst_root)
 3033			continue;
 3034
 3035		ret = drm_dp_mst_topology_mgr_resume(&aconnector->mst_mgr, true);
 3036
 3037		if (ret < 0) {
 3038			dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
 3039					aconnector->dc_link);
 3040			need_hotplug = true;
 3041		}
 3042	}
 3043	drm_connector_list_iter_end(&iter);
 3044
 3045	if (need_hotplug)
 3046		drm_kms_helper_hotplug_event(ddev);
 3047
 3048	amdgpu_dm_irq_resume_late(adev);
 3049
 3050	amdgpu_dm_smu_write_watermarks_table(adev);
 3051
 3052	return 0;
 3053}
 3054
 3055/**
 3056 * DOC: DM Lifecycle
 3057 *
 3058 * DM (and consequently DC) is registered in the amdgpu base driver as a IP
 3059 * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
 3060 * the base driver's device list to be initialized and torn down accordingly.
 3061 *
 3062 * The functions to do so are provided as hooks in &struct amd_ip_funcs.
 3063 */
 3064
 3065static const struct amd_ip_funcs amdgpu_dm_funcs = {
 3066	.name = "dm",
 3067	.early_init = dm_early_init,
 3068	.late_init = dm_late_init,
 3069	.sw_init = dm_sw_init,
 3070	.sw_fini = dm_sw_fini,
 3071	.early_fini = amdgpu_dm_early_fini,
 3072	.hw_init = dm_hw_init,
 3073	.hw_fini = dm_hw_fini,
 3074	.suspend = dm_suspend,
 3075	.resume = dm_resume,
 3076	.is_idle = dm_is_idle,
 3077	.wait_for_idle = dm_wait_for_idle,
 3078	.check_soft_reset = dm_check_soft_reset,
 3079	.soft_reset = dm_soft_reset,
 3080	.set_clockgating_state = dm_set_clockgating_state,
 3081	.set_powergating_state = dm_set_powergating_state,
 3082};
 3083
 3084const struct amdgpu_ip_block_version dm_ip_block = {
 3085	.type = AMD_IP_BLOCK_TYPE_DCE,
 3086	.major = 1,
 3087	.minor = 0,
 3088	.rev = 0,
 3089	.funcs = &amdgpu_dm_funcs,
 3090};
 3091
 3092
 3093/**
 3094 * DOC: atomic
 3095 *
 3096 * *WIP*
 3097 */
 3098
 3099static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
 3100	.fb_create = amdgpu_display_user_framebuffer_create,
 3101	.get_format_info = amdgpu_dm_plane_get_format_info,
 3102	.atomic_check = amdgpu_dm_atomic_check,
 3103	.atomic_commit = drm_atomic_helper_commit,
 3104};
 3105
 3106static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
 3107	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
 3108	.atomic_commit_setup = drm_dp_mst_atomic_setup_commit,
 3109};
 3110
 3111static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
 3112{
 3113	struct amdgpu_dm_backlight_caps *caps;
 3114	struct drm_connector *conn_base;
 3115	struct amdgpu_device *adev;
 3116	struct drm_luminance_range_info *luminance_range;
 3117
 3118	if (aconnector->bl_idx == -1 ||
 3119	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
 3120		return;
 3121
 3122	conn_base = &aconnector->base;
 3123	adev = drm_to_adev(conn_base->dev);
 3124
 3125	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
 3126	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
 3127	caps->aux_support = false;
 3128
 3129	if (caps->ext_caps->bits.oled == 1
 3130	    /*
 3131	     * ||
 3132	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
 3133	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
 3134	     */)
 3135		caps->aux_support = true;
 3136
 3137	if (amdgpu_backlight == 0)
 3138		caps->aux_support = false;
 3139	else if (amdgpu_backlight == 1)
 3140		caps->aux_support = true;
 3141
 3142	luminance_range = &conn_base->display_info.luminance_range;
 3143
 3144	if (luminance_range->max_luminance) {
 3145		caps->aux_min_input_signal = luminance_range->min_luminance;
 3146		caps->aux_max_input_signal = luminance_range->max_luminance;
 3147	} else {
 3148		caps->aux_min_input_signal = 0;
 3149		caps->aux_max_input_signal = 512;
 3150	}
 3151}
 3152
 3153void amdgpu_dm_update_connector_after_detect(
 3154		struct amdgpu_dm_connector *aconnector)
 3155{
 3156	struct drm_connector *connector = &aconnector->base;
 3157	struct drm_device *dev = connector->dev;
 3158	struct dc_sink *sink;
 3159
 3160	/* MST handled by drm_mst framework */
 3161	if (aconnector->mst_mgr.mst_state == true)
 3162		return;
 3163
 3164	sink = aconnector->dc_link->local_sink;
 3165	if (sink)
 3166		dc_sink_retain(sink);
 3167
 3168	/*
 3169	 * Edid mgmt connector gets first update only in mode_valid hook and then
 3170	 * the connector sink is set to either fake or physical sink depends on link status.
 3171	 * Skip if already done during boot.
 3172	 */
 3173	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
 3174			&& aconnector->dc_em_sink) {
 3175
 3176		/*
 3177		 * For S3 resume with headless use eml_sink to fake stream
 3178		 * because on resume connector->sink is set to NULL
 3179		 */
 3180		mutex_lock(&dev->mode_config.mutex);
 3181
 3182		if (sink) {
 3183			if (aconnector->dc_sink) {
 3184				amdgpu_dm_update_freesync_caps(connector, NULL);
 3185				/*
 3186				 * retain and release below are used to
 3187				 * bump up refcount for sink because the link doesn't point
 3188				 * to it anymore after disconnect, so on next crtc to connector
 3189				 * reshuffle by UMD we will get into unwanted dc_sink release
 3190				 */
 3191				dc_sink_release(aconnector->dc_sink);
 3192			}
 3193			aconnector->dc_sink = sink;
 3194			dc_sink_retain(aconnector->dc_sink);
 3195			amdgpu_dm_update_freesync_caps(connector,
 3196					aconnector->edid);
 3197		} else {
 3198			amdgpu_dm_update_freesync_caps(connector, NULL);
 3199			if (!aconnector->dc_sink) {
 3200				aconnector->dc_sink = aconnector->dc_em_sink;
 3201				dc_sink_retain(aconnector->dc_sink);
 3202			}
 3203		}
 3204
 3205		mutex_unlock(&dev->mode_config.mutex);
 3206
 3207		if (sink)
 3208			dc_sink_release(sink);
 3209		return;
 3210	}
 3211
 3212	/*
 3213	 * TODO: temporary guard to look for proper fix
 3214	 * if this sink is MST sink, we should not do anything
 3215	 */
 3216	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
 3217		dc_sink_release(sink);
 3218		return;
 3219	}
 3220
 3221	if (aconnector->dc_sink == sink) {
 3222		/*
 3223		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
 3224		 * Do nothing!!
 3225		 */
 3226		DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
 3227				aconnector->connector_id);
 3228		if (sink)
 3229			dc_sink_release(sink);
 3230		return;
 3231	}
 3232
 3233	DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
 3234		aconnector->connector_id, aconnector->dc_sink, sink);
 3235
 3236	mutex_lock(&dev->mode_config.mutex);
 3237
 3238	/*
 3239	 * 1. Update status of the drm connector
 3240	 * 2. Send an event and let userspace tell us what to do
 3241	 */
 3242	if (sink) {
 3243		/*
 3244		 * TODO: check if we still need the S3 mode update workaround.
 3245		 * If yes, put it here.
 3246		 */
 3247		if (aconnector->dc_sink) {
 3248			amdgpu_dm_update_freesync_caps(connector, NULL);
 3249			dc_sink_release(aconnector->dc_sink);
 3250		}
 3251
 3252		aconnector->dc_sink = sink;
 3253		dc_sink_retain(aconnector->dc_sink);
 3254		if (sink->dc_edid.length == 0) {
 3255			aconnector->edid = NULL;
 3256			if (aconnector->dc_link->aux_mode) {
 3257				drm_dp_cec_unset_edid(
 3258					&aconnector->dm_dp_aux.aux);
 3259			}
 3260		} else {
 3261			aconnector->edid =
 3262				(struct edid *)sink->dc_edid.raw_edid;
 3263
 3264			if (aconnector->dc_link->aux_mode)
 3265				drm_dp_cec_set_edid(&aconnector->dm_dp_aux.aux,
 3266						    aconnector->edid);
 3267		}
 3268
 3269		if (!aconnector->timing_requested) {
 3270			aconnector->timing_requested =
 3271				kzalloc(sizeof(struct dc_crtc_timing), GFP_KERNEL);
 3272			if (!aconnector->timing_requested)
 3273				drm_err(dev,
 3274					"failed to create aconnector->requested_timing\n");
 3275		}
 3276
 3277		drm_connector_update_edid_property(connector, aconnector->edid);
 3278		amdgpu_dm_update_freesync_caps(connector, aconnector->edid);
 3279		update_connector_ext_caps(aconnector);
 3280	} else {
 3281		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
 3282		amdgpu_dm_update_freesync_caps(connector, NULL);
 3283		drm_connector_update_edid_property(connector, NULL);
 3284		aconnector->num_modes = 0;
 3285		dc_sink_release(aconnector->dc_sink);
 3286		aconnector->dc_sink = NULL;
 3287		aconnector->edid = NULL;
 3288		kfree(aconnector->timing_requested);
 3289		aconnector->timing_requested = NULL;
 3290		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
 3291		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
 3292			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
 3293	}
 3294
 3295	mutex_unlock(&dev->mode_config.mutex);
 3296
 3297	update_subconnector_property(aconnector);
 3298
 3299	if (sink)
 3300		dc_sink_release(sink);
 3301}
 3302
 3303static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
 3304{
 3305	struct drm_connector *connector = &aconnector->base;
 3306	struct drm_device *dev = connector->dev;
 3307	enum dc_connection_type new_connection_type = dc_connection_none;
 3308	struct amdgpu_device *adev = drm_to_adev(dev);
 3309	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
 3310	bool ret = false;
 3311
 3312	if (adev->dm.disable_hpd_irq)
 3313		return;
 3314
 3315	/*
 3316	 * In case of failure or MST no need to update connector status or notify the OS
 3317	 * since (for MST case) MST does this in its own context.
 3318	 */
 3319	mutex_lock(&aconnector->hpd_lock);
 3320
 3321	if (adev->dm.hdcp_workqueue) {
 3322		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
 3323		dm_con_state->update_hdcp = true;
 3324	}
 3325	if (aconnector->fake_enable)
 3326		aconnector->fake_enable = false;
 3327
 3328	aconnector->timing_changed = false;
 3329
 3330	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
 3331		DRM_ERROR("KMS: Failed to detect connector\n");
 3332
 3333	if (aconnector->base.force && new_connection_type == dc_connection_none) {
 3334		emulated_link_detect(aconnector->dc_link);
 3335
 3336		drm_modeset_lock_all(dev);
 3337		dm_restore_drm_connector_state(dev, connector);
 3338		drm_modeset_unlock_all(dev);
 3339
 3340		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
 3341			drm_kms_helper_connector_hotplug_event(connector);
 3342	} else {
 3343		mutex_lock(&adev->dm.dc_lock);
 3344		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
 3345		mutex_unlock(&adev->dm.dc_lock);
 3346		if (ret) {
 3347			amdgpu_dm_update_connector_after_detect(aconnector);
 3348
 3349			drm_modeset_lock_all(dev);
 3350			dm_restore_drm_connector_state(dev, connector);
 3351			drm_modeset_unlock_all(dev);
 3352
 3353			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
 3354				drm_kms_helper_connector_hotplug_event(connector);
 3355		}
 3356	}
 3357	mutex_unlock(&aconnector->hpd_lock);
 3358
 3359}
 3360
 3361static void handle_hpd_irq(void *param)
 3362{
 3363	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
 3364
 3365	handle_hpd_irq_helper(aconnector);
 3366
 3367}
 3368
 3369static void schedule_hpd_rx_offload_work(struct hpd_rx_irq_offload_work_queue *offload_wq,
 3370							union hpd_irq_data hpd_irq_data)
 3371{
 3372	struct hpd_rx_irq_offload_work *offload_work =
 3373				kzalloc(sizeof(*offload_work), GFP_KERNEL);
 3374
 3375	if (!offload_work) {
 3376		DRM_ERROR("Failed to allocate hpd_rx_irq_offload_work.\n");
 3377		return;
 3378	}
 3379
 3380	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
 3381	offload_work->data = hpd_irq_data;
 3382	offload_work->offload_wq = offload_wq;
 3383
 3384	queue_work(offload_wq->wq, &offload_work->work);
 3385	DRM_DEBUG_KMS("queue work to handle hpd_rx offload work");
 3386}
 3387
 3388static void handle_hpd_rx_irq(void *param)
 3389{
 3390	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
 3391	struct drm_connector *connector = &aconnector->base;
 3392	struct drm_device *dev = connector->dev;
 3393	struct dc_link *dc_link = aconnector->dc_link;
 3394	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
 3395	bool result = false;
 3396	enum dc_connection_type new_connection_type = dc_connection_none;
 3397	struct amdgpu_device *adev = drm_to_adev(dev);
 3398	union hpd_irq_data hpd_irq_data;
 3399	bool link_loss = false;
 3400	bool has_left_work = false;
 3401	int idx = dc_link->link_index;
 3402	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
 3403
 3404	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
 3405
 3406	if (adev->dm.disable_hpd_irq)
 3407		return;
 3408
 3409	/*
 3410	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
 3411	 * conflict, after implement i2c helper, this mutex should be
 3412	 * retired.
 3413	 */
 3414	mutex_lock(&aconnector->hpd_lock);
 3415
 3416	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
 3417						&link_loss, true, &has_left_work);
 3418
 3419	if (!has_left_work)
 3420		goto out;
 3421
 3422	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
 3423		schedule_hpd_rx_offload_work(offload_wq, hpd_irq_data);
 3424		goto out;
 3425	}
 3426
 3427	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
 3428		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
 3429			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
 3430			bool skip = false;
 3431
 3432			/*
 3433			 * DOWN_REP_MSG_RDY is also handled by polling method
 3434			 * mgr->cbs->poll_hpd_irq()
 3435			 */
 3436			spin_lock(&offload_wq->offload_lock);
 3437			skip = offload_wq->is_handling_mst_msg_rdy_event;
 3438
 3439			if (!skip)
 3440				offload_wq->is_handling_mst_msg_rdy_event = true;
 3441
 3442			spin_unlock(&offload_wq->offload_lock);
 3443
 3444			if (!skip)
 3445				schedule_hpd_rx_offload_work(offload_wq, hpd_irq_data);
 3446
 3447			goto out;
 3448		}
 3449
 3450		if (link_loss) {
 3451			bool skip = false;
 3452
 3453			spin_lock(&offload_wq->offload_lock);
 3454			skip = offload_wq->is_handling_link_loss;
 3455
 3456			if (!skip)
 3457				offload_wq->is_handling_link_loss = true;
 3458
 3459			spin_unlock(&offload_wq->offload_lock);
 3460
 3461			if (!skip)
 3462				schedule_hpd_rx_offload_work(offload_wq, hpd_irq_data);
 3463
 3464			goto out;
 3465		}
 3466	}
 3467
 3468out:
 3469	if (result && !is_mst_root_connector) {
 3470		/* Downstream Port status changed. */
 3471		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
 3472			DRM_ERROR("KMS: Failed to detect connector\n");
 3473
 3474		if (aconnector->base.force && new_connection_type == dc_connection_none) {
 3475			emulated_link_detect(dc_link);
 3476
 3477			if (aconnector->fake_enable)
 3478				aconnector->fake_enable = false;
 3479
 3480			amdgpu_dm_update_connector_after_detect(aconnector);
 3481
 3482
 3483			drm_modeset_lock_all(dev);
 3484			dm_restore_drm_connector_state(dev, connector);
 3485			drm_modeset_unlock_all(dev);
 3486
 3487			drm_kms_helper_connector_hotplug_event(connector);
 3488		} else {
 3489			bool ret = false;
 3490
 3491			mutex_lock(&adev->dm.dc_lock);
 3492			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
 3493			mutex_unlock(&adev->dm.dc_lock);
 3494
 3495			if (ret) {
 3496				if (aconnector->fake_enable)
 3497					aconnector->fake_enable = false;
 3498
 3499				amdgpu_dm_update_connector_after_detect(aconnector);
 3500
 3501				drm_modeset_lock_all(dev);
 3502				dm_restore_drm_connector_state(dev, connector);
 3503				drm_modeset_unlock_all(dev);
 3504
 3505				drm_kms_helper_connector_hotplug_event(connector);
 3506			}
 3507		}
 3508	}
 3509	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
 3510		if (adev->dm.hdcp_workqueue)
 3511			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
 3512	}
 3513
 3514	if (dc_link->type != dc_connection_mst_branch)
 3515		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
 3516
 3517	mutex_unlock(&aconnector->hpd_lock);
 3518}
 3519
 3520static void register_hpd_handlers(struct amdgpu_device *adev)
 3521{
 3522	struct drm_device *dev = adev_to_drm(adev);
 3523	struct drm_connector *connector;
 3524	struct amdgpu_dm_connector *aconnector;
 3525	const struct dc_link *dc_link;
 3526	struct dc_interrupt_params int_params = {0};
 3527
 3528	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
 3529	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
 3530
 3531	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
 3532		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD, dmub_hpd_callback, true))
 3533			DRM_ERROR("amdgpu: fail to register dmub hpd callback");
 3534
 3535		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ, dmub_hpd_callback, true))
 3536			DRM_ERROR("amdgpu: fail to register dmub hpd callback");
 3537	}
 3538
 3539	list_for_each_entry(connector,
 3540			&dev->mode_config.connector_list, head)	{
 3541
 3542		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
 3543			continue;
 3544
 3545		aconnector = to_amdgpu_dm_connector(connector);
 3546		dc_link = aconnector->dc_link;
 3547
 3548		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
 3549			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
 3550			int_params.irq_source = dc_link->irq_source_hpd;
 3551
 3552			amdgpu_dm_irq_register_interrupt(adev, &int_params,
 3553					handle_hpd_irq,
 3554					(void *) aconnector);
 3555		}
 3556
 3557		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
 3558
 3559			/* Also register for DP short pulse (hpd_rx). */
 3560			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
 3561			int_params.irq_source =	dc_link->irq_source_hpd_rx;
 3562
 3563			amdgpu_dm_irq_register_interrupt(adev, &int_params,
 3564					handle_hpd_rx_irq,
 3565					(void *) aconnector);
 3566		}
 3567	}
 3568}
 3569
 3570#if defined(CONFIG_DRM_AMD_DC_SI)
 3571/* Register IRQ sources and initialize IRQ callbacks */
 3572static int dce60_register_irq_handlers(struct amdgpu_device *adev)
 3573{
 3574	struct dc *dc = adev->dm.dc;
 3575	struct common_irq_params *c_irq_params;
 3576	struct dc_interrupt_params int_params = {0};
 3577	int r;
 3578	int i;
 3579	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
 3580
 3581	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
 3582	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
 3583
 3584	/*
 3585	 * Actions of amdgpu_irq_add_id():
 3586	 * 1. Register a set() function with base driver.
 3587	 *    Base driver will call set() function to enable/disable an
 3588	 *    interrupt in DC hardware.
 3589	 * 2. Register amdgpu_dm_irq_handler().
 3590	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
 3591	 *    coming from DC hardware.
 3592	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
 3593	 *    for acknowledging and handling.
 3594	 */
 3595
 3596	/* Use VBLANK interrupt */
 3597	for (i = 0; i < adev->mode_info.num_crtc; i++) {
 3598		r = amdgpu_irq_add_id(adev, client_id, i + 1, &adev->crtc_irq);
 3599		if (r) {
 3600			DRM_ERROR("Failed to add crtc irq id!\n");
 3601			return r;
 3602		}
 3603
 3604		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
 3605		int_params.irq_source =
 3606			dc_interrupt_to_irq_source(dc, i + 1, 0);
 3607
 3608		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
 3609
 3610		c_irq_params->adev = adev;
 3611		c_irq_params->irq_src = int_params.irq_source;
 3612
 3613		amdgpu_dm_irq_register_interrupt(adev, &int_params,
 3614				dm_crtc_high_irq, c_irq_params);
 3615	}
 3616
 3617	/* Use GRPH_PFLIP interrupt */
 3618	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
 3619			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
 3620		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
 3621		if (r) {
 3622			DRM_ERROR("Failed to add page flip irq id!\n");
 3623			return r;
 3624		}
 3625
 3626		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
 3627		int_params.irq_source =
 3628			dc_interrupt_to_irq_source(dc, i, 0);
 3629
 3630		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
 3631
 3632		c_irq_params->adev = adev;
 3633		c_irq_params->irq_src = int_params.irq_source;
 3634
 3635		amdgpu_dm_irq_register_interrupt(adev, &int_params,
 3636				dm_pflip_high_irq, c_irq_params);
 3637
 3638	}
 3639
 3640	/* HPD */
 3641	r = amdgpu_irq_add_id(adev, client_id,
 3642			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
 3643	if (r) {
 3644		DRM_ERROR("Failed to add hpd irq id!\n");
 3645		return r;
 3646	}
 3647
 3648	register_hpd_handlers(adev);
 3649
 3650	return 0;
 3651}
 3652#endif
 3653
 3654/* Register IRQ sources and initialize IRQ callbacks */
 3655static int dce110_register_irq_handlers(struct amdgpu_device *adev)
 3656{
 3657	struct dc *dc = adev->dm.dc;
 3658	struct common_irq_params *c_irq_params;
 3659	struct dc_interrupt_params int_params = {0};
 3660	int r;
 3661	int i;
 3662	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
 3663
 3664	if (adev->family >= AMDGPU_FAMILY_AI)
 3665		client_id = SOC15_IH_CLIENTID_DCE;
 3666
 3667	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
 3668	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
 3669
 3670	/*
 3671	 * Actions of amdgpu_irq_add_id():
 3672	 * 1. Register a set() function with base driver.
 3673	 *    Base driver will call set() function to enable/disable an
 3674	 *    interrupt in DC hardware.
 3675	 * 2. Register amdgpu_dm_irq_handler().
 3676	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
 3677	 *    coming from DC hardware.
 3678	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
 3679	 *    for acknowledging and handling.
 3680	 */
 3681
 3682	/* Use VBLANK interrupt */
 3683	for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
 3684		r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
 3685		if (r) {
 3686			DRM_ERROR("Failed to add crtc irq id!\n");
 3687			return r;
 3688		}
 3689
 3690		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
 3691		int_params.irq_source =
 3692			dc_interrupt_to_irq_source(dc, i, 0);
 3693
 3694		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
 3695
 3696		c_irq_params->adev = adev;
 3697		c_irq_params->irq_src = int_params.irq_source;
 3698
 3699		amdgpu_dm_irq_register_interrupt(adev, &int_params,
 3700				dm_crtc_high_irq, c_irq_params);
 3701	}
 3702
 3703	/* Use VUPDATE interrupt */
 3704	for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
 3705		r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
 3706		if (r) {
 3707			DRM_ERROR("Failed to add vupdate irq id!\n");
 3708			return r;
 3709		}
 3710
 3711		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
 3712		int_params.irq_source =
 3713			dc_interrupt_to_irq_source(dc, i, 0);
 3714
 3715		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
 3716
 3717		c_irq_params->adev = adev;
 3718		c_irq_params->irq_src = int_params.irq_source;
 3719
 3720		amdgpu_dm_irq_register_interrupt(adev, &int_params,
 3721				dm_vupdate_high_irq, c_irq_params);
 3722	}
 3723
 3724	/* Use GRPH_PFLIP interrupt */
 3725	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
 3726			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
 3727		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
 3728		if (r) {
 3729			DRM_ERROR("Failed to add page flip irq id!\n");
 3730			return r;
 3731		}
 3732
 3733		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
 3734		int_params.irq_source =
 3735			dc_interrupt_to_irq_source(dc, i, 0);
 3736
 3737		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
 3738
 3739		c_irq_params->adev = adev;
 3740		c_irq_params->irq_src = int_params.irq_source;
 3741
 3742		amdgpu_dm_irq_register_interrupt(adev, &int_params,
 3743				dm_pflip_high_irq, c_irq_params);
 3744
 3745	}
 3746
 3747	/* HPD */
 3748	r = amdgpu_irq_add_id(adev, client_id,
 3749			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
 3750	if (r) {
 3751		DRM_ERROR("Failed to add hpd irq id!\n");
 3752		return r;
 3753	}
 3754
 3755	register_hpd_handlers(adev);
 3756
 3757	return 0;
 3758}
 3759
 3760/* Register IRQ sources and initialize IRQ callbacks */
 3761static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
 3762{
 3763	struct dc *dc = adev->dm.dc;
 3764	struct common_irq_params *c_irq_params;
 3765	struct dc_interrupt_params int_params = {0};
 3766	int r;
 3767	int i;
 3768#if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
 3769	static const unsigned int vrtl_int_srcid[] = {
 3770		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
 3771		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
 3772		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
 3773		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
 3774		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
 3775		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
 3776	};
 3777#endif
 3778
 3779	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
 3780	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
 3781
 3782	/*
 3783	 * Actions of amdgpu_irq_add_id():
 3784	 * 1. Register a set() function with base driver.
 3785	 *    Base driver will call set() function to enable/disable an
 3786	 *    interrupt in DC hardware.
 3787	 * 2. Register amdgpu_dm_irq_handler().
 3788	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
 3789	 *    coming from DC hardware.
 3790	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
 3791	 *    for acknowledging and handling.
 3792	 */
 3793
 3794	/* Use VSTARTUP interrupt */
 3795	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
 3796			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
 3797			i++) {
 3798		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
 3799
 3800		if (r) {
 3801			DRM_ERROR("Failed to add crtc irq id!\n");
 3802			return r;
 3803		}
 3804
 3805		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
 3806		int_params.irq_source =
 3807			dc_interrupt_to_irq_source(dc, i, 0);
 3808
 3809		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
 3810
 3811		c_irq_params->adev = adev;
 3812		c_irq_params->irq_src = int_params.irq_source;
 3813
 3814		amdgpu_dm_irq_register_interrupt(
 3815			adev, &int_params, dm_crtc_high_irq, c_irq_params);
 3816	}
 3817
 3818	/* Use otg vertical line interrupt */
 3819#if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
 3820	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
 3821		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
 3822				vrtl_int_srcid[i], &adev->vline0_irq);
 3823
 3824		if (r) {
 3825			DRM_ERROR("Failed to add vline0 irq id!\n");
 3826			return r;
 3827		}
 3828
 3829		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
 3830		int_params.irq_source =
 3831			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
 3832
 3833		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID) {
 3834			DRM_ERROR("Failed to register vline0 irq %d!\n", vrtl_int_srcid[i]);
 3835			break;
 3836		}
 3837
 3838		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
 3839					- DC_IRQ_SOURCE_DC1_VLINE0];
 3840
 3841		c_irq_params->adev = adev;
 3842		c_irq_params->irq_src = int_params.irq_source;
 3843
 3844		amdgpu_dm_irq_register_interrupt(adev, &int_params,
 3845				dm_dcn_vertical_interrupt0_high_irq, c_irq_params);
 3846	}
 3847#endif
 3848
 3849	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
 3850	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
 3851	 * to trigger at end of each vblank, regardless of state of the lock,
 3852	 * matching DCE behaviour.
 3853	 */
 3854	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
 3855	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
 3856	     i++) {
 3857		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
 3858
 3859		if (r) {
 3860			DRM_ERROR("Failed to add vupdate irq id!\n");
 3861			return r;
 3862		}
 3863
 3864		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
 3865		int_params.irq_source =
 3866			dc_interrupt_to_irq_source(dc, i, 0);
 3867
 3868		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
 3869
 3870		c_irq_params->adev = adev;
 3871		c_irq_params->irq_src = int_params.irq_source;
 3872
 3873		amdgpu_dm_irq_register_interrupt(adev, &int_params,
 3874				dm_vupdate_high_irq, c_irq_params);
 3875	}
 3876
 3877	/* Use GRPH_PFLIP interrupt */
 3878	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
 3879			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
 3880			i++) {
 3881		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
 3882		if (r) {
 3883			DRM_ERROR("Failed to add page flip irq id!\n");
 3884			return r;
 3885		}
 3886
 3887		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
 3888		int_params.irq_source =
 3889			dc_interrupt_to_irq_source(dc, i, 0);
 3890
 3891		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
 3892
 3893		c_irq_params->adev = adev;
 3894		c_irq_params->irq_src = int_params.irq_source;
 3895
 3896		amdgpu_dm_irq_register_interrupt(adev, &int_params,
 3897				dm_pflip_high_irq, c_irq_params);
 3898
 3899	}
 3900
 3901	/* HPD */
 3902	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
 3903			&adev->hpd_irq);
 3904	if (r) {
 3905		DRM_ERROR("Failed to add hpd irq id!\n");
 3906		return r;
 3907	}
 3908
 3909	register_hpd_handlers(adev);
 3910
 3911	return 0;
 3912}
 3913/* Register Outbox IRQ sources and initialize IRQ callbacks */
 3914static int register_outbox_irq_handlers(struct amdgpu_device *adev)
 3915{
 3916	struct dc *dc = adev->dm.dc;
 3917	struct common_irq_params *c_irq_params;
 3918	struct dc_interrupt_params int_params = {0};
 3919	int r, i;
 3920
 3921	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
 3922	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
 3923
 3924	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
 3925			&adev->dmub_outbox_irq);
 3926	if (r) {
 3927		DRM_ERROR("Failed to add outbox irq id!\n");
 3928		return r;
 3929	}
 3930
 3931	if (dc->ctx->dmub_srv) {
 3932		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
 3933		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
 3934		int_params.irq_source =
 3935		dc_interrupt_to_irq_source(dc, i, 0);
 3936
 3937		c_irq_params = &adev->dm.dmub_outbox_params[0];
 3938
 3939		c_irq_params->adev = adev;
 3940		c_irq_params->irq_src = int_params.irq_source;
 3941
 3942		amdgpu_dm_irq_register_interrupt(adev, &int_params,
 3943				dm_dmub_outbox1_low_irq, c_irq_params);
 3944	}
 3945
 3946	return 0;
 3947}
 3948
 3949/*
 3950 * Acquires the lock for the atomic state object and returns
 3951 * the new atomic state.
 3952 *
 3953 * This should only be called during atomic check.
 3954 */
 3955int dm_atomic_get_state(struct drm_atomic_state *state,
 3956			struct dm_atomic_state **dm_state)
 3957{
 3958	struct drm_device *dev = state->dev;
 3959	struct amdgpu_device *adev = drm_to_adev(dev);
 3960	struct amdgpu_display_manager *dm = &adev->dm;
 3961	struct drm_private_state *priv_state;
 3962
 3963	if (*dm_state)
 3964		return 0;
 3965
 3966	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
 3967	if (IS_ERR(priv_state))
 3968		return PTR_ERR(priv_state);
 3969
 3970	*dm_state = to_dm_atomic_state(priv_state);
 3971
 3972	return 0;
 3973}
 3974
 3975static struct dm_atomic_state *
 3976dm_atomic_get_new_state(struct drm_atomic_state *state)
 3977{
 3978	struct drm_device *dev = state->dev;
 3979	struct amdgpu_device *adev = drm_to_adev(dev);
 3980	struct amdgpu_display_manager *dm = &adev->dm;
 3981	struct drm_private_obj *obj;
 3982	struct drm_private_state *new_obj_state;
 3983	int i;
 3984
 3985	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
 3986		if (obj->funcs == dm->atomic_obj.funcs)
 3987			return to_dm_atomic_state(new_obj_state);
 3988	}
 3989
 3990	return NULL;
 3991}
 3992
 3993static struct drm_private_state *
 3994dm_atomic_duplicate_state(struct drm_private_obj *obj)
 3995{
 3996	struct dm_atomic_state *old_state, *new_state;
 3997
 3998	new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
 3999	if (!new_state)
 4000		return NULL;
 4001
 4002	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
 4003
 4004	old_state = to_dm_atomic_state(obj->state);
 4005
 4006	if (old_state && old_state->context)
 4007		new_state->context = dc_state_create_copy(old_state->context);
 4008
 4009	if (!new_state->context) {
 4010		kfree(new_state);
 4011		return NULL;
 4012	}
 4013
 4014	return &new_state->base;
 4015}
 4016
 4017static void dm_atomic_destroy_state(struct drm_private_obj *obj,
 4018				    struct drm_private_state *state)
 4019{
 4020	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
 4021
 4022	if (dm_state && dm_state->context)
 4023		dc_state_release(dm_state->context);
 4024
 4025	kfree(dm_state);
 4026}
 4027
 4028static struct drm_private_state_funcs dm_atomic_state_funcs = {
 4029	.atomic_duplicate_state = dm_atomic_duplicate_state,
 4030	.atomic_destroy_state = dm_atomic_destroy_state,
 4031};
 4032
 4033static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
 4034{
 4035	struct dm_atomic_state *state;
 4036	int r;
 4037
 4038	adev->mode_info.mode_config_initialized = true;
 4039
 4040	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
 4041	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
 4042
 4043	adev_to_drm(adev)->mode_config.max_width = 16384;
 4044	adev_to_drm(adev)->mode_config.max_height = 16384;
 4045
 4046	adev_to_drm(adev)->mode_config.preferred_depth = 24;
 4047	if (adev->asic_type == CHIP_HAWAII)
 4048		/* disable prefer shadow for now due to hibernation issues */
 4049		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
 4050	else
 4051		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
 4052	/* indicates support for immediate flip */
 4053	adev_to_drm(adev)->mode_config.async_page_flip = true;
 4054
 4055	state = kzalloc(sizeof(*state), GFP_KERNEL);
 4056	if (!state)
 4057		return -ENOMEM;
 4058
 4059	state->context = dc_state_create_current_copy(adev->dm.dc);
 4060	if (!state->context) {
 4061		kfree(state);
 4062		return -ENOMEM;
 4063	}
 4064
 4065	drm_atomic_private_obj_init(adev_to_drm(adev),
 4066				    &adev->dm.atomic_obj,
 4067				    &state->base,
 4068				    &dm_atomic_state_funcs);
 4069
 4070	r = amdgpu_display_modeset_create_props(adev);
 4071	if (r) {
 4072		dc_state_release(state->context);
 4073		kfree(state);
 4074		return r;
 4075	}
 4076
 4077#ifdef AMD_PRIVATE_COLOR
 4078	if (amdgpu_dm_create_color_properties(adev))
 4079		return -ENOMEM;
 4080#endif
 4081
 4082	r = amdgpu_dm_audio_init(adev);
 4083	if (r) {
 4084		dc_state_release(state->context);
 4085		kfree(state);
 4086		return r;
 4087	}
 4088
 4089	return 0;
 4090}
 4091
 4092#define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
 4093#define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
 4094#define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
 4095
 4096static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
 4097					    int bl_idx)
 4098{
 4099#if defined(CONFIG_ACPI)
 4100	struct amdgpu_dm_backlight_caps caps;
 4101
 4102	memset(&caps, 0, sizeof(caps));
 4103
 4104	if (dm->backlight_caps[bl_idx].caps_valid)
 4105		return;
 4106
 4107	amdgpu_acpi_get_backlight_caps(&caps);
 4108	if (caps.caps_valid) {
 4109		dm->backlight_caps[bl_idx].caps_valid = true;
 4110		if (caps.aux_support)
 4111			return;
 4112		dm->backlight_caps[bl_idx].min_input_signal = caps.min_input_signal;
 4113		dm->backlight_caps[bl_idx].max_input_signal = caps.max_input_signal;
 4114	} else {
 4115		dm->backlight_caps[bl_idx].min_input_signal =
 4116				AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
 4117		dm->backlight_caps[bl_idx].max_input_signal =
 4118				AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
 4119	}
 4120#else
 4121	if (dm->backlight_caps[bl_idx].aux_support)
 4122		return;
 4123
 4124	dm->backlight_caps[bl_idx].min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
 4125	dm->backlight_caps[bl_idx].max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
 4126#endif
 4127}
 4128
 4129static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
 4130				unsigned int *min, unsigned int *max)
 4131{
 4132	if (!caps)
 4133		return 0;
 4134
 4135	if (caps->aux_support) {
 4136		// Firmware limits are in nits, DC API wants millinits.
 4137		*max = 1000 * caps->aux_max_input_signal;
 4138		*min = 1000 * caps->aux_min_input_signal;
 4139	} else {
 4140		// Firmware limits are 8-bit, PWM control is 16-bit.
 4141		*max = 0x101 * caps->max_input_signal;
 4142		*min = 0x101 * caps->min_input_signal;
 4143	}
 4144	return 1;
 4145}
 4146
 4147static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
 4148					uint32_t brightness)
 4149{
 4150	unsigned int min, max;
 4151
 4152	if (!get_brightness_range(caps, &min, &max))
 4153		return brightness;
 4154
 4155	// Rescale 0..255 to min..max
 4156	return min + DIV_ROUND_CLOSEST((max - min) * brightness,
 4157				       AMDGPU_MAX_BL_LEVEL);
 4158}
 4159
 4160static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
 4161				      uint32_t brightness)
 4162{
 4163	unsigned int min, max;
 4164
 4165	if (!get_brightness_range(caps, &min, &max))
 4166		return brightness;
 4167
 4168	if (brightness < min)
 4169		return 0;
 4170	// Rescale min..max to 0..255
 4171	return DIV_ROUND_CLOSEST(AMDGPU_MAX_BL_LEVEL * (brightness - min),
 4172				 max - min);
 4173}
 4174
 4175static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
 4176					 int bl_idx,
 4177					 u32 user_brightness)
 4178{
 4179	struct amdgpu_dm_backlight_caps caps;
 4180	struct dc_link *link;
 4181	u32 brightness;
 4182	bool rc;
 4183
 4184	amdgpu_dm_update_backlight_caps(dm, bl_idx);
 4185	caps = dm->backlight_caps[bl_idx];
 4186
 4187	dm->brightness[bl_idx] = user_brightness;
 4188	/* update scratch register */
 4189	if (bl_idx == 0)
 4190		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
 4191	brightness = convert_brightness_from_user(&caps, dm->brightness[bl_idx]);
 4192	link = (struct dc_link *)dm->backlight_link[bl_idx];
 4193
 4194	/* Change brightness based on AUX property */
 4195	if (caps.aux_support) {
 4196		rc = dc_link_set_backlight_level_nits(link, true, brightness,
 4197						      AUX_BL_DEFAULT_TRANSITION_TIME_MS);
 4198		if (!rc)
 4199			DRM_DEBUG("DM: Failed to update backlight via AUX on eDP[%d]\n", bl_idx);
 4200	} else {
 4201		rc = dc_link_set_backlight_level(link, brightness, 0);
 4202		if (!rc)
 4203			DRM_DEBUG("DM: Failed to update backlight on eDP[%d]\n", bl_idx);
 4204	}
 4205
 4206	if (rc)
 4207		dm->actual_brightness[bl_idx] = user_brightness;
 4208}
 4209
 4210static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
 4211{
 4212	struct amdgpu_display_manager *dm = bl_get_data(bd);
 4213	int i;
 4214
 4215	for (i = 0; i < dm->num_of_edps; i++) {
 4216		if (bd == dm->backlight_dev[i])
 4217			break;
 4218	}
 4219	if (i >= AMDGPU_DM_MAX_NUM_EDP)
 4220		i = 0;
 4221	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
 4222
 4223	return 0;
 4224}
 4225
 4226static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
 4227					 int bl_idx)
 4228{
 4229	int ret;
 4230	struct amdgpu_dm_backlight_caps caps;
 4231	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
 4232
 4233	amdgpu_dm_update_backlight_caps(dm, bl_idx);
 4234	caps = dm->backlight_caps[bl_idx];
 4235
 4236	if (caps.aux_support) {
 4237		u32 avg, peak;
 4238		bool rc;
 4239
 4240		rc = dc_link_get_backlight_level_nits(link, &avg, &peak);
 4241		if (!rc)
 4242			return dm->brightness[bl_idx];
 4243		return convert_brightness_to_user(&caps, avg);
 4244	}
 4245
 4246	ret = dc_link_get_backlight_level(link);
 4247
 4248	if (ret == DC_ERROR_UNEXPECTED)
 4249		return dm->brightness[bl_idx];
 4250
 4251	return convert_brightness_to_user(&caps, ret);
 4252}
 4253
 4254static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
 4255{
 4256	struct amdgpu_display_manager *dm = bl_get_data(bd);
 4257	int i;
 4258
 4259	for (i = 0; i < dm->num_of_edps; i++) {
 4260		if (bd == dm->backlight_dev[i])
 4261			break;
 4262	}
 4263	if (i >= AMDGPU_DM_MAX_NUM_EDP)
 4264		i = 0;
 4265	return amdgpu_dm_backlight_get_level(dm, i);
 4266}
 4267
 4268static const struct backlight_ops amdgpu_dm_backlight_ops = {
 4269	.options = BL_CORE_SUSPENDRESUME,
 4270	.get_brightness = amdgpu_dm_backlight_get_brightness,
 4271	.update_status	= amdgpu_dm_backlight_update_status,
 4272};
 4273
 4274static void
 4275amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
 4276{
 4277	struct drm_device *drm = aconnector->base.dev;
 4278	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
 4279	struct backlight_properties props = { 0 };
 4280	char bl_name[16];
 4281
 4282	if (aconnector->bl_idx == -1)
 4283		return;
 4284
 4285	if (!acpi_video_backlight_use_native()) {
 4286		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
 4287		/* Try registering an ACPI video backlight device instead. */
 4288		acpi_video_register_backlight();
 4289		return;
 4290	}
 4291
 4292	props.max_brightness = AMDGPU_MAX_BL_LEVEL;
 4293	props.brightness = AMDGPU_MAX_BL_LEVEL;
 4294	props.type = BACKLIGHT_RAW;
 4295
 4296	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
 4297		 drm->primary->index + aconnector->bl_idx);
 4298
 4299	dm->backlight_dev[aconnector->bl_idx] =
 4300		backlight_device_register(bl_name, aconnector->base.kdev, dm,
 4301					  &amdgpu_dm_backlight_ops, &props);
 4302
 4303	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
 4304		DRM_ERROR("DM: Backlight registration failed!\n");
 4305		dm->backlight_dev[aconnector->bl_idx] = NULL;
 4306	} else
 4307		DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
 4308}
 4309
 4310static int initialize_plane(struct amdgpu_display_manager *dm,
 4311			    struct amdgpu_mode_info *mode_info, int plane_id,
 4312			    enum drm_plane_type plane_type,
 4313			    const struct dc_plane_cap *plane_cap)
 4314{
 4315	struct drm_plane *plane;
 4316	unsigned long possible_crtcs;
 4317	int ret = 0;
 4318
 4319	plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
 4320	if (!plane) {
 4321		DRM_ERROR("KMS: Failed to allocate plane\n");
 4322		return -ENOMEM;
 4323	}
 4324	plane->type = plane_type;
 4325
 4326	/*
 4327	 * HACK: IGT tests expect that the primary plane for a CRTC
 4328	 * can only have one possible CRTC. Only expose support for
 4329	 * any CRTC if they're not going to be used as a primary plane
 4330	 * for a CRTC - like overlay or underlay planes.
 4331	 */
 4332	possible_crtcs = 1 << plane_id;
 4333	if (plane_id >= dm->dc->caps.max_streams)
 4334		possible_crtcs = 0xff;
 4335
 4336	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
 4337
 4338	if (ret) {
 4339		DRM_ERROR("KMS: Failed to initialize plane\n");
 4340		kfree(plane);
 4341		return ret;
 4342	}
 4343
 4344	if (mode_info)
 4345		mode_info->planes[plane_id] = plane;
 4346
 4347	return ret;
 4348}
 4349
 4350
 4351static void setup_backlight_device(struct amdgpu_display_manager *dm,
 4352				   struct amdgpu_dm_connector *aconnector)
 4353{
 4354	struct dc_link *link = aconnector->dc_link;
 4355	int bl_idx = dm->num_of_edps;
 4356
 4357	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
 4358	    link->type == dc_connection_none)
 4359		return;
 4360
 4361	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
 4362		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
 4363		return;
 4364	}
 4365
 4366	aconnector->bl_idx = bl_idx;
 4367
 4368	amdgpu_dm_update_backlight_caps(dm, bl_idx);
 4369	dm->brightness[bl_idx] = AMDGPU_MAX_BL_LEVEL;
 4370	dm->backlight_link[bl_idx] = link;
 4371	dm->num_of_edps++;
 4372
 4373	update_connector_ext_caps(aconnector);
 4374}
 4375
 4376static void amdgpu_set_panel_orientation(struct drm_connector *connector);
 4377
 4378/*
 4379 * In this architecture, the association
 4380 * connector -> encoder -> crtc
 4381 * id not really requried. The crtc and connector will hold the
 4382 * display_index as an abstraction to use with DAL component
 4383 *
 4384 * Returns 0 on success
 4385 */
 4386static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
 4387{
 4388	struct amdgpu_display_manager *dm = &adev->dm;
 4389	s32 i;
 4390	struct amdgpu_dm_connector *aconnector = NULL;
 4391	struct amdgpu_encoder *aencoder = NULL;
 4392	struct amdgpu_mode_info *mode_info = &adev->mode_info;
 4393	u32 link_cnt;
 4394	s32 primary_planes;
 4395	enum dc_connection_type new_connection_type = dc_connection_none;
 4396	const struct dc_plane_cap *plane;
 4397	bool psr_feature_enabled = false;
 4398	int max_overlay = dm->dc->caps.max_slave_planes;
 4399
 4400	dm->display_indexes_num = dm->dc->caps.max_streams;
 4401	/* Update the actual used number of crtc */
 4402	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
 4403
 4404	amdgpu_dm_set_irq_funcs(adev);
 4405
 4406	link_cnt = dm->dc->caps.max_links;
 4407	if (amdgpu_dm_mode_config_init(dm->adev)) {
 4408		DRM_ERROR("DM: Failed to initialize mode config\n");
 4409		return -EINVAL;
 4410	}
 4411
 4412	/* There is one primary plane per CRTC */
 4413	primary_planes = dm->dc->caps.max_streams;
 4414	ASSERT(primary_planes <= AMDGPU_MAX_PLANES);
 4415
 4416	/*
 4417	 * Initialize primary planes, implicit planes for legacy IOCTLS.
 4418	 * Order is reversed to match iteration order in atomic check.
 4419	 */
 4420	for (i = (primary_planes - 1); i >= 0; i--) {
 4421		plane = &dm->dc->caps.planes[i];
 4422
 4423		if (initialize_plane(dm, mode_info, i,
 4424				     DRM_PLANE_TYPE_PRIMARY, plane)) {
 4425			DRM_ERROR("KMS: Failed to initialize primary plane\n");
 4426			goto fail;
 4427		}
 4428	}
 4429
 4430	/*
 4431	 * Initialize overlay planes, index starting after primary planes.
 4432	 * These planes have a higher DRM index than the primary planes since
 4433	 * they should be considered as having a higher z-order.
 4434	 * Order is reversed to match iteration order in atomic check.
 4435	 *
 4436	 * Only support DCN for now, and only expose one so we don't encourage
 4437	 * userspace to use up all the pipes.
 4438	 */
 4439	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
 4440		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
 4441
 4442		/* Do not create overlay if MPO disabled */
 4443		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
 4444			break;
 4445
 4446		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
 4447			continue;
 4448
 4449		if (!plane->pixel_format_support.argb8888)
 4450			continue;
 4451
 4452		if (max_overlay-- == 0)
 4453			break;
 4454
 4455		if (initialize_plane(dm, NULL, primary_planes + i,
 4456				     DRM_PLANE_TYPE_OVERLAY, plane)) {
 4457			DRM_ERROR("KMS: Failed to initialize overlay plane\n");
 4458			goto fail;
 4459		}
 4460	}
 4461
 4462	for (i = 0; i < dm->dc->caps.max_streams; i++)
 4463		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
 4464			DRM_ERROR("KMS: Failed to initialize crtc\n");
 4465			goto fail;
 4466		}
 4467
 4468	/* Use Outbox interrupt */
 4469	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
 4470	case IP_VERSION(3, 0, 0):
 4471	case IP_VERSION(3, 1, 2):
 4472	case IP_VERSION(3, 1, 3):
 4473	case IP_VERSION(3, 1, 4):
 4474	case IP_VERSION(3, 1, 5):
 4475	case IP_VERSION(3, 1, 6):
 4476	case IP_VERSION(3, 2, 0):
 4477	case IP_VERSION(3, 2, 1):
 4478	case IP_VERSION(2, 1, 0):
 4479	case IP_VERSION(3, 5, 0):
 4480		if (register_outbox_irq_handlers(dm->adev)) {
 4481			DRM_ERROR("DM: Failed to initialize IRQ\n");
 4482			goto fail;
 4483		}
 4484		break;
 4485	default:
 4486		DRM_DEBUG_KMS("Unsupported DCN IP version for outbox: 0x%X\n",
 4487			      amdgpu_ip_version(adev, DCE_HWIP, 0));
 4488	}
 4489
 4490	/* Determine whether to enable PSR support by default. */
 4491	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
 4492		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
 4493		case IP_VERSION(3, 1, 2):
 4494		case IP_VERSION(3, 1, 3):
 4495		case IP_VERSION(3, 1, 4):
 4496		case IP_VERSION(3, 1, 5):
 4497		case IP_VERSION(3, 1, 6):
 4498		case IP_VERSION(3, 2, 0):
 4499		case IP_VERSION(3, 2, 1):
 4500		case IP_VERSION(3, 5, 0):
 4501			psr_feature_enabled = true;
 4502			break;
 4503		default:
 4504			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
 4505			break;
 4506		}
 4507	}
 4508
 4509	/* loops over all connectors on the board */
 4510	for (i = 0; i < link_cnt; i++) {
 4511		struct dc_link *link = NULL;
 4512
 4513		if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
 4514			DRM_ERROR(
 4515				"KMS: Cannot support more than %d display indexes\n",
 4516					AMDGPU_DM_MAX_DISPLAY_INDEX);
 4517			continue;
 4518		}
 4519
 4520		link = dc_get_link_at_index(dm->dc, i);
 4521
 4522		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
 4523			struct amdgpu_dm_wb_connector *wbcon = kzalloc(sizeof(*wbcon), GFP_KERNEL);
 4524
 4525			if (!wbcon) {
 4526				DRM_ERROR("KMS: Failed to allocate writeback connector\n");
 4527				continue;
 4528			}
 4529
 4530			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
 4531				DRM_ERROR("KMS: Failed to initialize writeback connector\n");
 4532				kfree(wbcon);
 4533				continue;
 4534			}
 4535
 4536			link->psr_settings.psr_feature_enabled = false;
 4537			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
 4538
 4539			continue;
 4540		}
 4541
 4542		aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
 4543		if (!aconnector)
 4544			goto fail;
 4545
 4546		aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
 4547		if (!aencoder)
 4548			goto fail;
 4549
 4550		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
 4551			DRM_ERROR("KMS: Failed to initialize encoder\n");
 4552			goto fail;
 4553		}
 4554
 4555		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
 4556			DRM_ERROR("KMS: Failed to initialize connector\n");
 4557			goto fail;
 4558		}
 4559
 4560		if (dm->hpd_rx_offload_wq)
 4561			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
 4562				aconnector;
 4563
 4564		if (!dc_link_detect_connection_type(link, &new_connection_type))
 4565			DRM_ERROR("KMS: Failed to detect connector\n");
 4566
 4567		if (aconnector->base.force && new_connection_type == dc_connection_none) {
 4568			emulated_link_detect(link);
 4569			amdgpu_dm_update_connector_after_detect(aconnector);
 4570		} else {
 4571			bool ret = false;
 4572
 4573			mutex_lock(&dm->dc_lock);
 4574			ret = dc_link_detect(link, DETECT_REASON_BOOT);
 4575			mutex_unlock(&dm->dc_lock);
 4576
 4577			if (ret) {
 4578				amdgpu_dm_update_connector_after_detect(aconnector);
 4579				setup_backlight_device(dm, aconnector);
 4580
 4581				if (psr_feature_enabled)
 4582					amdgpu_dm_set_psr_caps(link);
 4583
 4584				/* TODO: Fix vblank control helpers to delay PSR entry to allow this when
 4585				 * PSR is also supported.
 4586				 */
 4587				if (link->psr_settings.psr_feature_enabled)
 4588					adev_to_drm(adev)->vblank_disable_immediate = false;
 4589			}
 4590		}
 4591		amdgpu_set_panel_orientation(&aconnector->base);
 4592	}
 4593
 4594	/* Software is initialized. Now we can register interrupt handlers. */
 4595	switch (adev->asic_type) {
 4596#if defined(CONFIG_DRM_AMD_DC_SI)
 4597	case CHIP_TAHITI:
 4598	case CHIP_PITCAIRN:
 4599	case CHIP_VERDE:
 4600	case CHIP_OLAND:
 4601		if (dce60_register_irq_handlers(dm->adev)) {
 4602			DRM_ERROR("DM: Failed to initialize IRQ\n");
 4603			goto fail;
 4604		}
 4605		break;
 4606#endif
 4607	case CHIP_BONAIRE:
 4608	case CHIP_HAWAII:
 4609	case CHIP_KAVERI:
 4610	case CHIP_KABINI:
 4611	case CHIP_MULLINS:
 4612	case CHIP_TONGA:
 4613	case CHIP_FIJI:
 4614	case CHIP_CARRIZO:
 4615	case CHIP_STONEY:
 4616	case CHIP_POLARIS11:
 4617	case CHIP_POLARIS10:
 4618	case CHIP_POLARIS12:
 4619	case CHIP_VEGAM:
 4620	case CHIP_VEGA10:
 4621	case CHIP_VEGA12:
 4622	case CHIP_VEGA20:
 4623		if (dce110_register_irq_handlers(dm->adev)) {
 4624			DRM_ERROR("DM: Failed to initialize IRQ\n");
 4625			goto fail;
 4626		}
 4627		break;
 4628	default:
 4629		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
 4630		case IP_VERSION(1, 0, 0):
 4631		case IP_VERSION(1, 0, 1):
 4632		case IP_VERSION(2, 0, 2):
 4633		case IP_VERSION(2, 0, 3):
 4634		case IP_VERSION(2, 0, 0):
 4635		case IP_VERSION(2, 1, 0):
 4636		case IP_VERSION(3, 0, 0):
 4637		case IP_VERSION(3, 0, 2):
 4638		case IP_VERSION(3, 0, 3):
 4639		case IP_VERSION(3, 0, 1):
 4640		case IP_VERSION(3, 1, 2):
 4641		case IP_VERSION(3, 1, 3):
 4642		case IP_VERSION(3, 1, 4):
 4643		case IP_VERSION(3, 1, 5):
 4644		case IP_VERSION(3, 1, 6):
 4645		case IP_VERSION(3, 2, 0):
 4646		case IP_VERSION(3, 2, 1):
 4647		case IP_VERSION(3, 5, 0):
 4648			if (dcn10_register_irq_handlers(dm->adev)) {
 4649				DRM_ERROR("DM: Failed to initialize IRQ\n");
 4650				goto fail;
 4651			}
 4652			break;
 4653		default:
 4654			DRM_ERROR("Unsupported DCE IP versions: 0x%X\n",
 4655					amdgpu_ip_version(adev, DCE_HWIP, 0));
 4656			goto fail;
 4657		}
 4658		break;
 4659	}
 4660
 4661	return 0;
 4662fail:
 4663	kfree(aencoder);
 4664	kfree(aconnector);
 4665
 4666	return -EINVAL;
 4667}
 4668
 4669static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
 4670{
 4671	drm_atomic_private_obj_fini(&dm->atomic_obj);
 4672}
 4673
 4674/******************************************************************************
 4675 * amdgpu_display_funcs functions
 4676 *****************************************************************************/
 4677
 4678/*
 4679 * dm_bandwidth_update - program display watermarks
 4680 *
 4681 * @adev: amdgpu_device pointer
 4682 *
 4683 * Calculate and program the display watermarks and line buffer allocation.
 4684 */
 4685static void dm_bandwidth_update(struct amdgpu_device *adev)
 4686{
 4687	/* TODO: implement later */
 4688}
 4689
 4690static const struct amdgpu_display_funcs dm_display_funcs = {
 4691	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
 4692	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
 4693	.backlight_set_level = NULL, /* never called for DC */
 4694	.backlight_get_level = NULL, /* never called for DC */
 4695	.hpd_sense = NULL,/* called unconditionally */
 4696	.hpd_set_polarity = NULL, /* called unconditionally */
 4697	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
 4698	.page_flip_get_scanoutpos =
 4699		dm_crtc_get_scanoutpos,/* called unconditionally */
 4700	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
 4701	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
 4702};
 4703
 4704#if defined(CONFIG_DEBUG_KERNEL_DC)
 4705
 4706static ssize_t s3_debug_store(struct device *device,
 4707			      struct device_attribute *attr,
 4708			      const char *buf,
 4709			      size_t count)
 4710{
 4711	int ret;
 4712	int s3_state;
 4713	struct drm_device *drm_dev = dev_get_drvdata(device);
 4714	struct amdgpu_device *adev = drm_to_adev(drm_dev);
 4715
 4716	ret = kstrtoint(buf, 0, &s3_state);
 4717
 4718	if (ret == 0) {
 4719		if (s3_state) {
 4720			dm_resume(adev);
 4721			drm_kms_helper_hotplug_event(adev_to_drm(adev));
 4722		} else
 4723			dm_suspend(adev);
 4724	}
 4725
 4726	return ret == 0 ? count : 0;
 4727}
 4728
 4729DEVICE_ATTR_WO(s3_debug);
 4730
 4731#endif
 4732
 4733static int dm_init_microcode(struct amdgpu_device *adev)
 4734{
 4735	char *fw_name_dmub;
 4736	int r;
 4737
 4738	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
 4739	case IP_VERSION(2, 1, 0):
 4740		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
 4741		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
 4742			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
 4743		break;
 4744	case IP_VERSION(3, 0, 0):
 4745		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
 4746			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
 4747		else
 4748			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
 4749		break;
 4750	case IP_VERSION(3, 0, 1):
 4751		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
 4752		break;
 4753	case IP_VERSION(3, 0, 2):
 4754		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
 4755		break;
 4756	case IP_VERSION(3, 0, 3):
 4757		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
 4758		break;
 4759	case IP_VERSION(3, 1, 2):
 4760	case IP_VERSION(3, 1, 3):
 4761		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
 4762		break;
 4763	case IP_VERSION(3, 1, 4):
 4764		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
 4765		break;
 4766	case IP_VERSION(3, 1, 5):
 4767		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
 4768		break;
 4769	case IP_VERSION(3, 1, 6):
 4770		fw_name_dmub = FIRMWARE_DCN316_DMUB;
 4771		break;
 4772	case IP_VERSION(3, 2, 0):
 4773		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
 4774		break;
 4775	case IP_VERSION(3, 2, 1):
 4776		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
 4777		break;
 4778	case IP_VERSION(3, 5, 0):
 4779		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
 4780		break;
 4781	default:
 4782		/* ASIC doesn't support DMUB. */
 4783		return 0;
 4784	}
 4785	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, fw_name_dmub);
 4786	return r;
 4787}
 4788
 4789static int dm_early_init(void *handle)
 4790{
 4791	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
 4792	struct amdgpu_mode_info *mode_info = &adev->mode_info;
 4793	struct atom_context *ctx = mode_info->atom_context;
 4794	int index = GetIndexIntoMasterTable(DATA, Object_Header);
 4795	u16 data_offset;
 4796
 4797	/* if there is no object header, skip DM */
 4798	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
 4799		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
 4800		dev_info(adev->dev, "No object header, skipping DM\n");
 4801		return -ENOENT;
 4802	}
 4803
 4804	switch (adev->asic_type) {
 4805#if defined(CONFIG_DRM_AMD_DC_SI)
 4806	case CHIP_TAHITI:
 4807	case CHIP_PITCAIRN:
 4808	case CHIP_VERDE:
 4809		adev->mode_info.num_crtc = 6;
 4810		adev->mode_info.num_hpd = 6;
 4811		adev->mode_info.num_dig = 6;
 4812		break;
 4813	case CHIP_OLAND:
 4814		adev->mode_info.num_crtc = 2;
 4815		adev->mode_info.num_hpd = 2;
 4816		adev->mode_info.num_dig = 2;
 4817		break;
 4818#endif
 4819	case CHIP_BONAIRE:
 4820	case CHIP_HAWAII:
 4821		adev->mode_info.num_crtc = 6;
 4822		adev->mode_info.num_hpd = 6;
 4823		adev->mode_info.num_dig = 6;
 4824		break;
 4825	case CHIP_KAVERI:
 4826		adev->mode_info.num_crtc = 4;
 4827		adev->mode_info.num_hpd = 6;
 4828		adev->mode_info.num_dig = 7;
 4829		break;
 4830	case CHIP_KABINI:
 4831	case CHIP_MULLINS:
 4832		adev->mode_info.num_crtc = 2;
 4833		adev->mode_info.num_hpd = 6;
 4834		adev->mode_info.num_dig = 6;
 4835		break;
 4836	case CHIP_FIJI:
 4837	case CHIP_TONGA:
 4838		adev->mode_info.num_crtc = 6;
 4839		adev->mode_info.num_hpd = 6;
 4840		adev->mode_info.num_dig = 7;
 4841		break;
 4842	case CHIP_CARRIZO:
 4843		adev->mode_info.num_crtc = 3;
 4844		adev->mode_info.num_hpd = 6;
 4845		adev->mode_info.num_dig = 9;
 4846		break;
 4847	case CHIP_STONEY:
 4848		adev->mode_info.num_crtc = 2;
 4849		adev->mode_info.num_hpd = 6;
 4850		adev->mode_info.num_dig = 9;
 4851		break;
 4852	case CHIP_POLARIS11:
 4853	case CHIP_POLARIS12:
 4854		adev->mode_info.num_crtc = 5;
 4855		adev->mode_info.num_hpd = 5;
 4856		adev->mode_info.num_dig = 5;
 4857		break;
 4858	case CHIP_POLARIS10:
 4859	case CHIP_VEGAM:
 4860		adev->mode_info.num_crtc = 6;
 4861		adev->mode_info.num_hpd = 6;
 4862		adev->mode_info.num_dig = 6;
 4863		break;
 4864	case CHIP_VEGA10:
 4865	case CHIP_VEGA12:
 4866	case CHIP_VEGA20:
 4867		adev->mode_info.num_crtc = 6;
 4868		adev->mode_info.num_hpd = 6;
 4869		adev->mode_info.num_dig = 6;
 4870		break;
 4871	default:
 4872
 4873		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
 4874		case IP_VERSION(2, 0, 2):
 4875		case IP_VERSION(3, 0, 0):
 4876			adev->mode_info.num_crtc = 6;
 4877			adev->mode_info.num_hpd = 6;
 4878			adev->mode_info.num_dig = 6;
 4879			break;
 4880		case IP_VERSION(2, 0, 0):
 4881		case IP_VERSION(3, 0, 2):
 4882			adev->mode_info.num_crtc = 5;
 4883			adev->mode_info.num_hpd = 5;
 4884			adev->mode_info.num_dig = 5;
 4885			break;
 4886		case IP_VERSION(2, 0, 3):
 4887		case IP_VERSION(3, 0, 3):
 4888			adev->mode_info.num_crtc = 2;
 4889			adev->mode_info.num_hpd = 2;
 4890			adev->mode_info.num_dig = 2;
 4891			break;
 4892		case IP_VERSION(1, 0, 0):
 4893		case IP_VERSION(1, 0, 1):
 4894		case IP_VERSION(3, 0, 1):
 4895		case IP_VERSION(2, 1, 0):
 4896		case IP_VERSION(3, 1, 2):
 4897		case IP_VERSION(3, 1, 3):
 4898		case IP_VERSION(3, 1, 4):
 4899		case IP_VERSION(3, 1, 5):
 4900		case IP_VERSION(3, 1, 6):
 4901		case IP_VERSION(3, 2, 0):
 4902		case IP_VERSION(3, 2, 1):
 4903		case IP_VERSION(3, 5, 0):
 4904			adev->mode_info.num_crtc = 4;
 4905			adev->mode_info.num_hpd = 4;
 4906			adev->mode_info.num_dig = 4;
 4907			break;
 4908		default:
 4909			DRM_ERROR("Unsupported DCE IP versions: 0x%x\n",
 4910					amdgpu_ip_version(adev, DCE_HWIP, 0));
 4911			return -EINVAL;
 4912		}
 4913		break;
 4914	}
 4915
 4916	if (adev->mode_info.funcs == NULL)
 4917		adev->mode_info.funcs = &dm_display_funcs;
 4918
 4919	/*
 4920	 * Note: Do NOT change adev->audio_endpt_rreg and
 4921	 * adev->audio_endpt_wreg because they are initialised in
 4922	 * amdgpu_device_init()
 4923	 */
 4924#if defined(CONFIG_DEBUG_KERNEL_DC)
 4925	device_create_file(
 4926		adev_to_drm(adev)->dev,
 4927		&dev_attr_s3_debug);
 4928#endif
 4929	adev->dc_enabled = true;
 4930
 4931	return dm_init_microcode(adev);
 4932}
 4933
 4934static bool modereset_required(struct drm_crtc_state *crtc_state)
 4935{
 4936	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
 4937}
 4938
 4939static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
 4940{
 4941	drm_encoder_cleanup(encoder);
 4942	kfree(encoder);
 4943}
 4944
 4945static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
 4946	.destroy = amdgpu_dm_encoder_destroy,
 4947};
 4948
 4949static int
 4950fill_plane_color_attributes(const struct drm_plane_state *plane_state,
 4951			    const enum surface_pixel_format format,
 4952			    enum dc_color_space *color_space)
 4953{
 4954	bool full_range;
 4955
 4956	*color_space = COLOR_SPACE_SRGB;
 4957
 4958	/* DRM color properties only affect non-RGB formats. */
 4959	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
 4960		return 0;
 4961
 4962	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
 4963
 4964	switch (plane_state->color_encoding) {
 4965	case DRM_COLOR_YCBCR_BT601:
 4966		if (full_range)
 4967			*color_space = COLOR_SPACE_YCBCR601;
 4968		else
 4969			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
 4970		break;
 4971
 4972	case DRM_COLOR_YCBCR_BT709:
 4973		if (full_range)
 4974			*color_space = COLOR_SPACE_YCBCR709;
 4975		else
 4976			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
 4977		break;
 4978
 4979	case DRM_COLOR_YCBCR_BT2020:
 4980		if (full_range)
 4981			*color_space = COLOR_SPACE_2020_YCBCR;
 4982		else
 4983			return -EINVAL;
 4984		break;
 4985
 4986	default:
 4987		return -EINVAL;
 4988	}
 4989
 4990	return 0;
 4991}
 4992
 4993static int
 4994fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
 4995			    const struct drm_plane_state *plane_state,
 4996			    const u64 tiling_flags,
 4997			    struct dc_plane_info *plane_info,
 4998			    struct dc_plane_address *address,
 4999			    bool tmz_surface,
 5000			    bool force_disable_dcc)
 5001{
 5002	const struct drm_framebuffer *fb = plane_state->fb;
 5003	const struct amdgpu_framebuffer *afb =
 5004		to_amdgpu_framebuffer(plane_state->fb);
 5005	int ret;
 5006
 5007	memset(plane_info, 0, sizeof(*plane_info));
 5008
 5009	switch (fb->format->format) {
 5010	case DRM_FORMAT_C8:
 5011		plane_info->format =
 5012			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
 5013		break;
 5014	case DRM_FORMAT_RGB565:
 5015		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
 5016		break;
 5017	case DRM_FORMAT_XRGB8888:
 5018	case DRM_FORMAT_ARGB8888:
 5019		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
 5020		break;
 5021	case DRM_FORMAT_XRGB2101010:
 5022	case DRM_FORMAT_ARGB2101010:
 5023		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
 5024		break;
 5025	case DRM_FORMAT_XBGR2101010:
 5026	case DRM_FORMAT_ABGR2101010:
 5027		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
 5028		break;
 5029	case DRM_FORMAT_XBGR8888:
 5030	case DRM_FORMAT_ABGR8888:
 5031		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
 5032		break;
 5033	case DRM_FORMAT_NV21:
 5034		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
 5035		break;
 5036	case DRM_FORMAT_NV12:
 5037		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
 5038		break;
 5039	case DRM_FORMAT_P010:
 5040		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
 5041		break;
 5042	case DRM_FORMAT_XRGB16161616F:
 5043	case DRM_FORMAT_ARGB16161616F:
 5044		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
 5045		break;
 5046	case DRM_FORMAT_XBGR16161616F:
 5047	case DRM_FORMAT_ABGR16161616F:
 5048		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
 5049		break;
 5050	case DRM_FORMAT_XRGB16161616:
 5051	case DRM_FORMAT_ARGB16161616:
 5052		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
 5053		break;
 5054	case DRM_FORMAT_XBGR16161616:
 5055	case DRM_FORMAT_ABGR16161616:
 5056		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
 5057		break;
 5058	default:
 5059		DRM_ERROR(
 5060			"Unsupported screen format %p4cc\n",
 5061			&fb->format->format);
 5062		return -EINVAL;
 5063	}
 5064
 5065	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
 5066	case DRM_MODE_ROTATE_0:
 5067		plane_info->rotation = ROTATION_ANGLE_0;
 5068		break;
 5069	case DRM_MODE_ROTATE_90:
 5070		plane_info->rotation = ROTATION_ANGLE_90;
 5071		break;
 5072	case DRM_MODE_ROTATE_180:
 5073		plane_info->rotation = ROTATION_ANGLE_180;
 5074		break;
 5075	case DRM_MODE_ROTATE_270:
 5076		plane_info->rotation = ROTATION_ANGLE_270;
 5077		break;
 5078	default:
 5079		plane_info->rotation = ROTATION_ANGLE_0;
 5080		break;
 5081	}
 5082
 5083
 5084	plane_info->visible = true;
 5085	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
 5086
 5087	plane_info->layer_index = plane_state->normalized_zpos;
 5088
 5089	ret = fill_plane_color_attributes(plane_state, plane_info->format,
 5090					  &plane_info->color_space);
 5091	if (ret)
 5092		return ret;
 5093
 5094	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
 5095					   plane_info->rotation, tiling_flags,
 5096					   &plane_info->tiling_info,
 5097					   &plane_info->plane_size,
 5098					   &plane_info->dcc, address,
 5099					   tmz_surface, force_disable_dcc);
 5100	if (ret)
 5101		return ret;
 5102
 5103	amdgpu_dm_plane_fill_blending_from_plane_state(
 5104		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
 5105		&plane_info->global_alpha, &plane_info->global_alpha_value);
 5106
 5107	return 0;
 5108}
 5109
 5110static int fill_dc_plane_attributes(struct amdgpu_device *adev,
 5111				    struct dc_plane_state *dc_plane_state,
 5112				    struct drm_plane_state *plane_state,
 5113				    struct drm_crtc_state *crtc_state)
 5114{
 5115	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
 5116	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
 5117	struct dc_scaling_info scaling_info;
 5118	struct dc_plane_info plane_info;
 5119	int ret;
 5120	bool force_disable_dcc = false;
 5121
 5122	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
 5123	if (ret)
 5124		return ret;
 5125
 5126	dc_plane_state->src_rect = scaling_info.src_rect;
 5127	dc_plane_state->dst_rect = scaling_info.dst_rect;
 5128	dc_plane_state->clip_rect = scaling_info.clip_rect;
 5129	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
 5130
 5131	force_disable_dcc = adev->asic_type == CHIP_RAVEN && adev->in_suspend;
 5132	ret = fill_dc_plane_info_and_addr(adev, plane_state,
 5133					  afb->tiling_flags,
 5134					  &plane_info,
 5135					  &dc_plane_state->address,
 5136					  afb->tmz_surface,
 5137					  force_disable_dcc);
 5138	if (ret)
 5139		return ret;
 5140
 5141	dc_plane_state->format = plane_info.format;
 5142	dc_plane_state->color_space = plane_info.color_space;
 5143	dc_plane_state->format = plane_info.format;
 5144	dc_plane_state->plane_size = plane_info.plane_size;
 5145	dc_plane_state->rotation = plane_info.rotation;
 5146	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
 5147	dc_plane_state->stereo_format = plane_info.stereo_format;
 5148	dc_plane_state->tiling_info = plane_info.tiling_info;
 5149	dc_plane_state->visible = plane_info.visible;
 5150	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
 5151	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
 5152	dc_plane_state->global_alpha = plane_info.global_alpha;
 5153	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
 5154	dc_plane_state->dcc = plane_info.dcc;
 5155	dc_plane_state->layer_index = plane_info.layer_index;
 5156	dc_plane_state->flip_int_enabled = true;
 5157
 5158	/*
 5159	 * Always set input transfer function, since plane state is refreshed
 5160	 * every time.
 5161	 */
 5162	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
 5163						plane_state,
 5164						dc_plane_state);
 5165	if (ret)
 5166		return ret;
 5167
 5168	return 0;
 5169}
 5170
 5171static inline void fill_dc_dirty_rect(struct drm_plane *plane,
 5172				      struct rect *dirty_rect, int32_t x,
 5173				      s32 y, s32 width, s32 height,
 5174				      int *i, bool ffu)
 5175{
 5176	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
 5177
 5178	dirty_rect->x = x;
 5179	dirty_rect->y = y;
 5180	dirty_rect->width = width;
 5181	dirty_rect->height = height;
 5182
 5183	if (ffu)
 5184		drm_dbg(plane->dev,
 5185			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
 5186			plane->base.id, width, height);
 5187	else
 5188		drm_dbg(plane->dev,
 5189			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
 5190			plane->base.id, x, y, width, height);
 5191
 5192	(*i)++;
 5193}
 5194
 5195/**
 5196 * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
 5197 *
 5198 * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
 5199 *         remote fb
 5200 * @old_plane_state: Old state of @plane
 5201 * @new_plane_state: New state of @plane
 5202 * @crtc_state: New state of CRTC connected to the @plane
 5203 * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
 5204 * @dirty_regions_changed: dirty regions changed
 5205 *
 5206 * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
 5207 * (referred to as "damage clips" in DRM nomenclature) that require updating on
 5208 * the eDP remote buffer. The responsibility of specifying the dirty regions is
 5209 * amdgpu_dm's.
 5210 *
 5211 * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
 5212 * plane with regions that require flushing to the eDP remote buffer. In
 5213 * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
 5214 * implicitly provide damage clips without any client support via the plane
 5215 * bounds.
 5216 */
 5217static void fill_dc_dirty_rects(struct drm_plane *plane,
 5218				struct drm_plane_state *old_plane_state,
 5219				struct drm_plane_state *new_plane_state,
 5220				struct drm_crtc_state *crtc_state,
 5221				struct dc_flip_addrs *flip_addrs,
 5222				bool is_psr_su,
 5223				bool *dirty_regions_changed)
 5224{
 5225	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
 5226	struct rect *dirty_rects = flip_addrs->dirty_rects;
 5227	u32 num_clips;
 5228	struct drm_mode_rect *clips;
 5229	bool bb_changed;
 5230	bool fb_changed;
 5231	u32 i = 0;
 5232	*dirty_regions_changed = false;
 5233
 5234	/*
 5235	 * Cursor plane has it's own dirty rect update interface. See
 5236	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
 5237	 */
 5238	if (plane->type == DRM_PLANE_TYPE_CURSOR)
 5239		return;
 5240
 5241	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
 5242		goto ffu;
 5243
 5244	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
 5245	clips = drm_plane_get_damage_clips(new_plane_state);
 5246
 5247	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
 5248						   is_psr_su)))
 5249		goto ffu;
 5250
 5251	if (!dm_crtc_state->mpo_requested) {
 5252		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
 5253			goto ffu;
 5254
 5255		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
 5256			fill_dc_dirty_rect(new_plane_state->plane,
 5257					   &dirty_rects[flip_addrs->dirty_rect_count],
 5258					   clips->x1, clips->y1,
 5259					   clips->x2 - clips->x1, clips->y2 - clips->y1,
 5260					   &flip_addrs->dirty_rect_count,
 5261					   false);
 5262		return;
 5263	}
 5264
 5265	/*
 5266	 * MPO is requested. Add entire plane bounding box to dirty rects if
 5267	 * flipped to or damaged.
 5268	 *
 5269	 * If plane is moved or resized, also add old bounding box to dirty
 5270	 * rects.
 5271	 */
 5272	fb_changed = old_plane_state->fb->base.id !=
 5273		     new_plane_state->fb->base.id;
 5274	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
 5275		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
 5276		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
 5277		      old_plane_state->crtc_h != new_plane_state->crtc_h);
 5278
 5279	drm_dbg(plane->dev,
 5280		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
 5281		new_plane_state->plane->base.id,
 5282		bb_changed, fb_changed, num_clips);
 5283
 5284	*dirty_regions_changed = bb_changed;
 5285
 5286	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
 5287		goto ffu;
 5288
 5289	if (bb_changed) {
 5290		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
 5291				   new_plane_state->crtc_x,
 5292				   new_plane_state->crtc_y,
 5293				   new_plane_state->crtc_w,
 5294				   new_plane_state->crtc_h, &i, false);
 5295
 5296		/* Add old plane bounding-box if plane is moved or resized */
 5297		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
 5298				   old_plane_state->crtc_x,
 5299				   old_plane_state->crtc_y,
 5300				   old_plane_state->crtc_w,
 5301				   old_plane_state->crtc_h, &i, false);
 5302	}
 5303
 5304	if (num_clips) {
 5305		for (; i < num_clips; clips++)
 5306			fill_dc_dirty_rect(new_plane_state->plane,
 5307					   &dirty_rects[i], clips->x1,
 5308					   clips->y1, clips->x2 - clips->x1,
 5309					   clips->y2 - clips->y1, &i, false);
 5310	} else if (fb_changed && !bb_changed) {
 5311		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
 5312				   new_plane_state->crtc_x,
 5313				   new_plane_state->crtc_y,
 5314				   new_plane_state->crtc_w,
 5315				   new_plane_state->crtc_h, &i, false);
 5316	}
 5317
 5318	flip_addrs->dirty_rect_count = i;
 5319	return;
 5320
 5321ffu:
 5322	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
 5323			   dm_crtc_state->base.mode.crtc_hdisplay,
 5324			   dm_crtc_state->base.mode.crtc_vdisplay,
 5325			   &flip_addrs->dirty_rect_count, true);
 5326}
 5327
 5328static void update_stream_scaling_settings(const struct drm_display_mode *mode,
 5329					   const struct dm_connector_state *dm_state,
 5330					   struct dc_stream_state *stream)
 5331{
 5332	enum amdgpu_rmx_type rmx_type;
 5333
 5334	struct rect src = { 0 }; /* viewport in composition space*/
 5335	struct rect dst = { 0 }; /* stream addressable area */
 5336
 5337	/* no mode. nothing to be done */
 5338	if (!mode)
 5339		return;
 5340
 5341	/* Full screen scaling by default */
 5342	src.width = mode->hdisplay;
 5343	src.height = mode->vdisplay;
 5344	dst.width = stream->timing.h_addressable;
 5345	dst.height = stream->timing.v_addressable;
 5346
 5347	if (dm_state) {
 5348		rmx_type = dm_state->scaling;
 5349		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
 5350			if (src.width * dst.height <
 5351					src.height * dst.width) {
 5352				/* height needs less upscaling/more downscaling */
 5353				dst.width = src.width *
 5354						dst.height / src.height;
 5355			} else {
 5356				/* width needs less upscaling/more downscaling */
 5357				dst.height = src.height *
 5358						dst.width / src.width;
 5359			}
 5360		} else if (rmx_type == RMX_CENTER) {
 5361			dst = src;
 5362		}
 5363
 5364		dst.x = (stream->timing.h_addressable - dst.width) / 2;
 5365		dst.y = (stream->timing.v_addressable - dst.height) / 2;
 5366
 5367		if (dm_state->underscan_enable) {
 5368			dst.x += dm_state->underscan_hborder / 2;
 5369			dst.y += dm_state->underscan_vborder / 2;
 5370			dst.width -= dm_state->underscan_hborder;
 5371			dst.height -= dm_state->underscan_vborder;
 5372		}
 5373	}
 5374
 5375	stream->src = src;
 5376	stream->dst = dst;
 5377
 5378	DRM_DEBUG_KMS("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
 5379		      dst.x, dst.y, dst.width, dst.height);
 5380
 5381}
 5382
 5383static enum dc_color_depth
 5384convert_color_depth_from_display_info(const struct drm_connector *connector,
 5385				      bool is_y420, int requested_bpc)
 5386{
 5387	u8 bpc;
 5388
 5389	if (is_y420) {
 5390		bpc = 8;
 5391
 5392		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
 5393		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
 5394			bpc = 16;
 5395		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
 5396			bpc = 12;
 5397		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
 5398			bpc = 10;
 5399	} else {
 5400		bpc = (uint8_t)connector->display_info.bpc;
 5401		/* Assume 8 bpc by default if no bpc is specified. */
 5402		bpc = bpc ? bpc : 8;
 5403	}
 5404
 5405	if (requested_bpc > 0) {
 5406		/*
 5407		 * Cap display bpc based on the user requested value.
 5408		 *
 5409		 * The value for state->max_bpc may not correctly updated
 5410		 * depending on when the connector gets added to the state
 5411		 * or if this was called outside of atomic check, so it
 5412		 * can't be used directly.
 5413		 */
 5414		bpc = min_t(u8, bpc, requested_bpc);
 5415
 5416		/* Round down to the nearest even number. */
 5417		bpc = bpc - (bpc & 1);
 5418	}
 5419
 5420	switch (bpc) {
 5421	case 0:
 5422		/*
 5423		 * Temporary Work around, DRM doesn't parse color depth for
 5424		 * EDID revision before 1.4
 5425		 * TODO: Fix edid parsing
 5426		 */
 5427		return COLOR_DEPTH_888;
 5428	case 6:
 5429		return COLOR_DEPTH_666;
 5430	case 8:
 5431		return COLOR_DEPTH_888;
 5432	case 10:
 5433		return COLOR_DEPTH_101010;
 5434	case 12:
 5435		return COLOR_DEPTH_121212;
 5436	case 14:
 5437		return COLOR_DEPTH_141414;
 5438	case 16:
 5439		return COLOR_DEPTH_161616;
 5440	default:
 5441		return COLOR_DEPTH_UNDEFINED;
 5442	}
 5443}
 5444
 5445static enum dc_aspect_ratio
 5446get_aspect_ratio(const struct drm_display_mode *mode_in)
 5447{
 5448	/* 1-1 mapping, since both enums follow the HDMI spec. */
 5449	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
 5450}
 5451
 5452static enum dc_color_space
 5453get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
 5454		       const struct drm_connector_state *connector_state)
 5455{
 5456	enum dc_color_space color_space = COLOR_SPACE_SRGB;
 5457
 5458	switch (connector_state->colorspace) {
 5459	case DRM_MODE_COLORIMETRY_BT601_YCC:
 5460		if (dc_crtc_timing->flags.Y_ONLY)
 5461			color_space = COLOR_SPACE_YCBCR601_LIMITED;
 5462		else
 5463			color_space = COLOR_SPACE_YCBCR601;
 5464		break;
 5465	case DRM_MODE_COLORIMETRY_BT709_YCC:
 5466		if (dc_crtc_timing->flags.Y_ONLY)
 5467			color_space = COLOR_SPACE_YCBCR709_LIMITED;
 5468		else
 5469			color_space = COLOR_SPACE_YCBCR709;
 5470		break;
 5471	case DRM_MODE_COLORIMETRY_OPRGB:
 5472		color_space = COLOR_SPACE_ADOBERGB;
 5473		break;
 5474	case DRM_MODE_COLORIMETRY_BT2020_RGB:
 5475	case DRM_MODE_COLORIMETRY_BT2020_YCC:
 5476		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
 5477			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
 5478		else
 5479			color_space = COLOR_SPACE_2020_YCBCR;
 5480		break;
 5481	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
 5482	default:
 5483		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
 5484			color_space = COLOR_SPACE_SRGB;
 5485		/*
 5486		 * 27030khz is the separation point between HDTV and SDTV
 5487		 * according to HDMI spec, we use YCbCr709 and YCbCr601
 5488		 * respectively
 5489		 */
 5490		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
 5491			if (dc_crtc_timing->flags.Y_ONLY)
 5492				color_space =
 5493					COLOR_SPACE_YCBCR709_LIMITED;
 5494			else
 5495				color_space = COLOR_SPACE_YCBCR709;
 5496		} else {
 5497			if (dc_crtc_timing->flags.Y_ONLY)
 5498				color_space =
 5499					COLOR_SPACE_YCBCR601_LIMITED;
 5500			else
 5501				color_space = COLOR_SPACE_YCBCR601;
 5502		}
 5503		break;
 5504	}
 5505
 5506	return color_space;
 5507}
 5508
 5509static enum display_content_type
 5510get_output_content_type(const struct drm_connector_state *connector_state)
 5511{
 5512	switch (connector_state->content_type) {
 5513	default:
 5514	case DRM_MODE_CONTENT_TYPE_NO_DATA:
 5515		return DISPLAY_CONTENT_TYPE_NO_DATA;
 5516	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
 5517		return DISPLAY_CONTENT_TYPE_GRAPHICS;
 5518	case DRM_MODE_CONTENT_TYPE_PHOTO:
 5519		return DISPLAY_CONTENT_TYPE_PHOTO;
 5520	case DRM_MODE_CONTENT_TYPE_CINEMA:
 5521		return DISPLAY_CONTENT_TYPE_CINEMA;
 5522	case DRM_MODE_CONTENT_TYPE_GAME:
 5523		return DISPLAY_CONTENT_TYPE_GAME;
 5524	}
 5525}
 5526
 5527static bool adjust_colour_depth_from_display_info(
 5528	struct dc_crtc_timing *timing_out,
 5529	const struct drm_display_info *info)
 5530{
 5531	enum dc_color_depth depth = timing_out->display_color_depth;
 5532	int normalized_clk;
 5533
 5534	do {
 5535		normalized_clk = timing_out->pix_clk_100hz / 10;
 5536		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
 5537		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
 5538			normalized_clk /= 2;
 5539		/* Adjusting pix clock following on HDMI spec based on colour depth */
 5540		switch (depth) {
 5541		case COLOR_DEPTH_888:
 5542			break;
 5543		case COLOR_DEPTH_101010:
 5544			normalized_clk = (normalized_clk * 30) / 24;
 5545			break;
 5546		case COLOR_DEPTH_121212:
 5547			normalized_clk = (normalized_clk * 36) / 24;
 5548			break;
 5549		case COLOR_DEPTH_161616:
 5550			normalized_clk = (normalized_clk * 48) / 24;
 5551			break;
 5552		default:
 5553			/* The above depths are the only ones valid for HDMI. */
 5554			return false;
 5555		}
 5556		if (normalized_clk <= info->max_tmds_clock) {
 5557			timing_out->display_color_depth = depth;
 5558			return true;
 5559		}
 5560	} while (--depth > COLOR_DEPTH_666);
 5561	return false;
 5562}
 5563
 5564static void fill_stream_properties_from_drm_display_mode(
 5565	struct dc_stream_state *stream,
 5566	const struct drm_display_mode *mode_in,
 5567	const struct drm_connector *connector,
 5568	const struct drm_connector_state *connector_state,
 5569	const struct dc_stream_state *old_stream,
 5570	int requested_bpc)
 5571{
 5572	struct dc_crtc_timing *timing_out = &stream->timing;
 5573	const struct drm_display_info *info = &connector->display_info;
 5574	struct amdgpu_dm_connector *aconnector = NULL;
 5575	struct hdmi_vendor_infoframe hv_frame;
 5576	struct hdmi_avi_infoframe avi_frame;
 5577
 5578	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
 5579		aconnector = to_amdgpu_dm_connector(connector);
 5580
 5581	memset(&hv_frame, 0, sizeof(hv_frame));
 5582	memset(&avi_frame, 0, sizeof(avi_frame));
 5583
 5584	timing_out->h_border_left = 0;
 5585	timing_out->h_border_right = 0;
 5586	timing_out->v_border_top = 0;
 5587	timing_out->v_border_bottom = 0;
 5588	/* TODO: un-hardcode */
 5589	if (drm_mode_is_420_only(info, mode_in)
 5590			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
 5591		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
 5592	else if (drm_mode_is_420_also(info, mode_in)
 5593			&& aconnector
 5594			&& aconnector->force_yuv420_output)
 5595		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
 5596	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR444)
 5597			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
 5598		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
 5599	else
 5600		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
 5601
 5602	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
 5603	timing_out->display_color_depth = convert_color_depth_from_display_info(
 5604		connector,
 5605		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
 5606		requested_bpc);
 5607	timing_out->scan_type = SCANNING_TYPE_NODATA;
 5608	timing_out->hdmi_vic = 0;
 5609
 5610	if (old_stream) {
 5611		timing_out->vic = old_stream->timing.vic;
 5612		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
 5613		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
 5614	} else {
 5615		timing_out->vic = drm_match_cea_mode(mode_in);
 5616		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
 5617			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
 5618		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
 5619			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
 5620	}
 5621
 5622	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
 5623		drm_hdmi_avi_infoframe_from_display_mode(&avi_frame, (struct drm_connector *)connector, mode_in);
 5624		timing_out->vic = avi_frame.video_code;
 5625		drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame, (struct drm_connector *)connector, mode_in);
 5626		timing_out->hdmi_vic = hv_frame.vic;
 5627	}
 5628
 5629	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
 5630		timing_out->h_addressable = mode_in->hdisplay;
 5631		timing_out->h_total = mode_in->htotal;
 5632		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
 5633		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
 5634		timing_out->v_total = mode_in->vtotal;
 5635		timing_out->v_addressable = mode_in->vdisplay;
 5636		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
 5637		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
 5638		timing_out->pix_clk_100hz = mode_in->clock * 10;
 5639	} else {
 5640		timing_out->h_addressable = mode_in->crtc_hdisplay;
 5641		timing_out->h_total = mode_in->crtc_htotal;
 5642		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
 5643		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
 5644		timing_out->v_total = mode_in->crtc_vtotal;
 5645		timing_out->v_addressable = mode_in->crtc_vdisplay;
 5646		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
 5647		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
 5648		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
 5649	}
 5650
 5651	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
 5652
 5653	stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
 5654	stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
 5655	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
 5656		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
 5657		    drm_mode_is_420_also(info, mode_in) &&
 5658		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
 5659			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
 5660			adjust_colour_depth_from_display_info(timing_out, info);
 5661		}
 5662	}
 5663
 5664	stream->output_color_space = get_output_color_space(timing_out, connector_state);
 5665	stream->content_type = get_output_content_type(connector_state);
 5666}
 5667
 5668static void fill_audio_info(struct audio_info *audio_info,
 5669			    const struct drm_connector *drm_connector,
 5670			    const struct dc_sink *dc_sink)
 5671{
 5672	int i = 0;
 5673	int cea_revision = 0;
 5674	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
 5675
 5676	audio_info->manufacture_id = edid_caps->manufacturer_id;
 5677	audio_info->product_id = edid_caps->product_id;
 5678
 5679	cea_revision = drm_connector->display_info.cea_rev;
 5680
 5681	strscpy(audio_info->display_name,
 5682		edid_caps->display_name,
 5683		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
 5684
 5685	if (cea_revision >= 3) {
 5686		audio_info->mode_count = edid_caps->audio_mode_count;
 5687
 5688		for (i = 0; i < audio_info->mode_count; ++i) {
 5689			audio_info->modes[i].format_code =
 5690					(enum audio_format_code)
 5691					(edid_caps->audio_modes[i].format_code);
 5692			audio_info->modes[i].channel_count =
 5693					edid_caps->audio_modes[i].channel_count;
 5694			audio_info->modes[i].sample_rates.all =
 5695					edid_caps->audio_modes[i].sample_rate;
 5696			audio_info->modes[i].sample_size =
 5697					edid_caps->audio_modes[i].sample_size;
 5698		}
 5699	}
 5700
 5701	audio_info->flags.all = edid_caps->speaker_flags;
 5702
 5703	/* TODO: We only check for the progressive mode, check for interlace mode too */
 5704	if (drm_connector->latency_present[0]) {
 5705		audio_info->video_latency = drm_connector->video_latency[0];
 5706		audio_info->audio_latency = drm_connector->audio_latency[0];
 5707	}
 5708
 5709	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
 5710
 5711}
 5712
 5713static void
 5714copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
 5715				      struct drm_display_mode *dst_mode)
 5716{
 5717	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
 5718	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
 5719	dst_mode->crtc_clock = src_mode->crtc_clock;
 5720	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
 5721	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
 5722	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
 5723	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
 5724	dst_mode->crtc_htotal = src_mode->crtc_htotal;
 5725	dst_mode->crtc_hskew = src_mode->crtc_hskew;
 5726	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
 5727	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
 5728	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
 5729	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
 5730	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
 5731}
 5732
 5733static void
 5734decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
 5735					const struct drm_display_mode *native_mode,
 5736					bool scale_enabled)
 5737{
 5738	if (scale_enabled) {
 5739		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
 5740	} else if (native_mode->clock == drm_mode->clock &&
 5741			native_mode->htotal == drm_mode->htotal &&
 5742			native_mode->vtotal == drm_mode->vtotal) {
 5743		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
 5744	} else {
 5745		/* no scaling nor amdgpu inserted, no need to patch */
 5746	}
 5747}
 5748
 5749static struct dc_sink *
 5750create_fake_sink(struct dc_link *link)
 5751{
 5752	struct dc_sink_init_data sink_init_data = { 0 };
 5753	struct dc_sink *sink = NULL;
 5754
 5755	sink_init_data.link = link;
 5756	sink_init_data.sink_signal = link->connector_signal;
 5757
 5758	sink = dc_sink_create(&sink_init_data);
 5759	if (!sink) {
 5760		DRM_ERROR("Failed to create sink!\n");
 5761		return NULL;
 5762	}
 5763	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
 5764
 5765	return sink;
 5766}
 5767
 5768static void set_multisync_trigger_params(
 5769		struct dc_stream_state *stream)
 5770{
 5771	struct dc_stream_state *master = NULL;
 5772
 5773	if (stream->triggered_crtc_reset.enabled) {
 5774		master = stream->triggered_crtc_reset.event_source;
 5775		stream->triggered_crtc_reset.event =
 5776			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
 5777			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
 5778		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
 5779	}
 5780}
 5781
 5782static void set_master_stream(struct dc_stream_state *stream_set[],
 5783			      int stream_count)
 5784{
 5785	int j, highest_rfr = 0, master_stream = 0;
 5786
 5787	for (j = 0;  j < stream_count; j++) {
 5788		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
 5789			int refresh_rate = 0;
 5790
 5791			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
 5792				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
 5793			if (refresh_rate > highest_rfr) {
 5794				highest_rfr = refresh_rate;
 5795				master_stream = j;
 5796			}
 5797		}
 5798	}
 5799	for (j = 0;  j < stream_count; j++) {
 5800		if (stream_set[j])
 5801			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
 5802	}
 5803}
 5804
 5805static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
 5806{
 5807	int i = 0;
 5808	struct dc_stream_state *stream;
 5809
 5810	if (context->stream_count < 2)
 5811		return;
 5812	for (i = 0; i < context->stream_count ; i++) {
 5813		if (!context->streams[i])
 5814			continue;
 5815		/*
 5816		 * TODO: add a function to read AMD VSDB bits and set
 5817		 * crtc_sync_master.multi_sync_enabled flag
 5818		 * For now it's set to false
 5819		 */
 5820	}
 5821
 5822	set_master_stream(context->streams, context->stream_count);
 5823
 5824	for (i = 0; i < context->stream_count ; i++) {
 5825		stream = context->streams[i];
 5826
 5827		if (!stream)
 5828			continue;
 5829
 5830		set_multisync_trigger_params(stream);
 5831	}
 5832}
 5833
 5834/**
 5835 * DOC: FreeSync Video
 5836 *
 5837 * When a userspace application wants to play a video, the content follows a
 5838 * standard format definition that usually specifies the FPS for that format.
 5839 * The below list illustrates some video format and the expected FPS,
 5840 * respectively:
 5841 *
 5842 * - TV/NTSC (23.976 FPS)
 5843 * - Cinema (24 FPS)
 5844 * - TV/PAL (25 FPS)
 5845 * - TV/NTSC (29.97 FPS)
 5846 * - TV/NTSC (30 FPS)
 5847 * - Cinema HFR (48 FPS)
 5848 * - TV/PAL (50 FPS)
 5849 * - Commonly used (60 FPS)
 5850 * - Multiples of 24 (48,72,96 FPS)
 5851 *
 5852 * The list of standards video format is not huge and can be added to the
 5853 * connector modeset list beforehand. With that, userspace can leverage
 5854 * FreeSync to extends the front porch in order to attain the target refresh
 5855 * rate. Such a switch will happen seamlessly, without screen blanking or
 5856 * reprogramming of the output in any other way. If the userspace requests a
 5857 * modesetting change compatible with FreeSync modes that only differ in the
 5858 * refresh rate, DC will skip the full update and avoid blink during the
 5859 * transition. For example, the video player can change the modesetting from
 5860 * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
 5861 * causing any display blink. This same concept can be applied to a mode
 5862 * setting change.
 5863 */
 5864static struct drm_display_mode *
 5865get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
 5866		bool use_probed_modes)
 5867{
 5868	struct drm_display_mode *m, *m_pref = NULL;
 5869	u16 current_refresh, highest_refresh;
 5870	struct list_head *list_head = use_probed_modes ?
 5871		&aconnector->base.probed_modes :
 5872		&aconnector->base.modes;
 5873
 5874	if (aconnector->freesync_vid_base.clock != 0)
 5875		return &aconnector->freesync_vid_base;
 5876
 5877	/* Find the preferred mode */
 5878	list_for_each_entry(m, list_head, head) {
 5879		if (m->type & DRM_MODE_TYPE_PREFERRED) {
 5880			m_pref = m;
 5881			break;
 5882		}
 5883	}
 5884
 5885	if (!m_pref) {
 5886		/* Probably an EDID with no preferred mode. Fallback to first entry */
 5887		m_pref = list_first_entry_or_null(
 5888				&aconnector->base.modes, struct drm_display_mode, head);
 5889		if (!m_pref) {
 5890			DRM_DEBUG_DRIVER("No preferred mode found in EDID\n");
 5891			return NULL;
 5892		}
 5893	}
 5894
 5895	highest_refresh = drm_mode_vrefresh(m_pref);
 5896
 5897	/*
 5898	 * Find the mode with highest refresh rate with same resolution.
 5899	 * For some monitors, preferred mode is not the mode with highest
 5900	 * supported refresh rate.
 5901	 */
 5902	list_for_each_entry(m, list_head, head) {
 5903		current_refresh  = drm_mode_vrefresh(m);
 5904
 5905		if (m->hdisplay == m_pref->hdisplay &&
 5906		    m->vdisplay == m_pref->vdisplay &&
 5907		    highest_refresh < current_refresh) {
 5908			highest_refresh = current_refresh;
 5909			m_pref = m;
 5910		}
 5911	}
 5912
 5913	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
 5914	return m_pref;
 5915}
 5916
 5917static bool is_freesync_video_mode(const struct drm_display_mode *mode,
 5918		struct amdgpu_dm_connector *aconnector)
 5919{
 5920	struct drm_display_mode *high_mode;
 5921	int timing_diff;
 5922
 5923	high_mode = get_highest_refresh_rate_mode(aconnector, false);
 5924	if (!high_mode || !mode)
 5925		return false;
 5926
 5927	timing_diff = high_mode->vtotal - mode->vtotal;
 5928
 5929	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
 5930	    high_mode->hdisplay != mode->hdisplay ||
 5931	    high_mode->vdisplay != mode->vdisplay ||
 5932	    high_mode->hsync_start != mode->hsync_start ||
 5933	    high_mode->hsync_end != mode->hsync_end ||
 5934	    high_mode->htotal != mode->htotal ||
 5935	    high_mode->hskew != mode->hskew ||
 5936	    high_mode->vscan != mode->vscan ||
 5937	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
 5938	    high_mode->vsync_end - mode->vsync_end != timing_diff)
 5939		return false;
 5940	else
 5941		return true;
 5942}
 5943
 5944static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
 5945			    struct dc_sink *sink, struct dc_stream_state *stream,
 5946			    struct dsc_dec_dpcd_caps *dsc_caps)
 5947{
 5948	stream->timing.flags.DSC = 0;
 5949	dsc_caps->is_dsc_supported = false;
 5950
 5951	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
 5952	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
 5953		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
 5954			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
 5955			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
 5956				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
 5957				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
 5958				dsc_caps);
 5959	}
 5960}
 5961
 5962
 5963static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
 5964				    struct dc_sink *sink, struct dc_stream_state *stream,
 5965				    struct dsc_dec_dpcd_caps *dsc_caps,
 5966				    uint32_t max_dsc_target_bpp_limit_override)
 5967{
 5968	const struct dc_link_settings *verified_link_cap = NULL;
 5969	u32 link_bw_in_kbps;
 5970	u32 edp_min_bpp_x16, edp_max_bpp_x16;
 5971	struct dc *dc = sink->ctx->dc;
 5972	struct dc_dsc_bw_range bw_range = {0};
 5973	struct dc_dsc_config dsc_cfg = {0};
 5974	struct dc_dsc_config_options dsc_options = {0};
 5975
 5976	dc_dsc_get_default_config_option(dc, &dsc_options);
 5977	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
 5978
 5979	verified_link_cap = dc_link_get_link_cap(stream->link);
 5980	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
 5981	edp_min_bpp_x16 = 8 * 16;
 5982	edp_max_bpp_x16 = 8 * 16;
 5983
 5984	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
 5985		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
 5986
 5987	if (edp_max_bpp_x16 < edp_min_bpp_x16)
 5988		edp_min_bpp_x16 = edp_max_bpp_x16;
 5989
 5990	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
 5991				dc->debug.dsc_min_slice_height_override,
 5992				edp_min_bpp_x16, edp_max_bpp_x16,
 5993				dsc_caps,
 5994				&stream->timing,
 5995				dc_link_get_highest_encoding_format(aconnector->dc_link),
 5996				&bw_range)) {
 5997
 5998		if (bw_range.max_kbps < link_bw_in_kbps) {
 5999			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
 6000					dsc_caps,
 6001					&dsc_options,
 6002					0,
 6003					&stream->timing,
 6004					dc_link_get_highest_encoding_format(aconnector->dc_link),
 6005					&dsc_cfg)) {
 6006				stream->timing.dsc_cfg = dsc_cfg;
 6007				stream->timing.flags.DSC = 1;
 6008				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
 6009			}
 6010			return;
 6011		}
 6012	}
 6013
 6014	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
 6015				dsc_caps,
 6016				&dsc_options,
 6017				link_bw_in_kbps,
 6018				&stream->timing,
 6019				dc_link_get_highest_encoding_format(aconnector->dc_link),
 6020				&dsc_cfg)) {
 6021		stream->timing.dsc_cfg = dsc_cfg;
 6022		stream->timing.flags.DSC = 1;
 6023	}
 6024}
 6025
 6026
 6027static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
 6028					struct dc_sink *sink, struct dc_stream_state *stream,
 6029					struct dsc_dec_dpcd_caps *dsc_caps)
 6030{
 6031	struct drm_connector *drm_connector = &aconnector->base;
 6032	u32 link_bandwidth_kbps;
 6033	struct dc *dc = sink->ctx->dc;
 6034	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
 6035	u32 dsc_max_supported_bw_in_kbps;
 6036	u32 max_dsc_target_bpp_limit_override =
 6037		drm_connector->display_info.max_dsc_bpp;
 6038	struct dc_dsc_config_options dsc_options = {0};
 6039
 6040	dc_dsc_get_default_config_option(dc, &dsc_options);
 6041	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
 6042
 6043	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
 6044							dc_link_get_link_cap(aconnector->dc_link));
 6045
 6046	/* Set DSC policy according to dsc_clock_en */
 6047	dc_dsc_policy_set_enable_dsc_when_not_needed(
 6048		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
 6049
 6050	if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_EDP &&
 6051	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
 6052	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
 6053
 6054		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
 6055
 6056	} else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
 6057		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
 6058			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
 6059						dsc_caps,
 6060						&dsc_options,
 6061						link_bandwidth_kbps,
 6062						&stream->timing,
 6063						dc_link_get_highest_encoding_format(aconnector->dc_link),
 6064						&stream->timing.dsc_cfg)) {
 6065				stream->timing.flags.DSC = 1;
 6066				DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from SST RX\n", __func__, drm_connector->name);
 6067			}
 6068		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
 6069			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
 6070					dc_link_get_highest_encoding_format(aconnector->dc_link));
 6071			max_supported_bw_in_kbps = link_bandwidth_kbps;
 6072			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
 6073
 6074			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
 6075					max_supported_bw_in_kbps > 0 &&
 6076					dsc_max_supported_bw_in_kbps > 0)
 6077				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
 6078						dsc_caps,
 6079						&dsc_options,
 6080						dsc_max_supported_bw_in_kbps,
 6081						&stream->timing,
 6082						dc_link_get_highest_encoding_format(aconnector->dc_link),
 6083						&stream->timing.dsc_cfg)) {
 6084					stream->timing.flags.DSC = 1;
 6085					DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from DP-HDMI PCON\n",
 6086									 __func__, drm_connector->name);
 6087				}
 6088		}
 6089	}
 6090
 6091	/* Overwrite the stream flag if DSC is enabled through debugfs */
 6092	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
 6093		stream->timing.flags.DSC = 1;
 6094
 6095	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
 6096		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
 6097
 6098	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
 6099		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
 6100
 6101	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
 6102		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
 6103}
 6104
 6105static struct dc_stream_state *
 6106create_stream_for_sink(struct drm_connector *connector,
 6107		       const struct drm_display_mode *drm_mode,
 6108		       const struct dm_connector_state *dm_state,
 6109		       const struct dc_stream_state *old_stream,
 6110		       int requested_bpc)
 6111{
 6112	struct amdgpu_dm_connector *aconnector = NULL;
 6113	struct drm_display_mode *preferred_mode = NULL;
 6114	const struct drm_connector_state *con_state = &dm_state->base;
 6115	struct dc_stream_state *stream = NULL;
 6116	struct drm_display_mode mode;
 6117	struct drm_display_mode saved_mode;
 6118	struct drm_display_mode *freesync_mode = NULL;
 6119	bool native_mode_found = false;
 6120	bool recalculate_timing = false;
 6121	bool scale = dm_state->scaling != RMX_OFF;
 6122	int mode_refresh;
 6123	int preferred_refresh = 0;
 6124	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
 6125	struct dsc_dec_dpcd_caps dsc_caps;
 6126
 6127	struct dc_link *link = NULL;
 6128	struct dc_sink *sink = NULL;
 6129
 6130	drm_mode_init(&mode, drm_mode);
 6131	memset(&saved_mode, 0, sizeof(saved_mode));
 6132
 6133	if (connector == NULL) {
 6134		DRM_ERROR("connector is NULL!\n");
 6135		return stream;
 6136	}
 6137
 6138	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
 6139		aconnector = NULL;
 6140		aconnector = to_amdgpu_dm_connector(connector);
 6141		link = aconnector->dc_link;
 6142	} else {
 6143		struct drm_writeback_connector *wbcon = NULL;
 6144		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
 6145
 6146		wbcon = drm_connector_to_writeback(connector);
 6147		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
 6148		link = dm_wbcon->link;
 6149	}
 6150
 6151	if (!aconnector || !aconnector->dc_sink) {
 6152		sink = create_fake_sink(link);
 6153		if (!sink)
 6154			return stream;
 6155
 6156	} else {
 6157		sink = aconnector->dc_sink;
 6158		dc_sink_retain(sink);
 6159	}
 6160
 6161	stream = dc_create_stream_for_sink(sink);
 6162
 6163	if (stream == NULL) {
 6164		DRM_ERROR("Failed to create stream for sink!\n");
 6165		goto finish;
 6166	}
 6167
 6168	/* We leave this NULL for writeback connectors */
 6169	stream->dm_stream_context = aconnector;
 6170
 6171	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
 6172		connector->display_info.hdmi.scdc.scrambling.low_rates;
 6173
 6174	list_for_each_entry(preferred_mode, &connector->modes, head) {
 6175		/* Search for preferred mode */
 6176		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
 6177			native_mode_found = true;
 6178			break;
 6179		}
 6180	}
 6181	if (!native_mode_found)
 6182		preferred_mode = list_first_entry_or_null(
 6183				&connector->modes,
 6184				struct drm_display_mode,
 6185				head);
 6186
 6187	mode_refresh = drm_mode_vrefresh(&mode);
 6188
 6189	if (preferred_mode == NULL) {
 6190		/*
 6191		 * This may not be an error, the use case is when we have no
 6192		 * usermode calls to reset and set mode upon hotplug. In this
 6193		 * case, we call set mode ourselves to restore the previous mode
 6194		 * and the modelist may not be filled in time.
 6195		 */
 6196		DRM_DEBUG_DRIVER("No preferred mode found\n");
 6197	} else if (aconnector) {
 6198		recalculate_timing = is_freesync_video_mode(&mode, aconnector);
 6199		if (recalculate_timing) {
 6200			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
 6201			drm_mode_copy(&saved_mode, &mode);
 6202			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
 6203			drm_mode_copy(&mode, freesync_mode);
 6204			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
 6205		} else {
 6206			decide_crtc_timing_for_drm_display_mode(
 6207					&mode, preferred_mode, scale);
 6208
 6209			preferred_refresh = drm_mode_vrefresh(preferred_mode);
 6210		}
 6211	}
 6212
 6213	if (recalculate_timing)
 6214		drm_mode_set_crtcinfo(&saved_mode, 0);
 6215
 6216	/*
 6217	 * If scaling is enabled and refresh rate didn't change
 6218	 * we copy the vic and polarities of the old timings
 6219	 */
 6220	if (!scale || mode_refresh != preferred_refresh)
 6221		fill_stream_properties_from_drm_display_mode(
 6222			stream, &mode, connector, con_state, NULL,
 6223			requested_bpc);
 6224	else
 6225		fill_stream_properties_from_drm_display_mode(
 6226			stream, &mode, connector, con_state, old_stream,
 6227			requested_bpc);
 6228
 6229	/* The rest isn't needed for writeback connectors */
 6230	if (!aconnector)
 6231		goto finish;
 6232
 6233	if (aconnector->timing_changed) {
 6234		drm_dbg(aconnector->base.dev,
 6235			"overriding timing for automated test, bpc %d, changing to %d\n",
 6236			stream->timing.display_color_depth,
 6237			aconnector->timing_requested->display_color_depth);
 6238		stream->timing = *aconnector->timing_requested;
 6239	}
 6240
 6241	/* SST DSC determination policy */
 6242	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
 6243	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
 6244		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
 6245
 6246	update_stream_scaling_settings(&mode, dm_state, stream);
 6247
 6248	fill_audio_info(
 6249		&stream->audio_info,
 6250		connector,
 6251		sink);
 6252
 6253	update_stream_signal(stream, sink);
 6254
 6255	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
 6256		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
 6257	else if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
 6258			 stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
 6259			 stream->signal == SIGNAL_TYPE_EDP) {
 6260		//
 6261		// should decide stream support vsc sdp colorimetry capability
 6262		// before building vsc info packet
 6263		//
 6264		stream->use_vsc_sdp_for_colorimetry = false;
 6265		if (aconnector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
 6266			stream->use_vsc_sdp_for_colorimetry =
 6267				aconnector->dc_sink->is_vsc_sdp_colorimetry_supported;
 6268		} else {
 6269			if (stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED)
 6270				stream->use_vsc_sdp_for_colorimetry = true;
 6271		}
 6272		if (stream->out_transfer_func->tf == TRANSFER_FUNCTION_GAMMA22)
 6273			tf = TRANSFER_FUNC_GAMMA_22;
 6274		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
 6275
 6276		if (stream->link->psr_settings.psr_feature_enabled)
 6277			aconnector->psr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
 6278	}
 6279finish:
 6280	dc_sink_release(sink);
 6281
 6282	return stream;
 6283}
 6284
 6285static enum drm_connector_status
 6286amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
 6287{
 6288	bool connected;
 6289	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
 6290
 6291	/*
 6292	 * Notes:
 6293	 * 1. This interface is NOT called in context of HPD irq.
 6294	 * 2. This interface *is called* in context of user-mode ioctl. Which
 6295	 * makes it a bad place for *any* MST-related activity.
 6296	 */
 6297
 6298	if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
 6299	    !aconnector->fake_enable)
 6300		connected = (aconnector->dc_sink != NULL);
 6301	else
 6302		connected = (aconnector->base.force == DRM_FORCE_ON ||
 6303				aconnector->base.force == DRM_FORCE_ON_DIGITAL);
 6304
 6305	update_subconnector_property(aconnector);
 6306
 6307	return (connected ? connector_status_connected :
 6308			connector_status_disconnected);
 6309}
 6310
 6311int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
 6312					    struct drm_connector_state *connector_state,
 6313					    struct drm_property *property,
 6314					    uint64_t val)
 6315{
 6316	struct drm_device *dev = connector->dev;
 6317	struct amdgpu_device *adev = drm_to_adev(dev);
 6318	struct dm_connector_state *dm_old_state =
 6319		to_dm_connector_state(connector->state);
 6320	struct dm_connector_state *dm_new_state =
 6321		to_dm_connector_state(connector_state);
 6322
 6323	int ret = -EINVAL;
 6324
 6325	if (property == dev->mode_config.scaling_mode_property) {
 6326		enum amdgpu_rmx_type rmx_type;
 6327
 6328		switch (val) {
 6329		case DRM_MODE_SCALE_CENTER:
 6330			rmx_type = RMX_CENTER;
 6331			break;
 6332		case DRM_MODE_SCALE_ASPECT:
 6333			rmx_type = RMX_ASPECT;
 6334			break;
 6335		case DRM_MODE_SCALE_FULLSCREEN:
 6336			rmx_type = RMX_FULL;
 6337			break;
 6338		case DRM_MODE_SCALE_NONE:
 6339		default:
 6340			rmx_type = RMX_OFF;
 6341			break;
 6342		}
 6343
 6344		if (dm_old_state->scaling == rmx_type)
 6345			return 0;
 6346
 6347		dm_new_state->scaling = rmx_type;
 6348		ret = 0;
 6349	} else if (property == adev->mode_info.underscan_hborder_property) {
 6350		dm_new_state->underscan_hborder = val;
 6351		ret = 0;
 6352	} else if (property == adev->mode_info.underscan_vborder_property) {
 6353		dm_new_state->underscan_vborder = val;
 6354		ret = 0;
 6355	} else if (property == adev->mode_info.underscan_property) {
 6356		dm_new_state->underscan_enable = val;
 6357		ret = 0;
 6358	} else if (property == adev->mode_info.abm_level_property) {
 6359		dm_new_state->abm_level = val ?: ABM_LEVEL_IMMEDIATE_DISABLE;
 6360		ret = 0;
 6361	}
 6362
 6363	return ret;
 6364}
 6365
 6366int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
 6367					    const struct drm_connector_state *state,
 6368					    struct drm_property *property,
 6369					    uint64_t *val)
 6370{
 6371	struct drm_device *dev = connector->dev;
 6372	struct amdgpu_device *adev = drm_to_adev(dev);
 6373	struct dm_connector_state *dm_state =
 6374		to_dm_connector_state(state);
 6375	int ret = -EINVAL;
 6376
 6377	if (property == dev->mode_config.scaling_mode_property) {
 6378		switch (dm_state->scaling) {
 6379		case RMX_CENTER:
 6380			*val = DRM_MODE_SCALE_CENTER;
 6381			break;
 6382		case RMX_ASPECT:
 6383			*val = DRM_MODE_SCALE_ASPECT;
 6384			break;
 6385		case RMX_FULL:
 6386			*val = DRM_MODE_SCALE_FULLSCREEN;
 6387			break;
 6388		case RMX_OFF:
 6389		default:
 6390			*val = DRM_MODE_SCALE_NONE;
 6391			break;
 6392		}
 6393		ret = 0;
 6394	} else if (property == adev->mode_info.underscan_hborder_property) {
 6395		*val = dm_state->underscan_hborder;
 6396		ret = 0;
 6397	} else if (property == adev->mode_info.underscan_vborder_property) {
 6398		*val = dm_state->underscan_vborder;
 6399		ret = 0;
 6400	} else if (property == adev->mode_info.underscan_property) {
 6401		*val = dm_state->underscan_enable;
 6402		ret = 0;
 6403	} else if (property == adev->mode_info.abm_level_property) {
 6404		*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
 6405			dm_state->abm_level : 0;
 6406		ret = 0;
 6407	}
 6408
 6409	return ret;
 6410}
 6411
 6412static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
 6413{
 6414	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
 6415
 6416	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
 6417}
 6418
 6419static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
 6420{
 6421	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
 6422	struct amdgpu_device *adev = drm_to_adev(connector->dev);
 6423	struct amdgpu_display_manager *dm = &adev->dm;
 6424
 6425	/*
 6426	 * Call only if mst_mgr was initialized before since it's not done
 6427	 * for all connector types.
 6428	 */
 6429	if (aconnector->mst_mgr.dev)
 6430		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
 6431
 6432	if (aconnector->bl_idx != -1) {
 6433		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
 6434		dm->backlight_dev[aconnector->bl_idx] = NULL;
 6435	}
 6436
 6437	if (aconnector->dc_em_sink)
 6438		dc_sink_release(aconnector->dc_em_sink);
 6439	aconnector->dc_em_sink = NULL;
 6440	if (aconnector->dc_sink)
 6441		dc_sink_release(aconnector->dc_sink);
 6442	aconnector->dc_sink = NULL;
 6443
 6444	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
 6445	drm_connector_unregister(connector);
 6446	drm_connector_cleanup(connector);
 6447	if (aconnector->i2c) {
 6448		i2c_del_adapter(&aconnector->i2c->base);
 6449		kfree(aconnector->i2c);
 6450	}
 6451	kfree(aconnector->dm_dp_aux.aux.name);
 6452
 6453	kfree(connector);
 6454}
 6455
 6456void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
 6457{
 6458	struct dm_connector_state *state =
 6459		to_dm_connector_state(connector->state);
 6460
 6461	if (connector->state)
 6462		__drm_atomic_helper_connector_destroy_state(connector->state);
 6463
 6464	kfree(state);
 6465
 6466	state = kzalloc(sizeof(*state), GFP_KERNEL);
 6467
 6468	if (state) {
 6469		state->scaling = RMX_OFF;
 6470		state->underscan_enable = false;
 6471		state->underscan_hborder = 0;
 6472		state->underscan_vborder = 0;
 6473		state->base.max_requested_bpc = 8;
 6474		state->vcpi_slots = 0;
 6475		state->pbn = 0;
 6476
 6477		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP)
 6478			state->abm_level = amdgpu_dm_abm_level ?:
 6479				ABM_LEVEL_IMMEDIATE_DISABLE;
 6480
 6481		__drm_atomic_helper_connector_reset(connector, &state->base);
 6482	}
 6483}
 6484
 6485struct drm_connector_state *
 6486amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
 6487{
 6488	struct dm_connector_state *state =
 6489		to_dm_connector_state(connector->state);
 6490
 6491	struct dm_connector_state *new_state =
 6492			kmemdup(state, sizeof(*state), GFP_KERNEL);
 6493
 6494	if (!new_state)
 6495		return NULL;
 6496
 6497	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
 6498
 6499	new_state->freesync_capable = state->freesync_capable;
 6500	new_state->abm_level = state->abm_level;
 6501	new_state->scaling = state->scaling;
 6502	new_state->underscan_enable = state->underscan_enable;
 6503	new_state->underscan_hborder = state->underscan_hborder;
 6504	new_state->underscan_vborder = state->underscan_vborder;
 6505	new_state->vcpi_slots = state->vcpi_slots;
 6506	new_state->pbn = state->pbn;
 6507	return &new_state->base;
 6508}
 6509
 6510static int
 6511amdgpu_dm_connector_late_register(struct drm_connector *connector)
 6512{
 6513	struct amdgpu_dm_connector *amdgpu_dm_connector =
 6514		to_amdgpu_dm_connector(connector);
 6515	int r;
 6516
 6517	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
 6518
 6519	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
 6520	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
 6521		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
 6522		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
 6523		if (r)
 6524			return r;
 6525	}
 6526
 6527#if defined(CONFIG_DEBUG_FS)
 6528	connector_debugfs_init(amdgpu_dm_connector);
 6529#endif
 6530
 6531	return 0;
 6532}
 6533
 6534static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
 6535{
 6536	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
 6537	struct dc_link *dc_link = aconnector->dc_link;
 6538	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
 6539	struct edid *edid;
 6540	struct i2c_adapter *ddc;
 6541
 6542	if (dc_link && dc_link->aux_mode)
 6543		ddc = &aconnector->dm_dp_aux.aux.ddc;
 6544	else
 6545		ddc = &aconnector->i2c->base;
 6546
 6547	/*
 6548	 * Note: drm_get_edid gets edid in the following order:
 6549	 * 1) override EDID if set via edid_override debugfs,
 6550	 * 2) firmware EDID if set via edid_firmware module parameter
 6551	 * 3) regular DDC read.
 6552	 */
 6553	edid = drm_get_edid(connector, ddc);
 6554	if (!edid) {
 6555		DRM_ERROR("No EDID found on connector: %s.\n", connector->name);
 6556		return;
 6557	}
 6558
 6559	aconnector->edid = edid;
 6560
 6561	/* Update emulated (virtual) sink's EDID */
 6562	if (dc_em_sink && dc_link) {
 6563		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
 6564		memmove(dc_em_sink->dc_edid.raw_edid, edid, (edid->extensions + 1) * EDID_LENGTH);
 6565		dm_helpers_parse_edid_caps(
 6566			dc_link,
 6567			&dc_em_sink->dc_edid,
 6568			&dc_em_sink->edid_caps);
 6569	}
 6570}
 6571
 6572static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
 6573	.reset = amdgpu_dm_connector_funcs_reset,
 6574	.detect = amdgpu_dm_connector_detect,
 6575	.fill_modes = drm_helper_probe_single_connector_modes,
 6576	.destroy = amdgpu_dm_connector_destroy,
 6577	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
 6578	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
 6579	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
 6580	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
 6581	.late_register = amdgpu_dm_connector_late_register,
 6582	.early_unregister = amdgpu_dm_connector_unregister,
 6583	.force = amdgpu_dm_connector_funcs_force
 6584};
 6585
 6586static int get_modes(struct drm_connector *connector)
 6587{
 6588	return amdgpu_dm_connector_get_modes(connector);
 6589}
 6590
 6591static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
 6592{
 6593	struct drm_connector *connector = &aconnector->base;
 6594	struct dc_link *dc_link = aconnector->dc_link;
 6595	struct dc_sink_init_data init_params = {
 6596			.link = aconnector->dc_link,
 6597			.sink_signal = SIGNAL_TYPE_VIRTUAL
 6598	};
 6599	struct edid *edid;
 6600	struct i2c_adapter *ddc;
 6601
 6602	if (dc_link->aux_mode)
 6603		ddc = &aconnector->dm_dp_aux.aux.ddc;
 6604	else
 6605		ddc = &aconnector->i2c->base;
 6606
 6607	/*
 6608	 * Note: drm_get_edid gets edid in the following order:
 6609	 * 1) override EDID if set via edid_override debugfs,
 6610	 * 2) firmware EDID if set via edid_firmware module parameter
 6611	 * 3) regular DDC read.
 6612	 */
 6613	edid = drm_get_edid(connector, ddc);
 6614	if (!edid) {
 6615		DRM_ERROR("No EDID found on connector: %s.\n", connector->name);
 6616		return;
 6617	}
 6618
 6619	if (drm_detect_hdmi_monitor(edid))
 6620		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
 6621
 6622	aconnector->edid = edid;
 6623
 6624	aconnector->dc_em_sink = dc_link_add_remote_sink(
 6625		aconnector->dc_link,
 6626		(uint8_t *)edid,
 6627		(edid->extensions + 1) * EDID_LENGTH,
 6628		&init_params);
 6629
 6630	if (aconnector->base.force == DRM_FORCE_ON) {
 6631		aconnector->dc_sink = aconnector->dc_link->local_sink ?
 6632		aconnector->dc_link->local_sink :
 6633		aconnector->dc_em_sink;
 6634		dc_sink_retain(aconnector->dc_sink);
 6635	}
 6636}
 6637
 6638static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
 6639{
 6640	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
 6641
 6642	/*
 6643	 * In case of headless boot with force on for DP managed connector
 6644	 * Those settings have to be != 0 to get initial modeset
 6645	 */
 6646	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
 6647		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
 6648		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
 6649	}
 6650
 6651	create_eml_sink(aconnector);
 6652}
 6653
 6654static enum dc_status dm_validate_stream_and_context(struct dc *dc,
 6655						struct dc_stream_state *stream)
 6656{
 6657	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
 6658	struct dc_plane_state *dc_plane_state = NULL;
 6659	struct dc_state *dc_state = NULL;
 6660
 6661	if (!stream)
 6662		goto cleanup;
 6663
 6664	dc_plane_state = dc_create_plane_state(dc);
 6665	if (!dc_plane_state)
 6666		goto cleanup;
 6667
 6668	dc_state = dc_state_create(dc);
 6669	if (!dc_state)
 6670		goto cleanup;
 6671
 6672	/* populate stream to plane */
 6673	dc_plane_state->src_rect.height  = stream->src.height;
 6674	dc_plane_state->src_rect.width   = stream->src.width;
 6675	dc_plane_state->dst_rect.height  = stream->src.height;
 6676	dc_plane_state->dst_rect.width   = stream->src.width;
 6677	dc_plane_state->clip_rect.height = stream->src.height;
 6678	dc_plane_state->clip_rect.width  = stream->src.width;
 6679	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
 6680	dc_plane_state->plane_size.surface_size.height = stream->src.height;
 6681	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
 6682	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
 6683	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
 6684	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
 6685	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
 6686	dc_plane_state->rotation = ROTATION_ANGLE_0;
 6687	dc_plane_state->is_tiling_rotated = false;
 6688	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
 6689
 6690	dc_result = dc_validate_stream(dc, stream);
 6691	if (dc_result == DC_OK)
 6692		dc_result = dc_validate_plane(dc, dc_plane_state);
 6693
 6694	if (dc_result == DC_OK)
 6695		dc_result = dc_state_add_stream(dc, dc_state, stream);
 6696
 6697	if (dc_result == DC_OK && !dc_state_add_plane(
 6698						dc,
 6699						stream,
 6700						dc_plane_state,
 6701						dc_state))
 6702		dc_result = DC_FAIL_ATTACH_SURFACES;
 6703
 6704	if (dc_result == DC_OK)
 6705		dc_result = dc_validate_global_state(dc, dc_state, true);
 6706
 6707cleanup:
 6708	if (dc_state)
 6709		dc_state_release(dc_state);
 6710
 6711	if (dc_plane_state)
 6712		dc_plane_state_release(dc_plane_state);
 6713
 6714	return dc_result;
 6715}
 6716
 6717struct dc_stream_state *
 6718create_validate_stream_for_sink(struct amdgpu_dm_connector *aconnector,
 6719				const struct drm_display_mode *drm_mode,
 6720				const struct dm_connector_state *dm_state,
 6721				const struct dc_stream_state *old_stream)
 6722{
 6723	struct drm_connector *connector = &aconnector->base;
 6724	struct amdgpu_device *adev = drm_to_adev(connector->dev);
 6725	struct dc_stream_state *stream;
 6726	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
 6727	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
 6728	enum dc_status dc_result = DC_OK;
 6729
 6730	do {
 6731		stream = create_stream_for_sink(connector, drm_mode,
 6732						dm_state, old_stream,
 6733						requested_bpc);
 6734		if (stream == NULL) {
 6735			DRM_ERROR("Failed to create stream for sink!\n");
 6736			break;
 6737		}
 6738
 6739		if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
 6740			return stream;
 6741
 6742		dc_result = dc_validate_stream(adev->dm.dc, stream);
 6743		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
 6744			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
 6745
 6746		if (dc_result == DC_OK)
 6747			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
 6748
 6749		if (dc_result != DC_OK) {
 6750			DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d (%s)\n",
 6751				      drm_mode->hdisplay,
 6752				      drm_mode->vdisplay,
 6753				      drm_mode->clock,
 6754				      dc_result,
 6755				      dc_status_to_str(dc_result));
 6756
 6757			dc_stream_release(stream);
 6758			stream = NULL;
 6759			requested_bpc -= 2; /* lower bpc to retry validation */
 6760		}
 6761
 6762	} while (stream == NULL && requested_bpc >= 6);
 6763
 6764	if (dc_result == DC_FAIL_ENC_VALIDATE && !aconnector->force_yuv420_output) {
 6765		DRM_DEBUG_KMS("Retry forcing YCbCr420 encoding\n");
 6766
 6767		aconnector->force_yuv420_output = true;
 6768		stream = create_validate_stream_for_sink(aconnector, drm_mode,
 6769						dm_state, old_stream);
 6770		aconnector->force_yuv420_output = false;
 6771	}
 6772
 6773	return stream;
 6774}
 6775
 6776enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
 6777				   struct drm_display_mode *mode)
 6778{
 6779	int result = MODE_ERROR;
 6780	struct dc_sink *dc_sink;
 6781	/* TODO: Unhardcode stream count */
 6782	struct dc_stream_state *stream;
 6783	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
 6784
 6785	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
 6786			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
 6787		return result;
 6788
 6789	/*
 6790	 * Only run this the first time mode_valid is called to initilialize
 6791	 * EDID mgmt
 6792	 */
 6793	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
 6794		!aconnector->dc_em_sink)
 6795		handle_edid_mgmt(aconnector);
 6796
 6797	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
 6798
 6799	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
 6800				aconnector->base.force != DRM_FORCE_ON) {
 6801		DRM_ERROR("dc_sink is NULL!\n");
 6802		goto fail;
 6803	}
 6804
 6805	drm_mode_set_crtcinfo(mode, 0);
 6806
 6807	stream = create_validate_stream_for_sink(aconnector, mode,
 6808						 to_dm_connector_state(connector->state),
 6809						 NULL);
 6810	if (stream) {
 6811		dc_stream_release(stream);
 6812		result = MODE_OK;
 6813	}
 6814
 6815fail:
 6816	/* TODO: error handling*/
 6817	return result;
 6818}
 6819
 6820static int fill_hdr_info_packet(const struct drm_connector_state *state,
 6821				struct dc_info_packet *out)
 6822{
 6823	struct hdmi_drm_infoframe frame;
 6824	unsigned char buf[30]; /* 26 + 4 */
 6825	ssize_t len;
 6826	int ret, i;
 6827
 6828	memset(out, 0, sizeof(*out));
 6829
 6830	if (!state->hdr_output_metadata)
 6831		return 0;
 6832
 6833	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
 6834	if (ret)
 6835		return ret;
 6836
 6837	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
 6838	if (len < 0)
 6839		return (int)len;
 6840
 6841	/* Static metadata is a fixed 26 bytes + 4 byte header. */
 6842	if (len != 30)
 6843		return -EINVAL;
 6844
 6845	/* Prepare the infopacket for DC. */
 6846	switch (state->connector->connector_type) {
 6847	case DRM_MODE_CONNECTOR_HDMIA:
 6848		out->hb0 = 0x87; /* type */
 6849		out->hb1 = 0x01; /* version */
 6850		out->hb2 = 0x1A; /* length */
 6851		out->sb[0] = buf[3]; /* checksum */
 6852		i = 1;
 6853		break;
 6854
 6855	case DRM_MODE_CONNECTOR_DisplayPort:
 6856	case DRM_MODE_CONNECTOR_eDP:
 6857		out->hb0 = 0x00; /* sdp id, zero */
 6858		out->hb1 = 0x87; /* type */
 6859		out->hb2 = 0x1D; /* payload len - 1 */
 6860		out->hb3 = (0x13 << 2); /* sdp version */
 6861		out->sb[0] = 0x01; /* version */
 6862		out->sb[1] = 0x1A; /* length */
 6863		i = 2;
 6864		break;
 6865
 6866	default:
 6867		return -EINVAL;
 6868	}
 6869
 6870	memcpy(&out->sb[i], &buf[4], 26);
 6871	out->valid = true;
 6872
 6873	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
 6874		       sizeof(out->sb), false);
 6875
 6876	return 0;
 6877}
 6878
 6879static int
 6880amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
 6881				 struct drm_atomic_state *state)
 6882{
 6883	struct drm_connector_state *new_con_state =
 6884		drm_atomic_get_new_connector_state(state, conn);
 6885	struct drm_connector_state *old_con_state =
 6886		drm_atomic_get_old_connector_state(state, conn);
 6887	struct drm_crtc *crtc = new_con_state->crtc;
 6888	struct drm_crtc_state *new_crtc_state;
 6889	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
 6890	int ret;
 6891
 6892	trace_amdgpu_dm_connector_atomic_check(new_con_state);
 6893
 6894	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
 6895		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
 6896		if (ret < 0)
 6897			return ret;
 6898	}
 6899
 6900	if (!crtc)
 6901		return 0;
 6902
 6903	if (new_con_state->colorspace != old_con_state->colorspace) {
 6904		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
 6905		if (IS_ERR(new_crtc_state))
 6906			return PTR_ERR(new_crtc_state);
 6907
 6908		new_crtc_state->mode_changed = true;
 6909	}
 6910
 6911	if (new_con_state->content_type != old_con_state->content_type) {
 6912		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
 6913		if (IS_ERR(new_crtc_state))
 6914			return PTR_ERR(new_crtc_state);
 6915
 6916		new_crtc_state->mode_changed = true;
 6917	}
 6918
 6919	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
 6920		struct dc_info_packet hdr_infopacket;
 6921
 6922		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
 6923		if (ret)
 6924			return ret;
 6925
 6926		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
 6927		if (IS_ERR(new_crtc_state))
 6928			return PTR_ERR(new_crtc_state);
 6929
 6930		/*
 6931		 * DC considers the stream backends changed if the
 6932		 * static metadata changes. Forcing the modeset also
 6933		 * gives a simple way for userspace to switch from
 6934		 * 8bpc to 10bpc when setting the metadata to enter
 6935		 * or exit HDR.
 6936		 *
 6937		 * Changing the static metadata after it's been
 6938		 * set is permissible, however. So only force a
 6939		 * modeset if we're entering or exiting HDR.
 6940		 */
 6941		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
 6942			!old_con_state->hdr_output_metadata ||
 6943			!new_con_state->hdr_output_metadata;
 6944	}
 6945
 6946	return 0;
 6947}
 6948
 6949static const struct drm_connector_helper_funcs
 6950amdgpu_dm_connector_helper_funcs = {
 6951	/*
 6952	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
 6953	 * modes will be filtered by drm_mode_validate_size(), and those modes
 6954	 * are missing after user start lightdm. So we need to renew modes list.
 6955	 * in get_modes call back, not just return the modes count
 6956	 */
 6957	.get_modes = get_modes,
 6958	.mode_valid = amdgpu_dm_connector_mode_valid,
 6959	.atomic_check = amdgpu_dm_connector_atomic_check,
 6960};
 6961
 6962static void dm_encoder_helper_disable(struct drm_encoder *encoder)
 6963{
 6964
 6965}
 6966
 6967int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
 6968{
 6969	switch (display_color_depth) {
 6970	case COLOR_DEPTH_666:
 6971		return 6;
 6972	case COLOR_DEPTH_888:
 6973		return 8;
 6974	case COLOR_DEPTH_101010:
 6975		return 10;
 6976	case COLOR_DEPTH_121212:
 6977		return 12;
 6978	case COLOR_DEPTH_141414:
 6979		return 14;
 6980	case COLOR_DEPTH_161616:
 6981		return 16;
 6982	default:
 6983		break;
 6984	}
 6985	return 0;
 6986}
 6987
 6988static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
 6989					  struct drm_crtc_state *crtc_state,
 6990					  struct drm_connector_state *conn_state)
 6991{
 6992	struct drm_atomic_state *state = crtc_state->state;
 6993	struct drm_connector *connector = conn_state->connector;
 6994	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
 6995	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
 6996	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
 6997	struct drm_dp_mst_topology_mgr *mst_mgr;
 6998	struct drm_dp_mst_port *mst_port;
 6999	struct drm_dp_mst_topology_state *mst_state;
 7000	enum dc_color_depth color_depth;
 7001	int clock, bpp = 0;
 7002	bool is_y420 = false;
 7003
 7004	if (!aconnector->mst_output_port)
 7005		return 0;
 7006
 7007	mst_port = aconnector->mst_output_port;
 7008	mst_mgr = &aconnector->mst_root->mst_mgr;
 7009
 7010	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
 7011		return 0;
 7012
 7013	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
 7014	if (IS_ERR(mst_state))
 7015		return PTR_ERR(mst_state);
 7016
 7017	mst_state->pbn_div.full = dfixed_const(dm_mst_get_pbn_divider(aconnector->mst_root->dc_link));
 7018
 7019	if (!state->duplicated) {
 7020		int max_bpc = conn_state->max_requested_bpc;
 7021
 7022		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
 7023			  aconnector->force_yuv420_output;
 7024		color_depth = convert_color_depth_from_display_info(connector,
 7025								    is_y420,
 7026								    max_bpc);
 7027		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
 7028		clock = adjusted_mode->clock;
 7029		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
 7030	}
 7031
 7032	dm_new_connector_state->vcpi_slots =
 7033		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
 7034					      dm_new_connector_state->pbn);
 7035	if (dm_new_connector_state->vcpi_slots < 0) {
 7036		DRM_DEBUG_ATOMIC("failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
 7037		return dm_new_connector_state->vcpi_slots;
 7038	}
 7039	return 0;
 7040}
 7041
 7042const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
 7043	.disable = dm_encoder_helper_disable,
 7044	.atomic_check = dm_encoder_helper_atomic_check
 7045};
 7046
 7047static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
 7048					    struct dc_state *dc_state,
 7049					    struct dsc_mst_fairness_vars *vars)
 7050{
 7051	struct dc_stream_state *stream = NULL;
 7052	struct drm_connector *connector;
 7053	struct drm_connector_state *new_con_state;
 7054	struct amdgpu_dm_connector *aconnector;
 7055	struct dm_connector_state *dm_conn_state;
 7056	int i, j, ret;
 7057	int vcpi, pbn_div, pbn, slot_num = 0;
 7058
 7059	for_each_new_connector_in_state(state, connector, new_con_state, i) {
 7060
 7061		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
 7062			continue;
 7063
 7064		aconnector = to_amdgpu_dm_connector(connector);
 7065
 7066		if (!aconnector->mst_output_port)
 7067			continue;
 7068
 7069		if (!new_con_state || !new_con_state->crtc)
 7070			continue;
 7071
 7072		dm_conn_state = to_dm_connector_state(new_con_state);
 7073
 7074		for (j = 0; j < dc_state->stream_count; j++) {
 7075			stream = dc_state->streams[j];
 7076			if (!stream)
 7077				continue;
 7078
 7079			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
 7080				break;
 7081
 7082			stream = NULL;
 7083		}
 7084
 7085		if (!stream)
 7086			continue;
 7087
 7088		pbn_div = dm_mst_get_pbn_divider(stream->link);
 7089		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
 7090		for (j = 0; j < dc_state->stream_count; j++) {
 7091			if (vars[j].aconnector == aconnector) {
 7092				pbn = vars[j].pbn;
 7093				break;
 7094			}
 7095		}
 7096
 7097		if (j == dc_state->stream_count)
 7098			continue;
 7099
 7100		slot_num = DIV_ROUND_UP(pbn, pbn_div);
 7101
 7102		if (stream->timing.flags.DSC != 1) {
 7103			dm_conn_state->pbn = pbn;
 7104			dm_conn_state->vcpi_slots = slot_num;
 7105
 7106			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
 7107							   dm_conn_state->pbn, false);
 7108			if (ret < 0)
 7109				return ret;
 7110
 7111			continue;
 7112		}
 7113
 7114		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
 7115		if (vcpi < 0)
 7116			return vcpi;
 7117
 7118		dm_conn_state->pbn = pbn;
 7119		dm_conn_state->vcpi_slots = vcpi;
 7120	}
 7121	return 0;
 7122}
 7123
 7124static int to_drm_connector_type(enum signal_type st)
 7125{
 7126	switch (st) {
 7127	case SIGNAL_TYPE_HDMI_TYPE_A:
 7128		return DRM_MODE_CONNECTOR_HDMIA;
 7129	case SIGNAL_TYPE_EDP:
 7130		return DRM_MODE_CONNECTOR_eDP;
 7131	case SIGNAL_TYPE_LVDS:
 7132		return DRM_MODE_CONNECTOR_LVDS;
 7133	case SIGNAL_TYPE_RGB:
 7134		return DRM_MODE_CONNECTOR_VGA;
 7135	case SIGNAL_TYPE_DISPLAY_PORT:
 7136	case SIGNAL_TYPE_DISPLAY_PORT_MST:
 7137		return DRM_MODE_CONNECTOR_DisplayPort;
 7138	case SIGNAL_TYPE_DVI_DUAL_LINK:
 7139	case SIGNAL_TYPE_DVI_SINGLE_LINK:
 7140		return DRM_MODE_CONNECTOR_DVID;
 7141	case SIGNAL_TYPE_VIRTUAL:
 7142		return DRM_MODE_CONNECTOR_VIRTUAL;
 7143
 7144	default:
 7145		return DRM_MODE_CONNECTOR_Unknown;
 7146	}
 7147}
 7148
 7149static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
 7150{
 7151	struct drm_encoder *encoder;
 7152
 7153	/* There is only one encoder per connector */
 7154	drm_connector_for_each_possible_encoder(connector, encoder)
 7155		return encoder;
 7156
 7157	return NULL;
 7158}
 7159
 7160static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
 7161{
 7162	struct drm_encoder *encoder;
 7163	struct amdgpu_encoder *amdgpu_encoder;
 7164
 7165	encoder = amdgpu_dm_connector_to_encoder(connector);
 7166
 7167	if (encoder == NULL)
 7168		return;
 7169
 7170	amdgpu_encoder = to_amdgpu_encoder(encoder);
 7171
 7172	amdgpu_encoder->native_mode.clock = 0;
 7173
 7174	if (!list_empty(&connector->probed_modes)) {
 7175		struct drm_display_mode *preferred_mode = NULL;
 7176
 7177		list_for_each_entry(preferred_mode,
 7178				    &connector->probed_modes,
 7179				    head) {
 7180			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
 7181				amdgpu_encoder->native_mode = *preferred_mode;
 7182
 7183			break;
 7184		}
 7185
 7186	}
 7187}
 7188
 7189static struct drm_display_mode *
 7190amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
 7191			     char *name,
 7192			     int hdisplay, int vdisplay)
 7193{
 7194	struct drm_device *dev = encoder->dev;
 7195	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
 7196	struct drm_display_mode *mode = NULL;
 7197	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
 7198
 7199	mode = drm_mode_duplicate(dev, native_mode);
 7200
 7201	if (mode == NULL)
 7202		return NULL;
 7203
 7204	mode->hdisplay = hdisplay;
 7205	mode->vdisplay = vdisplay;
 7206	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
 7207	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
 7208
 7209	return mode;
 7210
 7211}
 7212
 7213static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
 7214						 struct drm_connector *connector)
 7215{
 7216	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
 7217	struct drm_display_mode *mode = NULL;
 7218	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
 7219	struct amdgpu_dm_connector *amdgpu_dm_connector =
 7220				to_amdgpu_dm_connector(connector);
 7221	int i;
 7222	int n;
 7223	struct mode_size {
 7224		char name[DRM_DISPLAY_MODE_LEN];
 7225		int w;
 7226		int h;
 7227	} common_modes[] = {
 7228		{  "640x480",  640,  480},
 7229		{  "800x600",  800,  600},
 7230		{ "1024x768", 1024,  768},
 7231		{ "1280x720", 1280,  720},
 7232		{ "1280x800", 1280,  800},
 7233		{"1280x1024", 1280, 1024},
 7234		{ "1440x900", 1440,  900},
 7235		{"1680x1050", 1680, 1050},
 7236		{"1600x1200", 1600, 1200},
 7237		{"1920x1080", 1920, 1080},
 7238		{"1920x1200", 1920, 1200}
 7239	};
 7240
 7241	n = ARRAY_SIZE(common_modes);
 7242
 7243	for (i = 0; i < n; i++) {
 7244		struct drm_display_mode *curmode = NULL;
 7245		bool mode_existed = false;
 7246
 7247		if (common_modes[i].w > native_mode->hdisplay ||
 7248		    common_modes[i].h > native_mode->vdisplay ||
 7249		   (common_modes[i].w == native_mode->hdisplay &&
 7250		    common_modes[i].h == native_mode->vdisplay))
 7251			continue;
 7252
 7253		list_for_each_entry(curmode, &connector->probed_modes, head) {
 7254			if (common_modes[i].w == curmode->hdisplay &&
 7255			    common_modes[i].h == curmode->vdisplay) {
 7256				mode_existed = true;
 7257				break;
 7258			}
 7259		}
 7260
 7261		if (mode_existed)
 7262			continue;
 7263
 7264		mode = amdgpu_dm_create_common_mode(encoder,
 7265				common_modes[i].name, common_modes[i].w,
 7266				common_modes[i].h);
 7267		if (!mode)
 7268			continue;
 7269
 7270		drm_mode_probed_add(connector, mode);
 7271		amdgpu_dm_connector->num_modes++;
 7272	}
 7273}
 7274
 7275static void amdgpu_set_panel_orientation(struct drm_connector *connector)
 7276{
 7277	struct drm_encoder *encoder;
 7278	struct amdgpu_encoder *amdgpu_encoder;
 7279	const struct drm_display_mode *native_mode;
 7280
 7281	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
 7282	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
 7283		return;
 7284
 7285	mutex_lock(&connector->dev->mode_config.mutex);
 7286	amdgpu_dm_connector_get_modes(connector);
 7287	mutex_unlock(&connector->dev->mode_config.mutex);
 7288
 7289	encoder = amdgpu_dm_connector_to_encoder(connector);
 7290	if (!encoder)
 7291		return;
 7292
 7293	amdgpu_encoder = to_amdgpu_encoder(encoder);
 7294
 7295	native_mode = &amdgpu_encoder->native_mode;
 7296	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
 7297		return;
 7298
 7299	drm_connector_set_panel_orientation_with_quirk(connector,
 7300						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
 7301						       native_mode->hdisplay,
 7302						       native_mode->vdisplay);
 7303}
 7304
 7305static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
 7306					      struct edid *edid)
 7307{
 7308	struct amdgpu_dm_connector *amdgpu_dm_connector =
 7309			to_amdgpu_dm_connector(connector);
 7310
 7311	if (edid) {
 7312		/* empty probed_modes */
 7313		INIT_LIST_HEAD(&connector->probed_modes);
 7314		amdgpu_dm_connector->num_modes =
 7315				drm_add_edid_modes(connector, edid);
 7316
 7317		/* sorting the probed modes before calling function
 7318		 * amdgpu_dm_get_native_mode() since EDID can have
 7319		 * more than one preferred mode. The modes that are
 7320		 * later in the probed mode list could be of higher
 7321		 * and preferred resolution. For example, 3840x2160
 7322		 * resolution in base EDID preferred timing and 4096x2160
 7323		 * preferred resolution in DID extension block later.
 7324		 */
 7325		drm_mode_sort(&connector->probed_modes);
 7326		amdgpu_dm_get_native_mode(connector);
 7327
 7328		/* Freesync capabilities are reset by calling
 7329		 * drm_add_edid_modes() and need to be
 7330		 * restored here.
 7331		 */
 7332		amdgpu_dm_update_freesync_caps(connector, edid);
 7333	} else {
 7334		amdgpu_dm_connector->num_modes = 0;
 7335	}
 7336}
 7337
 7338static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
 7339			      struct drm_display_mode *mode)
 7340{
 7341	struct drm_display_mode *m;
 7342
 7343	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
 7344		if (drm_mode_equal(m, mode))
 7345			return true;
 7346	}
 7347
 7348	return false;
 7349}
 7350
 7351static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
 7352{
 7353	const struct drm_display_mode *m;
 7354	struct drm_display_mode *new_mode;
 7355	uint i;
 7356	u32 new_modes_count = 0;
 7357
 7358	/* Standard FPS values
 7359	 *
 7360	 * 23.976       - TV/NTSC
 7361	 * 24           - Cinema
 7362	 * 25           - TV/PAL
 7363	 * 29.97        - TV/NTSC
 7364	 * 30           - TV/NTSC
 7365	 * 48           - Cinema HFR
 7366	 * 50           - TV/PAL
 7367	 * 60           - Commonly used
 7368	 * 48,72,96,120 - Multiples of 24
 7369	 */
 7370	static const u32 common_rates[] = {
 7371		23976, 24000, 25000, 29970, 30000,
 7372		48000, 50000, 60000, 72000, 96000, 120000
 7373	};
 7374
 7375	/*
 7376	 * Find mode with highest refresh rate with the same resolution
 7377	 * as the preferred mode. Some monitors report a preferred mode
 7378	 * with lower resolution than the highest refresh rate supported.
 7379	 */
 7380
 7381	m = get_highest_refresh_rate_mode(aconnector, true);
 7382	if (!m)
 7383		return 0;
 7384
 7385	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
 7386		u64 target_vtotal, target_vtotal_diff;
 7387		u64 num, den;
 7388
 7389		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
 7390			continue;
 7391
 7392		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
 7393		    common_rates[i] > aconnector->max_vfreq * 1000)
 7394			continue;
 7395
 7396		num = (unsigned long long)m->clock * 1000 * 1000;
 7397		den = common_rates[i] * (unsigned long long)m->htotal;
 7398		target_vtotal = div_u64(num, den);
 7399		target_vtotal_diff = target_vtotal - m->vtotal;
 7400
 7401		/* Check for illegal modes */
 7402		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
 7403		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
 7404		    m->vtotal + target_vtotal_diff < m->vsync_end)
 7405			continue;
 7406
 7407		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
 7408		if (!new_mode)
 7409			goto out;
 7410
 7411		new_mode->vtotal += (u16)target_vtotal_diff;
 7412		new_mode->vsync_start += (u16)target_vtotal_diff;
 7413		new_mode->vsync_end += (u16)target_vtotal_diff;
 7414		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
 7415		new_mode->type |= DRM_MODE_TYPE_DRIVER;
 7416
 7417		if (!is_duplicate_mode(aconnector, new_mode)) {
 7418			drm_mode_probed_add(&aconnector->base, new_mode);
 7419			new_modes_count += 1;
 7420		} else
 7421			drm_mode_destroy(aconnector->base.dev, new_mode);
 7422	}
 7423 out:
 7424	return new_modes_count;
 7425}
 7426
 7427static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
 7428						   struct edid *edid)
 7429{
 7430	struct amdgpu_dm_connector *amdgpu_dm_connector =
 7431		to_amdgpu_dm_connector(connector);
 7432
 7433	if (!edid)
 7434		return;
 7435
 7436	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
 7437		amdgpu_dm_connector->num_modes +=
 7438			add_fs_modes(amdgpu_dm_connector);
 7439}
 7440
 7441static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
 7442{
 7443	struct amdgpu_dm_connector *amdgpu_dm_connector =
 7444			to_amdgpu_dm_connector(connector);
 7445	struct drm_encoder *encoder;
 7446	struct edid *edid = amdgpu_dm_connector->edid;
 7447	struct dc_link_settings *verified_link_cap =
 7448			&amdgpu_dm_connector->dc_link->verified_link_cap;
 7449	const struct dc *dc = amdgpu_dm_connector->dc_link->dc;
 7450
 7451	encoder = amdgpu_dm_connector_to_encoder(connector);
 7452
 7453	if (!drm_edid_is_valid(edid)) {
 7454		amdgpu_dm_connector->num_modes =
 7455				drm_add_modes_noedid(connector, 640, 480);
 7456		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
 7457			amdgpu_dm_connector->num_modes +=
 7458				drm_add_modes_noedid(connector, 1920, 1080);
 7459	} else {
 7460		amdgpu_dm_connector_ddc_get_modes(connector, edid);
 7461		amdgpu_dm_connector_add_common_modes(encoder, connector);
 7462		amdgpu_dm_connector_add_freesync_modes(connector, edid);
 7463	}
 7464	amdgpu_dm_fbc_init(connector);
 7465
 7466	return amdgpu_dm_connector->num_modes;
 7467}
 7468
 7469static const u32 supported_colorspaces =
 7470	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
 7471	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
 7472	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
 7473	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
 7474
 7475void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
 7476				     struct amdgpu_dm_connector *aconnector,
 7477				     int connector_type,
 7478				     struct dc_link *link,
 7479				     int link_index)
 7480{
 7481	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
 7482
 7483	/*
 7484	 * Some of the properties below require access to state, like bpc.
 7485	 * Allocate some default initial connector state with our reset helper.
 7486	 */
 7487	if (aconnector->base.funcs->reset)
 7488		aconnector->base.funcs->reset(&aconnector->base);
 7489
 7490	aconnector->connector_id = link_index;
 7491	aconnector->bl_idx = -1;
 7492	aconnector->dc_link = link;
 7493	aconnector->base.interlace_allowed = false;
 7494	aconnector->base.doublescan_allowed = false;
 7495	aconnector->base.stereo_allowed = false;
 7496	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
 7497	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
 7498	aconnector->audio_inst = -1;
 7499	aconnector->pack_sdp_v1_3 = false;
 7500	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
 7501	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
 7502	mutex_init(&aconnector->hpd_lock);
 7503	mutex_init(&aconnector->handle_mst_msg_ready);
 7504
 7505	/*
 7506	 * configure support HPD hot plug connector_>polled default value is 0
 7507	 * which means HPD hot plug not supported
 7508	 */
 7509	switch (connector_type) {
 7510	case DRM_MODE_CONNECTOR_HDMIA:
 7511		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
 7512		aconnector->base.ycbcr_420_allowed =
 7513			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
 7514		break;
 7515	case DRM_MODE_CONNECTOR_DisplayPort:
 7516		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
 7517		link->link_enc = link_enc_cfg_get_link_enc(link);
 7518		ASSERT(link->link_enc);
 7519		if (link->link_enc)
 7520			aconnector->base.ycbcr_420_allowed =
 7521			link->link_enc->features.dp_ycbcr420_supported ? true : false;
 7522		break;
 7523	case DRM_MODE_CONNECTOR_DVID:
 7524		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
 7525		break;
 7526	default:
 7527		break;
 7528	}
 7529
 7530	drm_object_attach_property(&aconnector->base.base,
 7531				dm->ddev->mode_config.scaling_mode_property,
 7532				DRM_MODE_SCALE_NONE);
 7533
 7534	drm_object_attach_property(&aconnector->base.base,
 7535				adev->mode_info.underscan_property,
 7536				UNDERSCAN_OFF);
 7537	drm_object_attach_property(&aconnector->base.base,
 7538				adev->mode_info.underscan_hborder_property,
 7539				0);
 7540	drm_object_attach_property(&aconnector->base.base,
 7541				adev->mode_info.underscan_vborder_property,
 7542				0);
 7543
 7544	if (!aconnector->mst_root)
 7545		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
 7546
 7547	aconnector->base.state->max_bpc = 16;
 7548	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
 7549
 7550	if (connector_type == DRM_MODE_CONNECTOR_eDP &&
 7551	    (dc_is_dmcu_initialized(adev->dm.dc) || adev->dm.dc->ctx->dmub_srv)) {
 7552		drm_object_attach_property(&aconnector->base.base,
 7553				adev->mode_info.abm_level_property, 0);
 7554	}
 7555
 7556	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
 7557		/* Content Type is currently only implemented for HDMI. */
 7558		drm_connector_attach_content_type_property(&aconnector->base);
 7559	}
 7560
 7561	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
 7562		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
 7563			drm_connector_attach_colorspace_property(&aconnector->base);
 7564	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
 7565		   connector_type == DRM_MODE_CONNECTOR_eDP) {
 7566		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
 7567			drm_connector_attach_colorspace_property(&aconnector->base);
 7568	}
 7569
 7570	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
 7571	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
 7572	    connector_type == DRM_MODE_CONNECTOR_eDP) {
 7573		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
 7574
 7575		if (!aconnector->mst_root)
 7576			drm_connector_attach_vrr_capable_property(&aconnector->base);
 7577
 7578		if (adev->dm.hdcp_workqueue)
 7579			drm_connector_attach_content_protection_property(&aconnector->base, true);
 7580	}
 7581}
 7582
 7583static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
 7584			      struct i2c_msg *msgs, int num)
 7585{
 7586	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
 7587	struct ddc_service *ddc_service = i2c->ddc_service;
 7588	struct i2c_command cmd;
 7589	int i;
 7590	int result = -EIO;
 7591
 7592	if (!ddc_service->ddc_pin || !ddc_service->ddc_pin->hw_info.hw_supported)
 7593		return result;
 7594
 7595	cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
 7596
 7597	if (!cmd.payloads)
 7598		return result;
 7599
 7600	cmd.number_of_payloads = num;
 7601	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
 7602	cmd.speed = 100;
 7603
 7604	for (i = 0; i < num; i++) {
 7605		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
 7606		cmd.payloads[i].address = msgs[i].addr;
 7607		cmd.payloads[i].length = msgs[i].len;
 7608		cmd.payloads[i].data = msgs[i].buf;
 7609	}
 7610
 7611	if (dc_submit_i2c(
 7612			ddc_service->ctx->dc,
 7613			ddc_service->link->link_index,
 7614			&cmd))
 7615		result = num;
 7616
 7617	kfree(cmd.payloads);
 7618	return result;
 7619}
 7620
 7621static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
 7622{
 7623	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
 7624}
 7625
 7626static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
 7627	.master_xfer = amdgpu_dm_i2c_xfer,
 7628	.functionality = amdgpu_dm_i2c_func,
 7629};
 7630
 7631static struct amdgpu_i2c_adapter *
 7632create_i2c(struct ddc_service *ddc_service,
 7633	   int link_index,
 7634	   int *res)
 7635{
 7636	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
 7637	struct amdgpu_i2c_adapter *i2c;
 7638
 7639	i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
 7640	if (!i2c)
 7641		return NULL;
 7642	i2c->base.owner = THIS_MODULE;
 7643	i2c->base.dev.parent = &adev->pdev->dev;
 7644	i2c->base.algo = &amdgpu_dm_i2c_algo;
 7645	snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
 7646	i2c_set_adapdata(&i2c->base, i2c);
 7647	i2c->ddc_service = ddc_service;
 7648
 7649	return i2c;
 7650}
 7651
 7652
 7653/*
 7654 * Note: this function assumes that dc_link_detect() was called for the
 7655 * dc_link which will be represented by this aconnector.
 7656 */
 7657static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
 7658				    struct amdgpu_dm_connector *aconnector,
 7659				    u32 link_index,
 7660				    struct amdgpu_encoder *aencoder)
 7661{
 7662	int res = 0;
 7663	int connector_type;
 7664	struct dc *dc = dm->dc;
 7665	struct dc_link *link = dc_get_link_at_index(dc, link_index);
 7666	struct amdgpu_i2c_adapter *i2c;
 7667
 7668	/* Not needed for writeback connector */
 7669	link->priv = aconnector;
 7670
 7671
 7672	i2c = create_i2c(link->ddc, link->link_index, &res);
 7673	if (!i2c) {
 7674		DRM_ERROR("Failed to create i2c adapter data\n");
 7675		return -ENOMEM;
 7676	}
 7677
 7678	aconnector->i2c = i2c;
 7679	res = i2c_add_adapter(&i2c->base);
 7680
 7681	if (res) {
 7682		DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
 7683		goto out_free;
 7684	}
 7685
 7686	connector_type = to_drm_connector_type(link->connector_signal);
 7687
 7688	res = drm_connector_init_with_ddc(
 7689			dm->ddev,
 7690			&aconnector->base,
 7691			&amdgpu_dm_connector_funcs,
 7692			connector_type,
 7693			&i2c->base);
 7694
 7695	if (res) {
 7696		DRM_ERROR("connector_init failed\n");
 7697		aconnector->connector_id = -1;
 7698		goto out_free;
 7699	}
 7700
 7701	drm_connector_helper_add(
 7702			&aconnector->base,
 7703			&amdgpu_dm_connector_helper_funcs);
 7704
 7705	amdgpu_dm_connector_init_helper(
 7706		dm,
 7707		aconnector,
 7708		connector_type,
 7709		link,
 7710		link_index);
 7711
 7712	drm_connector_attach_encoder(
 7713		&aconnector->base, &aencoder->base);
 7714
 7715	if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
 7716		|| connector_type == DRM_MODE_CONNECTOR_eDP)
 7717		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
 7718
 7719out_free:
 7720	if (res) {
 7721		kfree(i2c);
 7722		aconnector->i2c = NULL;
 7723	}
 7724	return res;
 7725}
 7726
 7727int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
 7728{
 7729	switch (adev->mode_info.num_crtc) {
 7730	case 1:
 7731		return 0x1;
 7732	case 2:
 7733		return 0x3;
 7734	case 3:
 7735		return 0x7;
 7736	case 4:
 7737		return 0xf;
 7738	case 5:
 7739		return 0x1f;
 7740	case 6:
 7741	default:
 7742		return 0x3f;
 7743	}
 7744}
 7745
 7746static int amdgpu_dm_encoder_init(struct drm_device *dev,
 7747				  struct amdgpu_encoder *aencoder,
 7748				  uint32_t link_index)
 7749{
 7750	struct amdgpu_device *adev = drm_to_adev(dev);
 7751
 7752	int res = drm_encoder_init(dev,
 7753				   &aencoder->base,
 7754				   &amdgpu_dm_encoder_funcs,
 7755				   DRM_MODE_ENCODER_TMDS,
 7756				   NULL);
 7757
 7758	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
 7759
 7760	if (!res)
 7761		aencoder->encoder_id = link_index;
 7762	else
 7763		aencoder->encoder_id = -1;
 7764
 7765	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
 7766
 7767	return res;
 7768}
 7769
 7770static void manage_dm_interrupts(struct amdgpu_device *adev,
 7771				 struct amdgpu_crtc *acrtc,
 7772				 bool enable)
 7773{
 7774	/*
 7775	 * We have no guarantee that the frontend index maps to the same
 7776	 * backend index - some even map to more than one.
 7777	 *
 7778	 * TODO: Use a different interrupt or check DC itself for the mapping.
 7779	 */
 7780	int irq_type =
 7781		amdgpu_display_crtc_idx_to_irq_type(
 7782			adev,
 7783			acrtc->crtc_id);
 7784
 7785	if (enable) {
 7786		drm_crtc_vblank_on(&acrtc->base);
 7787		amdgpu_irq_get(
 7788			adev,
 7789			&adev->pageflip_irq,
 7790			irq_type);
 7791#if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
 7792		amdgpu_irq_get(
 7793			adev,
 7794			&adev->vline0_irq,
 7795			irq_type);
 7796#endif
 7797	} else {
 7798#if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
 7799		amdgpu_irq_put(
 7800			adev,
 7801			&adev->vline0_irq,
 7802			irq_type);
 7803#endif
 7804		amdgpu_irq_put(
 7805			adev,
 7806			&adev->pageflip_irq,
 7807			irq_type);
 7808		drm_crtc_vblank_off(&acrtc->base);
 7809	}
 7810}
 7811
 7812static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
 7813				      struct amdgpu_crtc *acrtc)
 7814{
 7815	int irq_type =
 7816		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
 7817
 7818	/**
 7819	 * This reads the current state for the IRQ and force reapplies
 7820	 * the setting to hardware.
 7821	 */
 7822	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
 7823}
 7824
 7825static bool
 7826is_scaling_state_different(const struct dm_connector_state *dm_state,
 7827			   const struct dm_connector_state *old_dm_state)
 7828{
 7829	if (dm_state->scaling != old_dm_state->scaling)
 7830		return true;
 7831	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
 7832		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
 7833			return true;
 7834	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
 7835		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
 7836			return true;
 7837	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
 7838		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
 7839		return true;
 7840	return false;
 7841}
 7842
 7843static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
 7844					    struct drm_crtc_state *old_crtc_state,
 7845					    struct drm_connector_state *new_conn_state,
 7846					    struct drm_connector_state *old_conn_state,
 7847					    const struct drm_connector *connector,
 7848					    struct hdcp_workqueue *hdcp_w)
 7849{
 7850	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
 7851	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
 7852
 7853	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
 7854		connector->index, connector->status, connector->dpms);
 7855	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
 7856		old_conn_state->content_protection, new_conn_state->content_protection);
 7857
 7858	if (old_crtc_state)
 7859		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
 7860		old_crtc_state->enable,
 7861		old_crtc_state->active,
 7862		old_crtc_state->mode_changed,
 7863		old_crtc_state->active_changed,
 7864		old_crtc_state->connectors_changed);
 7865
 7866	if (new_crtc_state)
 7867		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
 7868		new_crtc_state->enable,
 7869		new_crtc_state->active,
 7870		new_crtc_state->mode_changed,
 7871		new_crtc_state->active_changed,
 7872		new_crtc_state->connectors_changed);
 7873
 7874	/* hdcp content type change */
 7875	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
 7876	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
 7877		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
 7878		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
 7879		return true;
 7880	}
 7881
 7882	/* CP is being re enabled, ignore this */
 7883	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
 7884	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
 7885		if (new_crtc_state && new_crtc_state->mode_changed) {
 7886			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
 7887			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
 7888			return true;
 7889		}
 7890		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
 7891		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
 7892		return false;
 7893	}
 7894
 7895	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
 7896	 *
 7897	 * Handles:	UNDESIRED -> ENABLED
 7898	 */
 7899	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
 7900	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
 7901		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
 7902
 7903	/* Stream removed and re-enabled
 7904	 *
 7905	 * Can sometimes overlap with the HPD case,
 7906	 * thus set update_hdcp to false to avoid
 7907	 * setting HDCP multiple times.
 7908	 *
 7909	 * Handles:	DESIRED -> DESIRED (Special case)
 7910	 */
 7911	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
 7912		new_conn_state->crtc && new_conn_state->crtc->enabled &&
 7913		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
 7914		dm_con_state->update_hdcp = false;
 7915		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
 7916			__func__);
 7917		return true;
 7918	}
 7919
 7920	/* Hot-plug, headless s3, dpms
 7921	 *
 7922	 * Only start HDCP if the display is connected/enabled.
 7923	 * update_hdcp flag will be set to false until the next
 7924	 * HPD comes in.
 7925	 *
 7926	 * Handles:	DESIRED -> DESIRED (Special case)
 7927	 */
 7928	if (dm_con_state->update_hdcp &&
 7929	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
 7930	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
 7931		dm_con_state->update_hdcp = false;
 7932		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
 7933			__func__);
 7934		return true;
 7935	}
 7936
 7937	if (old_conn_state->content_protection == new_conn_state->content_protection) {
 7938		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
 7939			if (new_crtc_state && new_crtc_state->mode_changed) {
 7940				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
 7941					__func__);
 7942				return true;
 7943			}
 7944			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
 7945				__func__);
 7946			return false;
 7947		}
 7948
 7949		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
 7950		return false;
 7951	}
 7952
 7953	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
 7954		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
 7955			__func__);
 7956		return true;
 7957	}
 7958
 7959	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
 7960	return false;
 7961}
 7962
 7963static void remove_stream(struct amdgpu_device *adev,
 7964			  struct amdgpu_crtc *acrtc,
 7965			  struct dc_stream_state *stream)
 7966{
 7967	/* this is the update mode case */
 7968
 7969	acrtc->otg_inst = -1;
 7970	acrtc->enabled = false;
 7971}
 7972
 7973static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
 7974{
 7975
 7976	assert_spin_locked(&acrtc->base.dev->event_lock);
 7977	WARN_ON(acrtc->event);
 7978
 7979	acrtc->event = acrtc->base.state->event;
 7980
 7981	/* Set the flip status */
 7982	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
 7983
 7984	/* Mark this event as consumed */
 7985	acrtc->base.state->event = NULL;
 7986
 7987	drm_dbg_state(acrtc->base.dev,
 7988		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
 7989		      acrtc->crtc_id);
 7990}
 7991
 7992static void update_freesync_state_on_stream(
 7993	struct amdgpu_display_manager *dm,
 7994	struct dm_crtc_state *new_crtc_state,
 7995	struct dc_stream_state *new_stream,
 7996	struct dc_plane_state *surface,
 7997	u32 flip_timestamp_in_us)
 7998{
 7999	struct mod_vrr_params vrr_params;
 8000	struct dc_info_packet vrr_infopacket = {0};
 8001	struct amdgpu_device *adev = dm->adev;
 8002	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
 8003	unsigned long flags;
 8004	bool pack_sdp_v1_3 = false;
 8005	struct amdgpu_dm_connector *aconn;
 8006	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
 8007
 8008	if (!new_stream)
 8009		return;
 8010
 8011	/*
 8012	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
 8013	 * For now it's sufficient to just guard against these conditions.
 8014	 */
 8015
 8016	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
 8017		return;
 8018
 8019	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
 8020	vrr_params = acrtc->dm_irq_params.vrr_params;
 8021
 8022	if (surface) {
 8023		mod_freesync_handle_preflip(
 8024			dm->freesync_module,
 8025			surface,
 8026			new_stream,
 8027			flip_timestamp_in_us,
 8028			&vrr_params);
 8029
 8030		if (adev->family < AMDGPU_FAMILY_AI &&
 8031		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
 8032			mod_freesync_handle_v_update(dm->freesync_module,
 8033						     new_stream, &vrr_params);
 8034
 8035			/* Need to call this before the frame ends. */
 8036			dc_stream_adjust_vmin_vmax(dm->dc,
 8037						   new_crtc_state->stream,
 8038						   &vrr_params.adjust);
 8039		}
 8040	}
 8041
 8042	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
 8043
 8044	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
 8045		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
 8046
 8047		if (aconn->vsdb_info.amd_vsdb_version == 1)
 8048			packet_type = PACKET_TYPE_FS_V1;
 8049		else if (aconn->vsdb_info.amd_vsdb_version == 2)
 8050			packet_type = PACKET_TYPE_FS_V2;
 8051		else if (aconn->vsdb_info.amd_vsdb_version == 3)
 8052			packet_type = PACKET_TYPE_FS_V3;
 8053
 8054		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
 8055					&new_stream->adaptive_sync_infopacket);
 8056	}
 8057
 8058	mod_freesync_build_vrr_infopacket(
 8059		dm->freesync_module,
 8060		new_stream,
 8061		&vrr_params,
 8062		packet_type,
 8063		TRANSFER_FUNC_UNKNOWN,
 8064		&vrr_infopacket,
 8065		pack_sdp_v1_3);
 8066
 8067	new_crtc_state->freesync_vrr_info_changed |=
 8068		(memcmp(&new_crtc_state->vrr_infopacket,
 8069			&vrr_infopacket,
 8070			sizeof(vrr_infopacket)) != 0);
 8071
 8072	acrtc->dm_irq_params.vrr_params = vrr_params;
 8073	new_crtc_state->vrr_infopacket = vrr_infopacket;
 8074
 8075	new_stream->vrr_infopacket = vrr_infopacket;
 8076	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
 8077
 8078	if (new_crtc_state->freesync_vrr_info_changed)
 8079		DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
 8080			      new_crtc_state->base.crtc->base.id,
 8081			      (int)new_crtc_state->base.vrr_enabled,
 8082			      (int)vrr_params.state);
 8083
 8084	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
 8085}
 8086
 8087static void update_stream_irq_parameters(
 8088	struct amdgpu_display_manager *dm,
 8089	struct dm_crtc_state *new_crtc_state)
 8090{
 8091	struct dc_stream_state *new_stream = new_crtc_state->stream;
 8092	struct mod_vrr_params vrr_params;
 8093	struct mod_freesync_config config = new_crtc_state->freesync_config;
 8094	struct amdgpu_device *adev = dm->adev;
 8095	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
 8096	unsigned long flags;
 8097
 8098	if (!new_stream)
 8099		return;
 8100
 8101	/*
 8102	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
 8103	 * For now it's sufficient to just guard against these conditions.
 8104	 */
 8105	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
 8106		return;
 8107
 8108	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
 8109	vrr_params = acrtc->dm_irq_params.vrr_params;
 8110
 8111	if (new_crtc_state->vrr_supported &&
 8112	    config.min_refresh_in_uhz &&
 8113	    config.max_refresh_in_uhz) {
 8114		/*
 8115		 * if freesync compatible mode was set, config.state will be set
 8116		 * in atomic check
 8117		 */
 8118		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
 8119		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
 8120		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
 8121			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
 8122			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
 8123			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
 8124			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
 8125		} else {
 8126			config.state = new_crtc_state->base.vrr_enabled ?
 8127						     VRR_STATE_ACTIVE_VARIABLE :
 8128						     VRR_STATE_INACTIVE;
 8129		}
 8130	} else {
 8131		config.state = VRR_STATE_UNSUPPORTED;
 8132	}
 8133
 8134	mod_freesync_build_vrr_params(dm->freesync_module,
 8135				      new_stream,
 8136				      &config, &vrr_params);
 8137
 8138	new_crtc_state->freesync_config = config;
 8139	/* Copy state for access from DM IRQ handler */
 8140	acrtc->dm_irq_params.freesync_config = config;
 8141	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
 8142	acrtc->dm_irq_params.vrr_params = vrr_params;
 8143	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
 8144}
 8145
 8146static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
 8147					    struct dm_crtc_state *new_state)
 8148{
 8149	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
 8150	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
 8151
 8152	if (!old_vrr_active && new_vrr_active) {
 8153		/* Transition VRR inactive -> active:
 8154		 * While VRR is active, we must not disable vblank irq, as a
 8155		 * reenable after disable would compute bogus vblank/pflip
 8156		 * timestamps if it likely happened inside display front-porch.
 8157		 *
 8158		 * We also need vupdate irq for the actual core vblank handling
 8159		 * at end of vblank.
 8160		 */
 8161		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
 8162		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
 8163		DRM_DEBUG_DRIVER("%s: crtc=%u VRR off->on: Get vblank ref\n",
 8164				 __func__, new_state->base.crtc->base.id);
 8165	} else if (old_vrr_active && !new_vrr_active) {
 8166		/* Transition VRR active -> inactive:
 8167		 * Allow vblank irq disable again for fixed refresh rate.
 8168		 */
 8169		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
 8170		drm_crtc_vblank_put(new_state->base.crtc);
 8171		DRM_DEBUG_DRIVER("%s: crtc=%u VRR on->off: Drop vblank ref\n",
 8172				 __func__, new_state->base.crtc->base.id);
 8173	}
 8174}
 8175
 8176static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
 8177{
 8178	struct drm_plane *plane;
 8179	struct drm_plane_state *old_plane_state;
 8180	int i;
 8181
 8182	/*
 8183	 * TODO: Make this per-stream so we don't issue redundant updates for
 8184	 * commits with multiple streams.
 8185	 */
 8186	for_each_old_plane_in_state(state, plane, old_plane_state, i)
 8187		if (plane->type == DRM_PLANE_TYPE_CURSOR)
 8188			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
 8189}
 8190
 8191static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
 8192{
 8193	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
 8194
 8195	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
 8196}
 8197
 8198static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
 8199				    struct drm_device *dev,
 8200				    struct amdgpu_display_manager *dm,
 8201				    struct drm_crtc *pcrtc,
 8202				    bool wait_for_vblank)
 8203{
 8204	u32 i;
 8205	u64 timestamp_ns = ktime_get_ns();
 8206	struct drm_plane *plane;
 8207	struct drm_plane_state *old_plane_state, *new_plane_state;
 8208	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
 8209	struct drm_crtc_state *new_pcrtc_state =
 8210			drm_atomic_get_new_crtc_state(state, pcrtc);
 8211	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
 8212	struct dm_crtc_state *dm_old_crtc_state =
 8213			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
 8214	int planes_count = 0, vpos, hpos;
 8215	unsigned long flags;
 8216	u32 target_vblank, last_flip_vblank;
 8217	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
 8218	bool cursor_update = false;
 8219	bool pflip_present = false;
 8220	bool dirty_rects_changed = false;
 8221	struct {
 8222		struct dc_surface_update surface_updates[MAX_SURFACES];
 8223		struct dc_plane_info plane_infos[MAX_SURFACES];
 8224		struct dc_scaling_info scaling_infos[MAX_SURFACES];
 8225		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
 8226		struct dc_stream_update stream_update;
 8227	} *bundle;
 8228
 8229	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
 8230
 8231	if (!bundle) {
 8232		drm_err(dev, "Failed to allocate update bundle\n");
 8233		goto cleanup;
 8234	}
 8235
 8236	/*
 8237	 * Disable the cursor first if we're disabling all the planes.
 8238	 * It'll remain on the screen after the planes are re-enabled
 8239	 * if we don't.
 8240	 */
 8241	if (acrtc_state->active_planes == 0)
 8242		amdgpu_dm_commit_cursors(state);
 8243
 8244	/* update planes when needed */
 8245	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
 8246		struct drm_crtc *crtc = new_plane_state->crtc;
 8247		struct drm_crtc_state *new_crtc_state;
 8248		struct drm_framebuffer *fb = new_plane_state->fb;
 8249		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
 8250		bool plane_needs_flip;
 8251		struct dc_plane_state *dc_plane;
 8252		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
 8253
 8254		/* Cursor plane is handled after stream updates */
 8255		if (plane->type == DRM_PLANE_TYPE_CURSOR) {
 8256			if ((fb && crtc == pcrtc) ||
 8257			    (old_plane_state->fb && old_plane_state->crtc == pcrtc))
 8258				cursor_update = true;
 8259
 8260			continue;
 8261		}
 8262
 8263		if (!fb || !crtc || pcrtc != crtc)
 8264			continue;
 8265
 8266		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
 8267		if (!new_crtc_state->active)
 8268			continue;
 8269
 8270		dc_plane = dm_new_plane_state->dc_state;
 8271		if (!dc_plane)
 8272			continue;
 8273
 8274		bundle->surface_updates[planes_count].surface = dc_plane;
 8275		if (new_pcrtc_state->color_mgmt_changed) {
 8276			bundle->surface_updates[planes_count].gamma = dc_plane->gamma_correction;
 8277			bundle->surface_updates[planes_count].in_transfer_func = dc_plane->in_transfer_func;
 8278			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
 8279			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
 8280			bundle->surface_updates[planes_count].func_shaper = dc_plane->in_shaper_func;
 8281			bundle->surface_updates[planes_count].lut3d_func = dc_plane->lut3d_func;
 8282			bundle->surface_updates[planes_count].blend_tf = dc_plane->blend_tf;
 8283		}
 8284
 8285		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
 8286				     &bundle->scaling_infos[planes_count]);
 8287
 8288		bundle->surface_updates[planes_count].scaling_info =
 8289			&bundle->scaling_infos[planes_count];
 8290
 8291		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
 8292
 8293		pflip_present = pflip_present || plane_needs_flip;
 8294
 8295		if (!plane_needs_flip) {
 8296			planes_count += 1;
 8297			continue;
 8298		}
 8299
 8300		fill_dc_plane_info_and_addr(
 8301			dm->adev, new_plane_state,
 8302			afb->tiling_flags,
 8303			&bundle->plane_infos[planes_count],
 8304			&bundle->flip_addrs[planes_count].address,
 8305			afb->tmz_surface, false);
 8306
 8307		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
 8308				 new_plane_state->plane->index,
 8309				 bundle->plane_infos[planes_count].dcc.enable);
 8310
 8311		bundle->surface_updates[planes_count].plane_info =
 8312			&bundle->plane_infos[planes_count];
 8313
 8314		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
 8315		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
 8316			fill_dc_dirty_rects(plane, old_plane_state,
 8317					    new_plane_state, new_crtc_state,
 8318					    &bundle->flip_addrs[planes_count],
 8319					    acrtc_state->stream->link->psr_settings.psr_version ==
 8320					    DC_PSR_VERSION_SU_1,
 8321					    &dirty_rects_changed);
 8322
 8323			/*
 8324			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
 8325			 * and enabled it again after dirty regions are stable to avoid video glitch.
 8326			 * PSR-SU will be enabled in vblank_control_worker() if user pause the video
 8327			 * during the PSR-SU was disabled.
 8328			 */
 8329			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
 8330			    acrtc_attach->dm_irq_params.allow_psr_entry &&
 8331#ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
 8332			    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
 8333#endif
 8334			    dirty_rects_changed) {
 8335				mutex_lock(&dm->dc_lock);
 8336				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
 8337				timestamp_ns;
 8338				if (acrtc_state->stream->link->psr_settings.psr_allow_active)
 8339					amdgpu_dm_psr_disable(acrtc_state->stream);
 8340				mutex_unlock(&dm->dc_lock);
 8341			}
 8342		}
 8343
 8344		/*
 8345		 * Only allow immediate flips for fast updates that don't
 8346		 * change memory domain, FB pitch, DCC state, rotation or
 8347		 * mirroring.
 8348		 *
 8349		 * dm_crtc_helper_atomic_check() only accepts async flips with
 8350		 * fast updates.
 8351		 */
 8352		if (crtc->state->async_flip &&
 8353		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
 8354		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
 8355			drm_warn_once(state->dev,
 8356				      "[PLANE:%d:%s] async flip with non-fast update\n",
 8357				      plane->base.id, plane->name);
 8358
 8359		bundle->flip_addrs[planes_count].flip_immediate =
 8360			crtc->state->async_flip &&
 8361			acrtc_state->update_type == UPDATE_TYPE_FAST &&
 8362			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
 8363
 8364		timestamp_ns = ktime_get_ns();
 8365		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
 8366		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
 8367		bundle->surface_updates[planes_count].surface = dc_plane;
 8368
 8369		if (!bundle->surface_updates[planes_count].surface) {
 8370			DRM_ERROR("No surface for CRTC: id=%d\n",
 8371					acrtc_attach->crtc_id);
 8372			continue;
 8373		}
 8374
 8375		if (plane == pcrtc->primary)
 8376			update_freesync_state_on_stream(
 8377				dm,
 8378				acrtc_state,
 8379				acrtc_state->stream,
 8380				dc_plane,
 8381				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
 8382
 8383		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
 8384				 __func__,
 8385				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
 8386				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
 8387
 8388		planes_count += 1;
 8389
 8390	}
 8391
 8392	if (pflip_present) {
 8393		if (!vrr_active) {
 8394			/* Use old throttling in non-vrr fixed refresh rate mode
 8395			 * to keep flip scheduling based on target vblank counts
 8396			 * working in a backwards compatible way, e.g., for
 8397			 * clients using the GLX_OML_sync_control extension or
 8398			 * DRI3/Present extension with defined target_msc.
 8399			 */
 8400			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
 8401		} else {
 8402			/* For variable refresh rate mode only:
 8403			 * Get vblank of last completed flip to avoid > 1 vrr
 8404			 * flips per video frame by use of throttling, but allow
 8405			 * flip programming anywhere in the possibly large
 8406			 * variable vrr vblank interval for fine-grained flip
 8407			 * timing control and more opportunity to avoid stutter
 8408			 * on late submission of flips.
 8409			 */
 8410			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
 8411			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
 8412			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
 8413		}
 8414
 8415		target_vblank = last_flip_vblank + wait_for_vblank;
 8416
 8417		/*
 8418		 * Wait until we're out of the vertical blank period before the one
 8419		 * targeted by the flip
 8420		 */
 8421		while ((acrtc_attach->enabled &&
 8422			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
 8423							    0, &vpos, &hpos, NULL,
 8424							    NULL, &pcrtc->hwmode)
 8425			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
 8426			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
 8427			(int)(target_vblank -
 8428			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
 8429			usleep_range(1000, 1100);
 8430		}
 8431
 8432		/**
 8433		 * Prepare the flip event for the pageflip interrupt to handle.
 8434		 *
 8435		 * This only works in the case where we've already turned on the
 8436		 * appropriate hardware blocks (eg. HUBP) so in the transition case
 8437		 * from 0 -> n planes we have to skip a hardware generated event
 8438		 * and rely on sending it from software.
 8439		 */
 8440		if (acrtc_attach->base.state->event &&
 8441		    acrtc_state->active_planes > 0) {
 8442			drm_crtc_vblank_get(pcrtc);
 8443
 8444			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
 8445
 8446			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
 8447			prepare_flip_isr(acrtc_attach);
 8448
 8449			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
 8450		}
 8451
 8452		if (acrtc_state->stream) {
 8453			if (acrtc_state->freesync_vrr_info_changed)
 8454				bundle->stream_update.vrr_infopacket =
 8455					&acrtc_state->stream->vrr_infopacket;
 8456		}
 8457	} else if (cursor_update && acrtc_state->active_planes > 0 &&
 8458		   acrtc_attach->base.state->event) {
 8459		drm_crtc_vblank_get(pcrtc);
 8460
 8461		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
 8462
 8463		acrtc_attach->event = acrtc_attach->base.state->event;
 8464		acrtc_attach->base.state->event = NULL;
 8465
 8466		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
 8467	}
 8468
 8469	/* Update the planes if changed or disable if we don't have any. */
 8470	if ((planes_count || acrtc_state->active_planes == 0) &&
 8471		acrtc_state->stream) {
 8472		/*
 8473		 * If PSR or idle optimizations are enabled then flush out
 8474		 * any pending work before hardware programming.
 8475		 */
 8476		if (dm->vblank_control_workqueue)
 8477			flush_workqueue(dm->vblank_control_workqueue);
 8478
 8479		bundle->stream_update.stream = acrtc_state->stream;
 8480		if (new_pcrtc_state->mode_changed) {
 8481			bundle->stream_update.src = acrtc_state->stream->src;
 8482			bundle->stream_update.dst = acrtc_state->stream->dst;
 8483		}
 8484
 8485		if (new_pcrtc_state->color_mgmt_changed) {
 8486			/*
 8487			 * TODO: This isn't fully correct since we've actually
 8488			 * already modified the stream in place.
 8489			 */
 8490			bundle->stream_update.gamut_remap =
 8491				&acrtc_state->stream->gamut_remap_matrix;
 8492			bundle->stream_update.output_csc_transform =
 8493				&acrtc_state->stream->csc_color_matrix;
 8494			bundle->stream_update.out_transfer_func =
 8495				acrtc_state->stream->out_transfer_func;
 8496			bundle->stream_update.lut3d_func =
 8497				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
 8498			bundle->stream_update.func_shaper =
 8499				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
 8500		}
 8501
 8502		acrtc_state->stream->abm_level = acrtc_state->abm_level;
 8503		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
 8504			bundle->stream_update.abm_level = &acrtc_state->abm_level;
 8505
 8506		mutex_lock(&dm->dc_lock);
 8507		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
 8508				acrtc_state->stream->link->psr_settings.psr_allow_active)
 8509			amdgpu_dm_psr_disable(acrtc_state->stream);
 8510		mutex_unlock(&dm->dc_lock);
 8511
 8512		/*
 8513		 * If FreeSync state on the stream has changed then we need to
 8514		 * re-adjust the min/max bounds now that DC doesn't handle this
 8515		 * as part of commit.
 8516		 */
 8517		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
 8518			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
 8519			dc_stream_adjust_vmin_vmax(
 8520				dm->dc, acrtc_state->stream,
 8521				&acrtc_attach->dm_irq_params.vrr_params.adjust);
 8522			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
 8523		}
 8524		mutex_lock(&dm->dc_lock);
 8525		update_planes_and_stream_adapter(dm->dc,
 8526					 acrtc_state->update_type,
 8527					 planes_count,
 8528					 acrtc_state->stream,
 8529					 &bundle->stream_update,
 8530					 bundle->surface_updates);
 8531
 8532		/**
 8533		 * Enable or disable the interrupts on the backend.
 8534		 *
 8535		 * Most pipes are put into power gating when unused.
 8536		 *
 8537		 * When power gating is enabled on a pipe we lose the
 8538		 * interrupt enablement state when power gating is disabled.
 8539		 *
 8540		 * So we need to update the IRQ control state in hardware
 8541		 * whenever the pipe turns on (since it could be previously
 8542		 * power gated) or off (since some pipes can't be power gated
 8543		 * on some ASICs).
 8544		 */
 8545		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
 8546			dm_update_pflip_irq_state(drm_to_adev(dev),
 8547						  acrtc_attach);
 8548
 8549		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
 8550				acrtc_state->stream->link->psr_settings.psr_version != DC_PSR_VERSION_UNSUPPORTED &&
 8551				!acrtc_state->stream->link->psr_settings.psr_feature_enabled)
 8552			amdgpu_dm_link_setup_psr(acrtc_state->stream);
 8553
 8554		/* Decrement skip count when PSR is enabled and we're doing fast updates. */
 8555		if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
 8556		    acrtc_state->stream->link->psr_settings.psr_feature_enabled) {
 8557			struct amdgpu_dm_connector *aconn =
 8558				(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
 8559
 8560			if (aconn->psr_skip_count > 0)
 8561				aconn->psr_skip_count--;
 8562
 8563			/* Allow PSR when skip count is 0. */
 8564			acrtc_attach->dm_irq_params.allow_psr_entry = !aconn->psr_skip_count;
 8565
 8566			/*
 8567			 * If sink supports PSR SU, there is no need to rely on
 8568			 * a vblank event disable request to enable PSR. PSR SU
 8569			 * can be enabled immediately once OS demonstrates an
 8570			 * adequate number of fast atomic commits to notify KMD
 8571			 * of update events. See `vblank_control_worker()`.
 8572			 */
 8573			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
 8574			    acrtc_attach->dm_irq_params.allow_psr_entry &&
 8575#ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
 8576			    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
 8577#endif
 8578			    !acrtc_state->stream->link->psr_settings.psr_allow_active &&
 8579			    (timestamp_ns -
 8580			    acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns) >
 8581			    500000000)
 8582				amdgpu_dm_psr_enable(acrtc_state->stream);
 8583		} else {
 8584			acrtc_attach->dm_irq_params.allow_psr_entry = false;
 8585		}
 8586
 8587		mutex_unlock(&dm->dc_lock);
 8588	}
 8589
 8590	/*
 8591	 * Update cursor state *after* programming all the planes.
 8592	 * This avoids redundant programming in the case where we're going
 8593	 * to be disabling a single plane - those pipes are being disabled.
 8594	 */
 8595	if (acrtc_state->active_planes)
 8596		amdgpu_dm_commit_cursors(state);
 8597
 8598cleanup:
 8599	kfree(bundle);
 8600}
 8601
 8602static void amdgpu_dm_commit_audio(struct drm_device *dev,
 8603				   struct drm_atomic_state *state)
 8604{
 8605	struct amdgpu_device *adev = drm_to_adev(dev);
 8606	struct amdgpu_dm_connector *aconnector;
 8607	struct drm_connector *connector;
 8608	struct drm_connector_state *old_con_state, *new_con_state;
 8609	struct drm_crtc_state *new_crtc_state;
 8610	struct dm_crtc_state *new_dm_crtc_state;
 8611	const struct dc_stream_status *status;
 8612	int i, inst;
 8613
 8614	/* Notify device removals. */
 8615	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
 8616		if (old_con_state->crtc != new_con_state->crtc) {
 8617			/* CRTC changes require notification. */
 8618			goto notify;
 8619		}
 8620
 8621		if (!new_con_state->crtc)
 8622			continue;
 8623
 8624		new_crtc_state = drm_atomic_get_new_crtc_state(
 8625			state, new_con_state->crtc);
 8626
 8627		if (!new_crtc_state)
 8628			continue;
 8629
 8630		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
 8631			continue;
 8632
 8633		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
 8634			continue;
 8635
 8636notify:
 8637		aconnector = to_amdgpu_dm_connector(connector);
 8638
 8639		mutex_lock(&adev->dm.audio_lock);
 8640		inst = aconnector->audio_inst;
 8641		aconnector->audio_inst = -1;
 8642		mutex_unlock(&adev->dm.audio_lock);
 8643
 8644		amdgpu_dm_audio_eld_notify(adev, inst);
 8645	}
 8646
 8647	/* Notify audio device additions. */
 8648	for_each_new_connector_in_state(state, connector, new_con_state, i) {
 8649		if (!new_con_state->crtc)
 8650			continue;
 8651
 8652		new_crtc_state = drm_atomic_get_new_crtc_state(
 8653			state, new_con_state->crtc);
 8654
 8655		if (!new_crtc_state)
 8656			continue;
 8657
 8658		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
 8659			continue;
 8660
 8661		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
 8662		if (!new_dm_crtc_state->stream)
 8663			continue;
 8664
 8665		status = dc_stream_get_status(new_dm_crtc_state->stream);
 8666		if (!status)
 8667			continue;
 8668
 8669		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
 8670			continue;
 8671
 8672		aconnector = to_amdgpu_dm_connector(connector);
 8673
 8674		mutex_lock(&adev->dm.audio_lock);
 8675		inst = status->audio_inst;
 8676		aconnector->audio_inst = inst;
 8677		mutex_unlock(&adev->dm.audio_lock);
 8678
 8679		amdgpu_dm_audio_eld_notify(adev, inst);
 8680	}
 8681}
 8682
 8683/*
 8684 * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
 8685 * @crtc_state: the DRM CRTC state
 8686 * @stream_state: the DC stream state.
 8687 *
 8688 * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
 8689 * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
 8690 */
 8691static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
 8692						struct dc_stream_state *stream_state)
 8693{
 8694	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
 8695}
 8696
 8697static void dm_clear_writeback(struct amdgpu_display_manager *dm,
 8698			      struct dm_crtc_state *crtc_state)
 8699{
 8700	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
 8701}
 8702
 8703static void amdgpu_dm_commit_streams(struct drm_atomic_state *state,
 8704					struct dc_state *dc_state)
 8705{
 8706	struct drm_device *dev = state->dev;
 8707	struct amdgpu_device *adev = drm_to_adev(dev);
 8708	struct amdgpu_display_manager *dm = &adev->dm;
 8709	struct drm_crtc *crtc;
 8710	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
 8711	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
 8712	struct drm_connector_state *old_con_state;
 8713	struct drm_connector *connector;
 8714	bool mode_set_reset_required = false;
 8715	u32 i;
 8716
 8717	/* Disable writeback */
 8718	for_each_old_connector_in_state(state, connector, old_con_state, i) {
 8719		struct dm_connector_state *dm_old_con_state;
 8720		struct amdgpu_crtc *acrtc;
 8721
 8722		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
 8723			continue;
 8724
 8725		old_crtc_state = NULL;
 8726
 8727		dm_old_con_state = to_dm_connector_state(old_con_state);
 8728		if (!dm_old_con_state->base.crtc)
 8729			continue;
 8730
 8731		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
 8732		if (acrtc)
 8733			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
 8734
 8735		if (!acrtc->wb_enabled)
 8736			continue;
 8737
 8738		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
 8739
 8740		dm_clear_writeback(dm, dm_old_crtc_state);
 8741		acrtc->wb_enabled = false;
 8742	}
 8743
 8744	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
 8745				      new_crtc_state, i) {
 8746		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
 8747
 8748		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
 8749
 8750		if (old_crtc_state->active &&
 8751		    (!new_crtc_state->active ||
 8752		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
 8753			manage_dm_interrupts(adev, acrtc, false);
 8754			dc_stream_release(dm_old_crtc_state->stream);
 8755		}
 8756	}
 8757
 8758	drm_atomic_helper_calc_timestamping_constants(state);
 8759
 8760	/* update changed items */
 8761	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
 8762		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
 8763
 8764		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
 8765		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
 8766
 8767		drm_dbg_state(state->dev,
 8768			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
 8769			acrtc->crtc_id,
 8770			new_crtc_state->enable,
 8771			new_crtc_state->active,
 8772			new_crtc_state->planes_changed,
 8773			new_crtc_state->mode_changed,
 8774			new_crtc_state->active_changed,
 8775			new_crtc_state->connectors_changed);
 8776
 8777		/* Disable cursor if disabling crtc */
 8778		if (old_crtc_state->active && !new_crtc_state->active) {
 8779			struct dc_cursor_position position;
 8780
 8781			memset(&position, 0, sizeof(position));
 8782			mutex_lock(&dm->dc_lock);
 8783			dc_stream_set_cursor_position(dm_old_crtc_state->stream, &position);
 8784			mutex_unlock(&dm->dc_lock);
 8785		}
 8786
 8787		/* Copy all transient state flags into dc state */
 8788		if (dm_new_crtc_state->stream) {
 8789			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
 8790							    dm_new_crtc_state->stream);
 8791		}
 8792
 8793		/* handles headless hotplug case, updating new_state and
 8794		 * aconnector as needed
 8795		 */
 8796
 8797		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
 8798
 8799			DRM_DEBUG_ATOMIC("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
 8800
 8801			if (!dm_new_crtc_state->stream) {
 8802				/*
 8803				 * this could happen because of issues with
 8804				 * userspace notifications delivery.
 8805				 * In this case userspace tries to set mode on
 8806				 * display which is disconnected in fact.
 8807				 * dc_sink is NULL in this case on aconnector.
 8808				 * We expect reset mode will come soon.
 8809				 *
 8810				 * This can also happen when unplug is done
 8811				 * during resume sequence ended
 8812				 *
 8813				 * In this case, we want to pretend we still
 8814				 * have a sink to keep the pipe running so that
 8815				 * hw state is consistent with the sw state
 8816				 */
 8817				DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
 8818						__func__, acrtc->base.base.id);
 8819				continue;
 8820			}
 8821
 8822			if (dm_old_crtc_state->stream)
 8823				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
 8824
 8825			pm_runtime_get_noresume(dev->dev);
 8826
 8827			acrtc->enabled = true;
 8828			acrtc->hw_mode = new_crtc_state->mode;
 8829			crtc->hwmode = new_crtc_state->mode;
 8830			mode_set_reset_required = true;
 8831		} else if (modereset_required(new_crtc_state)) {
 8832			DRM_DEBUG_ATOMIC("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
 8833			/* i.e. reset mode */
 8834			if (dm_old_crtc_state->stream)
 8835				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
 8836
 8837			mode_set_reset_required = true;
 8838		}
 8839	} /* for_each_crtc_in_state() */
 8840
 8841	/* if there mode set or reset, disable eDP PSR */
 8842	if (mode_set_reset_required) {
 8843		if (dm->vblank_control_workqueue)
 8844			flush_workqueue(dm->vblank_control_workqueue);
 8845
 8846		amdgpu_dm_psr_disable_all(dm);
 8847	}
 8848
 8849	dm_enable_per_frame_crtc_master_sync(dc_state);
 8850	mutex_lock(&dm->dc_lock);
 8851	WARN_ON(!dc_commit_streams(dm->dc, dc_state->streams, dc_state->stream_count));
 8852
 8853	/* Allow idle optimization when vblank count is 0 for display off */
 8854	if (dm->active_vblank_irq_count == 0)
 8855		dc_allow_idle_optimizations(dm->dc, true);
 8856	mutex_unlock(&dm->dc_lock);
 8857
 8858	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
 8859		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
 8860
 8861		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
 8862
 8863		if (dm_new_crtc_state->stream != NULL) {
 8864			const struct dc_stream_status *status =
 8865					dc_stream_get_status(dm_new_crtc_state->stream);
 8866
 8867			if (!status)
 8868				status = dc_state_get_stream_status(dc_state,
 8869									 dm_new_crtc_state->stream);
 8870			if (!status)
 8871				drm_err(dev,
 8872					"got no status for stream %p on acrtc%p\n",
 8873					dm_new_crtc_state->stream, acrtc);
 8874			else
 8875				acrtc->otg_inst = status->primary_otg_inst;
 8876		}
 8877	}
 8878}
 8879
 8880static void dm_set_writeback(struct amdgpu_display_manager *dm,
 8881			      struct dm_crtc_state *crtc_state,
 8882			      struct drm_connector *connector,
 8883			      struct drm_connector_state *new_con_state)
 8884{
 8885	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
 8886	struct amdgpu_device *adev = dm->adev;
 8887	struct amdgpu_crtc *acrtc;
 8888	struct dc_writeback_info *wb_info;
 8889	struct pipe_ctx *pipe = NULL;
 8890	struct amdgpu_framebuffer *afb;
 8891	int i = 0;
 8892
 8893	wb_info = kzalloc(sizeof(*wb_info), GFP_KERNEL);
 8894	if (!wb_info) {
 8895		DRM_ERROR("Failed to allocate wb_info\n");
 8896		return;
 8897	}
 8898
 8899	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
 8900	if (!acrtc) {
 8901		DRM_ERROR("no amdgpu_crtc found\n");
 8902		kfree(wb_info);
 8903		return;
 8904	}
 8905
 8906	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
 8907	if (!afb) {
 8908		DRM_ERROR("No amdgpu_framebuffer found\n");
 8909		kfree(wb_info);
 8910		return;
 8911	}
 8912
 8913	for (i = 0; i < MAX_PIPES; i++) {
 8914		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
 8915			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
 8916			break;
 8917		}
 8918	}
 8919
 8920	/* fill in wb_info */
 8921	wb_info->wb_enabled = true;
 8922
 8923	wb_info->dwb_pipe_inst = 0;
 8924	wb_info->dwb_params.dwbscl_black_color = 0;
 8925	wb_info->dwb_params.hdr_mult = 0x1F000;
 8926	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
 8927	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
 8928	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
 8929	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
 8930
 8931	/* width & height from crtc */
 8932	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
 8933	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
 8934	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
 8935	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
 8936
 8937	wb_info->dwb_params.cnv_params.crop_en = false;
 8938	wb_info->dwb_params.stereo_params.stereo_enabled = false;
 8939
 8940	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
 8941	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
 8942	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
 8943	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
 8944
 8945	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
 8946
 8947	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
 8948
 8949	wb_info->dwb_params.scaler_taps.h_taps = 4;
 8950	wb_info->dwb_params.scaler_taps.v_taps = 4;
 8951	wb_info->dwb_params.scaler_taps.h_taps_c = 2;
 8952	wb_info->dwb_params.scaler_taps.v_taps_c = 2;
 8953	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
 8954
 8955	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
 8956	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
 8957
 8958	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
 8959		wb_info->mcif_buf_params.luma_address[i] = afb->address;
 8960		wb_info->mcif_buf_params.chroma_address[i] = 0;
 8961	}
 8962
 8963	wb_info->mcif_buf_params.p_vmid = 1;
 8964	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
 8965		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
 8966		wb_info->mcif_warmup_params.region_size =
 8967			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
 8968	}
 8969	wb_info->mcif_warmup_params.p_vmid = 1;
 8970	wb_info->writeback_source_plane = pipe->plane_state;
 8971
 8972	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
 8973
 8974	acrtc->wb_pending = true;
 8975	acrtc->wb_conn = wb_conn;
 8976	drm_writeback_queue_job(wb_conn, new_con_state);
 8977}
 8978
 8979/**
 8980 * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
 8981 * @state: The atomic state to commit
 8982 *
 8983 * This will tell DC to commit the constructed DC state from atomic_check,
 8984 * programming the hardware. Any failures here implies a hardware failure, since
 8985 * atomic check should have filtered anything non-kosher.
 8986 */
 8987static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
 8988{
 8989	struct drm_device *dev = state->dev;
 8990	struct amdgpu_device *adev = drm_to_adev(dev);
 8991	struct amdgpu_display_manager *dm = &adev->dm;
 8992	struct dm_atomic_state *dm_state;
 8993	struct dc_state *dc_state = NULL;
 8994	u32 i, j;
 8995	struct drm_crtc *crtc;
 8996	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
 8997	unsigned long flags;
 8998	bool wait_for_vblank = true;
 8999	struct drm_connector *connector;
 9000	struct drm_connector_state *old_con_state, *new_con_state;
 9001	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
 9002	int crtc_disable_count = 0;
 9003
 9004	trace_amdgpu_dm_atomic_commit_tail_begin(state);
 9005
 9006	if (dm->dc->caps.ips_support && dm->dc->idle_optimizations_allowed)
 9007		dc_allow_idle_optimizations(dm->dc, false);
 9008
 9009	drm_atomic_helper_update_legacy_modeset_state(dev, state);
 9010	drm_dp_mst_atomic_wait_for_dependencies(state);
 9011
 9012	dm_state = dm_atomic_get_new_state(state);
 9013	if (dm_state && dm_state->context) {
 9014		dc_state = dm_state->context;
 9015		amdgpu_dm_commit_streams(state, dc_state);
 9016	}
 9017
 9018	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
 9019		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
 9020		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
 9021		struct amdgpu_dm_connector *aconnector;
 9022
 9023		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
 9024			continue;
 9025
 9026		aconnector = to_amdgpu_dm_connector(connector);
 9027
 9028		if (!adev->dm.hdcp_workqueue)
 9029			continue;
 9030
 9031		pr_debug("[HDCP_DM] -------------- i : %x ----------\n", i);
 9032
 9033		if (!connector)
 9034			continue;
 9035
 9036		pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
 9037			connector->index, connector->status, connector->dpms);
 9038		pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
 9039			old_con_state->content_protection, new_con_state->content_protection);
 9040
 9041		if (aconnector->dc_sink) {
 9042			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
 9043				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
 9044				pr_debug("[HDCP_DM] pipe_ctx dispname=%s\n",
 9045				aconnector->dc_sink->edid_caps.display_name);
 9046			}
 9047		}
 9048
 9049		new_crtc_state = NULL;
 9050		old_crtc_state = NULL;
 9051
 9052		if (acrtc) {
 9053			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
 9054			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
 9055		}
 9056
 9057		if (old_crtc_state)
 9058			pr_debug("old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
 9059			old_crtc_state->enable,
 9060			old_crtc_state->active,
 9061			old_crtc_state->mode_changed,
 9062			old_crtc_state->active_changed,
 9063			old_crtc_state->connectors_changed);
 9064
 9065		if (new_crtc_state)
 9066			pr_debug("NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
 9067			new_crtc_state->enable,
 9068			new_crtc_state->active,
 9069			new_crtc_state->mode_changed,
 9070			new_crtc_state->active_changed,
 9071			new_crtc_state->connectors_changed);
 9072	}
 9073
 9074	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
 9075		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
 9076		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
 9077		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
 9078
 9079		if (!adev->dm.hdcp_workqueue)
 9080			continue;
 9081
 9082		new_crtc_state = NULL;
 9083		old_crtc_state = NULL;
 9084
 9085		if (acrtc) {
 9086			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
 9087			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
 9088		}
 9089
 9090		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
 9091
 9092		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
 9093		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
 9094			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
 9095			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
 9096			dm_new_con_state->update_hdcp = true;
 9097			continue;
 9098		}
 9099
 9100		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
 9101											old_con_state, connector, adev->dm.hdcp_workqueue)) {
 9102			/* when display is unplugged from mst hub, connctor will
 9103			 * be destroyed within dm_dp_mst_connector_destroy. connector
 9104			 * hdcp perperties, like type, undesired, desired, enabled,
 9105			 * will be lost. So, save hdcp properties into hdcp_work within
 9106			 * amdgpu_dm_atomic_commit_tail. if the same display is
 9107			 * plugged back with same display index, its hdcp properties
 9108			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
 9109			 */
 9110
 9111			bool enable_encryption = false;
 9112
 9113			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
 9114				enable_encryption = true;
 9115
 9116			if (aconnector->dc_link && aconnector->dc_sink &&
 9117				aconnector->dc_link->type == dc_connection_mst_branch) {
 9118				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
 9119				struct hdcp_workqueue *hdcp_w =
 9120					&hdcp_work[aconnector->dc_link->link_index];
 9121
 9122				hdcp_w->hdcp_content_type[connector->index] =
 9123					new_con_state->hdcp_content_type;
 9124				hdcp_w->content_protection[connector->index] =
 9125					new_con_state->content_protection;
 9126			}
 9127
 9128			if (new_crtc_state && new_crtc_state->mode_changed &&
 9129				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
 9130				enable_encryption = true;
 9131
 9132			DRM_INFO("[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
 9133
 9134			hdcp_update_display(
 9135				adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
 9136				new_con_state->hdcp_content_type, enable_encryption);
 9137		}
 9138	}
 9139
 9140	/* Handle connector state changes */
 9141	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
 9142		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
 9143		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
 9144		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
 9145		struct dc_surface_update *dummy_updates;
 9146		struct dc_stream_update stream_update;
 9147		struct dc_info_packet hdr_packet;
 9148		struct dc_stream_status *status = NULL;
 9149		bool abm_changed, hdr_changed, scaling_changed;
 9150
 9151		memset(&stream_update, 0, sizeof(stream_update));
 9152
 9153		if (acrtc) {
 9154			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
 9155			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
 9156		}
 9157
 9158		/* Skip any modesets/resets */
 9159		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
 9160			continue;
 9161
 9162		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
 9163		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
 9164
 9165		scaling_changed = is_scaling_state_different(dm_new_con_state,
 9166							     dm_old_con_state);
 9167
 9168		abm_changed = dm_new_crtc_state->abm_level !=
 9169			      dm_old_crtc_state->abm_level;
 9170
 9171		hdr_changed =
 9172			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
 9173
 9174		if (!scaling_changed && !abm_changed && !hdr_changed)
 9175			continue;
 9176
 9177		stream_update.stream = dm_new_crtc_state->stream;
 9178		if (scaling_changed) {
 9179			update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
 9180					dm_new_con_state, dm_new_crtc_state->stream);
 9181
 9182			stream_update.src = dm_new_crtc_state->stream->src;
 9183			stream_update.dst = dm_new_crtc_state->stream->dst;
 9184		}
 9185
 9186		if (abm_changed) {
 9187			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
 9188
 9189			stream_update.abm_level = &dm_new_crtc_state->abm_level;
 9190		}
 9191
 9192		if (hdr_changed) {
 9193			fill_hdr_info_packet(new_con_state, &hdr_packet);
 9194			stream_update.hdr_static_metadata = &hdr_packet;
 9195		}
 9196
 9197		status = dc_stream_get_status(dm_new_crtc_state->stream);
 9198
 9199		if (WARN_ON(!status))
 9200			continue;
 9201
 9202		WARN_ON(!status->plane_count);
 9203
 9204		/*
 9205		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
 9206		 * Here we create an empty update on each plane.
 9207		 * To fix this, DC should permit updating only stream properties.
 9208		 */
 9209		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_ATOMIC);
 9210		if (!dummy_updates) {
 9211			DRM_ERROR("Failed to allocate memory for dummy_updates.\n");
 9212			continue;
 9213		}
 9214		for (j = 0; j < status->plane_count; j++)
 9215			dummy_updates[j].surface = status->plane_states[0];
 9216
 9217
 9218		mutex_lock(&dm->dc_lock);
 9219		dc_update_planes_and_stream(dm->dc,
 9220					    dummy_updates,
 9221					    status->plane_count,
 9222					    dm_new_crtc_state->stream,
 9223					    &stream_update);
 9224		mutex_unlock(&dm->dc_lock);
 9225		kfree(dummy_updates);
 9226	}
 9227
 9228	/**
 9229	 * Enable interrupts for CRTCs that are newly enabled or went through
 9230	 * a modeset. It was intentionally deferred until after the front end
 9231	 * state was modified to wait until the OTG was on and so the IRQ
 9232	 * handlers didn't access stale or invalid state.
 9233	 */
 9234	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
 9235		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
 9236#ifdef CONFIG_DEBUG_FS
 9237		enum amdgpu_dm_pipe_crc_source cur_crc_src;
 9238#endif
 9239		/* Count number of newly disabled CRTCs for dropping PM refs later. */
 9240		if (old_crtc_state->active && !new_crtc_state->active)
 9241			crtc_disable_count++;
 9242
 9243		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
 9244		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
 9245
 9246		/* For freesync config update on crtc state and params for irq */
 9247		update_stream_irq_parameters(dm, dm_new_crtc_state);
 9248
 9249#ifdef CONFIG_DEBUG_FS
 9250		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
 9251		cur_crc_src = acrtc->dm_irq_params.crc_src;
 9252		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
 9253#endif
 9254
 9255		if (new_crtc_state->active &&
 9256		    (!old_crtc_state->active ||
 9257		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
 9258			dc_stream_retain(dm_new_crtc_state->stream);
 9259			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
 9260			manage_dm_interrupts(adev, acrtc, true);
 9261		}
 9262		/* Handle vrr on->off / off->on transitions */
 9263		amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
 9264
 9265#ifdef CONFIG_DEBUG_FS
 9266		if (new_crtc_state->active &&
 9267		    (!old_crtc_state->active ||
 9268		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
 9269			/**
 9270			 * Frontend may have changed so reapply the CRC capture
 9271			 * settings for the stream.
 9272			 */
 9273			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
 9274#if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
 9275				if (amdgpu_dm_crc_window_is_activated(crtc)) {
 9276					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
 9277					acrtc->dm_irq_params.window_param.update_win = true;
 9278
 9279					/**
 9280					 * It takes 2 frames for HW to stably generate CRC when
 9281					 * resuming from suspend, so we set skip_frame_cnt 2.
 9282					 */
 9283					acrtc->dm_irq_params.window_param.skip_frame_cnt = 2;
 9284					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
 9285				}
 9286#endif
 9287				if (amdgpu_dm_crtc_configure_crc_source(
 9288					crtc, dm_new_crtc_state, cur_crc_src))
 9289					DRM_DEBUG_DRIVER("Failed to configure crc source");
 9290			}
 9291		}
 9292#endif
 9293	}
 9294
 9295	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
 9296		if (new_crtc_state->async_flip)
 9297			wait_for_vblank = false;
 9298
 9299	/* update planes when needed per crtc*/
 9300	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
 9301		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
 9302
 9303		if (dm_new_crtc_state->stream)
 9304			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
 9305	}
 9306
 9307	/* Enable writeback */
 9308	for_each_new_connector_in_state(state, connector, new_con_state, i) {
 9309		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
 9310		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
 9311
 9312		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
 9313			continue;
 9314
 9315		if (!new_con_state->writeback_job)
 9316			continue;
 9317
 9318		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
 9319
 9320		if (!new_crtc_state)
 9321			continue;
 9322
 9323		if (acrtc->wb_enabled)
 9324			continue;
 9325
 9326		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
 9327
 9328		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
 9329		acrtc->wb_enabled = true;
 9330	}
 9331
 9332	/* Update audio instances for each connector. */
 9333	amdgpu_dm_commit_audio(dev, state);
 9334
 9335	/* restore the backlight level */
 9336	for (i = 0; i < dm->num_of_edps; i++) {
 9337		if (dm->backlight_dev[i] &&
 9338		    (dm->actual_brightness[i] != dm->brightness[i]))
 9339			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
 9340	}
 9341
 9342	/*
 9343	 * send vblank event on all events not handled in flip and
 9344	 * mark consumed event for drm_atomic_helper_commit_hw_done
 9345	 */
 9346	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
 9347	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
 9348
 9349		if (new_crtc_state->event)
 9350			drm_send_event_locked(dev, &new_crtc_state->event->base);
 9351
 9352		new_crtc_state->event = NULL;
 9353	}
 9354	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
 9355
 9356	/* Signal HW programming completion */
 9357	drm_atomic_helper_commit_hw_done(state);
 9358
 9359	if (wait_for_vblank)
 9360		drm_atomic_helper_wait_for_flip_done(dev, state);
 9361
 9362	drm_atomic_helper_cleanup_planes(dev, state);
 9363
 9364	/* Don't free the memory if we are hitting this as part of suspend.
 9365	 * This way we don't free any memory during suspend; see
 9366	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
 9367	 * non-suspend modeset or when the driver is torn down.
 9368	 */
 9369	if (!adev->in_suspend) {
 9370		/* return the stolen vga memory back to VRAM */
 9371		if (!adev->mman.keep_stolen_vga_memory)
 9372			amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
 9373		amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
 9374	}
 9375
 9376	/*
 9377	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
 9378	 * so we can put the GPU into runtime suspend if we're not driving any
 9379	 * displays anymore
 9380	 */
 9381	for (i = 0; i < crtc_disable_count; i++)
 9382		pm_runtime_put_autosuspend(dev->dev);
 9383	pm_runtime_mark_last_busy(dev->dev);
 9384}
 9385
 9386static int dm_force_atomic_commit(struct drm_connector *connector)
 9387{
 9388	int ret = 0;
 9389	struct drm_device *ddev = connector->dev;
 9390	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
 9391	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
 9392	struct drm_plane *plane = disconnected_acrtc->base.primary;
 9393	struct drm_connector_state *conn_state;
 9394	struct drm_crtc_state *crtc_state;
 9395	struct drm_plane_state *plane_state;
 9396
 9397	if (!state)
 9398		return -ENOMEM;
 9399
 9400	state->acquire_ctx = ddev->mode_config.acquire_ctx;
 9401
 9402	/* Construct an atomic state to restore previous display setting */
 9403
 9404	/*
 9405	 * Attach connectors to drm_atomic_state
 9406	 */
 9407	conn_state = drm_atomic_get_connector_state(state, connector);
 9408
 9409	ret = PTR_ERR_OR_ZERO(conn_state);
 9410	if (ret)
 9411		goto out;
 9412
 9413	/* Attach crtc to drm_atomic_state*/
 9414	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
 9415
 9416	ret = PTR_ERR_OR_ZERO(crtc_state);
 9417	if (ret)
 9418		goto out;
 9419
 9420	/* force a restore */
 9421	crtc_state->mode_changed = true;
 9422
 9423	/* Attach plane to drm_atomic_state */
 9424	plane_state = drm_atomic_get_plane_state(state, plane);
 9425
 9426	ret = PTR_ERR_OR_ZERO(plane_state);
 9427	if (ret)
 9428		goto out;
 9429
 9430	/* Call commit internally with the state we just constructed */
 9431	ret = drm_atomic_commit(state);
 9432
 9433out:
 9434	drm_atomic_state_put(state);
 9435	if (ret)
 9436		DRM_ERROR("Restoring old state failed with %i\n", ret);
 9437
 9438	return ret;
 9439}
 9440
 9441/*
 9442 * This function handles all cases when set mode does not come upon hotplug.
 9443 * This includes when a display is unplugged then plugged back into the
 9444 * same port and when running without usermode desktop manager supprot
 9445 */
 9446void dm_restore_drm_connector_state(struct drm_device *dev,
 9447				    struct drm_connector *connector)
 9448{
 9449	struct amdgpu_dm_connector *aconnector;
 9450	struct amdgpu_crtc *disconnected_acrtc;
 9451	struct dm_crtc_state *acrtc_state;
 9452
 9453	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
 9454		return;
 9455
 9456	aconnector = to_amdgpu_dm_connector(connector);
 9457
 9458	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
 9459		return;
 9460
 9461	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
 9462	if (!disconnected_acrtc)
 9463		return;
 9464
 9465	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
 9466	if (!acrtc_state->stream)
 9467		return;
 9468
 9469	/*
 9470	 * If the previous sink is not released and different from the current,
 9471	 * we deduce we are in a state where we can not rely on usermode call
 9472	 * to turn on the display, so we do it here
 9473	 */
 9474	if (acrtc_state->stream->sink != aconnector->dc_sink)
 9475		dm_force_atomic_commit(&aconnector->base);
 9476}
 9477
 9478/*
 9479 * Grabs all modesetting locks to serialize against any blocking commits,
 9480 * Waits for completion of all non blocking commits.
 9481 */
 9482static int do_aquire_global_lock(struct drm_device *dev,
 9483				 struct drm_atomic_state *state)
 9484{
 9485	struct drm_crtc *crtc;
 9486	struct drm_crtc_commit *commit;
 9487	long ret;
 9488
 9489	/*
 9490	 * Adding all modeset locks to aquire_ctx will
 9491	 * ensure that when the framework release it the
 9492	 * extra locks we are locking here will get released to
 9493	 */
 9494	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
 9495	if (ret)
 9496		return ret;
 9497
 9498	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
 9499		spin_lock(&crtc->commit_lock);
 9500		commit = list_first_entry_or_null(&crtc->commit_list,
 9501				struct drm_crtc_commit, commit_entry);
 9502		if (commit)
 9503			drm_crtc_commit_get(commit);
 9504		spin_unlock(&crtc->commit_lock);
 9505
 9506		if (!commit)
 9507			continue;
 9508
 9509		/*
 9510		 * Make sure all pending HW programming completed and
 9511		 * page flips done
 9512		 */
 9513		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
 9514
 9515		if (ret > 0)
 9516			ret = wait_for_completion_interruptible_timeout(
 9517					&commit->flip_done, 10*HZ);
 9518
 9519		if (ret == 0)
 9520			DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done timed out\n",
 9521				  crtc->base.id, crtc->name);
 9522
 9523		drm_crtc_commit_put(commit);
 9524	}
 9525
 9526	return ret < 0 ? ret : 0;
 9527}
 9528
 9529static void get_freesync_config_for_crtc(
 9530	struct dm_crtc_state *new_crtc_state,
 9531	struct dm_connector_state *new_con_state)
 9532{
 9533	struct mod_freesync_config config = {0};
 9534	struct amdgpu_dm_connector *aconnector;
 9535	struct drm_display_mode *mode = &new_crtc_state->base.mode;
 9536	int vrefresh = drm_mode_vrefresh(mode);
 9537	bool fs_vid_mode = false;
 9538
 9539	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
 9540		return;
 9541
 9542	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
 9543
 9544	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
 9545					vrefresh >= aconnector->min_vfreq &&
 9546					vrefresh <= aconnector->max_vfreq;
 9547
 9548	if (new_crtc_state->vrr_supported) {
 9549		new_crtc_state->stream->ignore_msa_timing_param = true;
 9550		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
 9551
 9552		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
 9553		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
 9554		config.vsif_supported = true;
 9555		config.btr = true;
 9556
 9557		if (fs_vid_mode) {
 9558			config.state = VRR_STATE_ACTIVE_FIXED;
 9559			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
 9560			goto out;
 9561		} else if (new_crtc_state->base.vrr_enabled) {
 9562			config.state = VRR_STATE_ACTIVE_VARIABLE;
 9563		} else {
 9564			config.state = VRR_STATE_INACTIVE;
 9565		}
 9566	}
 9567out:
 9568	new_crtc_state->freesync_config = config;
 9569}
 9570
 9571static void reset_freesync_config_for_crtc(
 9572	struct dm_crtc_state *new_crtc_state)
 9573{
 9574	new_crtc_state->vrr_supported = false;
 9575
 9576	memset(&new_crtc_state->vrr_infopacket, 0,
 9577	       sizeof(new_crtc_state->vrr_infopacket));
 9578}
 9579
 9580static bool
 9581is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
 9582				 struct drm_crtc_state *new_crtc_state)
 9583{
 9584	const struct drm_display_mode *old_mode, *new_mode;
 9585
 9586	if (!old_crtc_state || !new_crtc_state)
 9587		return false;
 9588
 9589	old_mode = &old_crtc_state->mode;
 9590	new_mode = &new_crtc_state->mode;
 9591
 9592	if (old_mode->clock       == new_mode->clock &&
 9593	    old_mode->hdisplay    == new_mode->hdisplay &&
 9594	    old_mode->vdisplay    == new_mode->vdisplay &&
 9595	    old_mode->htotal      == new_mode->htotal &&
 9596	    old_mode->vtotal      != new_mode->vtotal &&
 9597	    old_mode->hsync_start == new_mode->hsync_start &&
 9598	    old_mode->vsync_start != new_mode->vsync_start &&
 9599	    old_mode->hsync_end   == new_mode->hsync_end &&
 9600	    old_mode->vsync_end   != new_mode->vsync_end &&
 9601	    old_mode->hskew       == new_mode->hskew &&
 9602	    old_mode->vscan       == new_mode->vscan &&
 9603	    (old_mode->vsync_end - old_mode->vsync_start) ==
 9604	    (new_mode->vsync_end - new_mode->vsync_start))
 9605		return true;
 9606
 9607	return false;
 9608}
 9609
 9610static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
 9611{
 9612	u64 num, den, res;
 9613	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
 9614
 9615	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
 9616
 9617	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
 9618	den = (unsigned long long)new_crtc_state->mode.htotal *
 9619	      (unsigned long long)new_crtc_state->mode.vtotal;
 9620
 9621	res = div_u64(num, den);
 9622	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
 9623}
 9624
 9625static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
 9626			 struct drm_atomic_state *state,
 9627			 struct drm_crtc *crtc,
 9628			 struct drm_crtc_state *old_crtc_state,
 9629			 struct drm_crtc_state *new_crtc_state,
 9630			 bool enable,
 9631			 bool *lock_and_validation_needed)
 9632{
 9633	struct dm_atomic_state *dm_state = NULL;
 9634	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
 9635	struct dc_stream_state *new_stream;
 9636	int ret = 0;
 9637
 9638	/*
 9639	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
 9640	 * update changed items
 9641	 */
 9642	struct amdgpu_crtc *acrtc = NULL;
 9643	struct drm_connector *connector = NULL;
 9644	struct amdgpu_dm_connector *aconnector = NULL;
 9645	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
 9646	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
 9647
 9648	new_stream = NULL;
 9649
 9650	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
 9651	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
 9652	acrtc = to_amdgpu_crtc(crtc);
 9653	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
 9654	if (connector)
 9655		aconnector = to_amdgpu_dm_connector(connector);
 9656
 9657	/* TODO This hack should go away */
 9658	if (connector && enable) {
 9659		/* Make sure fake sink is created in plug-in scenario */
 9660		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
 9661									connector);
 9662		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
 9663									connector);
 9664
 9665		if (IS_ERR(drm_new_conn_state)) {
 9666			ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
 9667			goto fail;
 9668		}
 9669
 9670		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
 9671		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
 9672
 9673		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
 9674			goto skip_modeset;
 9675
 9676		new_stream = create_validate_stream_for_sink(aconnector,
 9677							     &new_crtc_state->mode,
 9678							     dm_new_conn_state,
 9679							     dm_old_crtc_state->stream);
 9680
 9681		/*
 9682		 * we can have no stream on ACTION_SET if a display
 9683		 * was disconnected during S3, in this case it is not an
 9684		 * error, the OS will be updated after detection, and
 9685		 * will do the right thing on next atomic commit
 9686		 */
 9687
 9688		if (!new_stream) {
 9689			DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
 9690					__func__, acrtc->base.base.id);
 9691			ret = -ENOMEM;
 9692			goto fail;
 9693		}
 9694
 9695		/*
 9696		 * TODO: Check VSDB bits to decide whether this should
 9697		 * be enabled or not.
 9698		 */
 9699		new_stream->triggered_crtc_reset.enabled =
 9700			dm->force_timing_sync;
 9701
 9702		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
 9703
 9704		ret = fill_hdr_info_packet(drm_new_conn_state,
 9705					   &new_stream->hdr_static_metadata);
 9706		if (ret)
 9707			goto fail;
 9708
 9709		/*
 9710		 * If we already removed the old stream from the context
 9711		 * (and set the new stream to NULL) then we can't reuse
 9712		 * the old stream even if the stream and scaling are unchanged.
 9713		 * We'll hit the BUG_ON and black screen.
 9714		 *
 9715		 * TODO: Refactor this function to allow this check to work
 9716		 * in all conditions.
 9717		 */
 9718		if (dm_new_crtc_state->stream &&
 9719		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
 9720			goto skip_modeset;
 9721
 9722		if (dm_new_crtc_state->stream &&
 9723		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
 9724		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
 9725			new_crtc_state->mode_changed = false;
 9726			DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
 9727					 new_crtc_state->mode_changed);
 9728		}
 9729	}
 9730
 9731	/* mode_changed flag may get updated above, need to check again */
 9732	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
 9733		goto skip_modeset;
 9734
 9735	drm_dbg_state(state->dev,
 9736		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
 9737		acrtc->crtc_id,
 9738		new_crtc_state->enable,
 9739		new_crtc_state->active,
 9740		new_crtc_state->planes_changed,
 9741		new_crtc_state->mode_changed,
 9742		new_crtc_state->active_changed,
 9743		new_crtc_state->connectors_changed);
 9744
 9745	/* Remove stream for any changed/disabled CRTC */
 9746	if (!enable) {
 9747
 9748		if (!dm_old_crtc_state->stream)
 9749			goto skip_modeset;
 9750
 9751		/* Unset freesync video if it was active before */
 9752		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
 9753			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
 9754			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
 9755		}
 9756
 9757		/* Now check if we should set freesync video mode */
 9758		if (dm_new_crtc_state->stream &&
 9759		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
 9760		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
 9761		    is_timing_unchanged_for_freesync(new_crtc_state,
 9762						     old_crtc_state)) {
 9763			new_crtc_state->mode_changed = false;
 9764			DRM_DEBUG_DRIVER(
 9765				"Mode change not required for front porch change, setting mode_changed to %d",
 9766				new_crtc_state->mode_changed);
 9767
 9768			set_freesync_fixed_config(dm_new_crtc_state);
 9769
 9770			goto skip_modeset;
 9771		} else if (aconnector &&
 9772			   is_freesync_video_mode(&new_crtc_state->mode,
 9773						  aconnector)) {
 9774			struct drm_display_mode *high_mode;
 9775
 9776			high_mode = get_highest_refresh_rate_mode(aconnector, false);
 9777			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
 9778				set_freesync_fixed_config(dm_new_crtc_state);
 9779		}
 9780
 9781		ret = dm_atomic_get_state(state, &dm_state);
 9782		if (ret)
 9783			goto fail;
 9784
 9785		DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
 9786				crtc->base.id);
 9787
 9788		/* i.e. reset mode */
 9789		if (dc_state_remove_stream(
 9790				dm->dc,
 9791				dm_state->context,
 9792				dm_old_crtc_state->stream) != DC_OK) {
 9793			ret = -EINVAL;
 9794			goto fail;
 9795		}
 9796
 9797		dc_stream_release(dm_old_crtc_state->stream);
 9798		dm_new_crtc_state->stream = NULL;
 9799
 9800		reset_freesync_config_for_crtc(dm_new_crtc_state);
 9801
 9802		*lock_and_validation_needed = true;
 9803
 9804	} else {/* Add stream for any updated/enabled CRTC */
 9805		/*
 9806		 * Quick fix to prevent NULL pointer on new_stream when
 9807		 * added MST connectors not found in existing crtc_state in the chained mode
 9808		 * TODO: need to dig out the root cause of that
 9809		 */
 9810		if (!connector)
 9811			goto skip_modeset;
 9812
 9813		if (modereset_required(new_crtc_state))
 9814			goto skip_modeset;
 9815
 9816		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
 9817				     dm_old_crtc_state->stream)) {
 9818
 9819			WARN_ON(dm_new_crtc_state->stream);
 9820
 9821			ret = dm_atomic_get_state(state, &dm_state);
 9822			if (ret)
 9823				goto fail;
 9824
 9825			dm_new_crtc_state->stream = new_stream;
 9826
 9827			dc_stream_retain(new_stream);
 9828
 9829			DRM_DEBUG_ATOMIC("Enabling DRM crtc: %d\n",
 9830					 crtc->base.id);
 9831
 9832			if (dc_state_add_stream(
 9833					dm->dc,
 9834					dm_state->context,
 9835					dm_new_crtc_state->stream) != DC_OK) {
 9836				ret = -EINVAL;
 9837				goto fail;
 9838			}
 9839
 9840			*lock_and_validation_needed = true;
 9841		}
 9842	}
 9843
 9844skip_modeset:
 9845	/* Release extra reference */
 9846	if (new_stream)
 9847		dc_stream_release(new_stream);
 9848
 9849	/*
 9850	 * We want to do dc stream updates that do not require a
 9851	 * full modeset below.
 9852	 */
 9853	if (!(enable && connector && new_crtc_state->active))
 9854		return 0;
 9855	/*
 9856	 * Given above conditions, the dc state cannot be NULL because:
 9857	 * 1. We're in the process of enabling CRTCs (just been added
 9858	 *    to the dc context, or already is on the context)
 9859	 * 2. Has a valid connector attached, and
 9860	 * 3. Is currently active and enabled.
 9861	 * => The dc stream state currently exists.
 9862	 */
 9863	BUG_ON(dm_new_crtc_state->stream == NULL);
 9864
 9865	/* Scaling or underscan settings */
 9866	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
 9867				drm_atomic_crtc_needs_modeset(new_crtc_state))
 9868		update_stream_scaling_settings(
 9869			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
 9870
 9871	/* ABM settings */
 9872	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
 9873
 9874	/*
 9875	 * Color management settings. We also update color properties
 9876	 * when a modeset is needed, to ensure it gets reprogrammed.
 9877	 */
 9878	if (dm_new_crtc_state->base.color_mgmt_changed ||
 9879	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
 9880	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
 9881		ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
 9882		if (ret)
 9883			goto fail;
 9884	}
 9885
 9886	/* Update Freesync settings. */
 9887	get_freesync_config_for_crtc(dm_new_crtc_state,
 9888				     dm_new_conn_state);
 9889
 9890	return ret;
 9891
 9892fail:
 9893	if (new_stream)
 9894		dc_stream_release(new_stream);
 9895	return ret;
 9896}
 9897
 9898static bool should_reset_plane(struct drm_atomic_state *state,
 9899			       struct drm_plane *plane,
 9900			       struct drm_plane_state *old_plane_state,
 9901			       struct drm_plane_state *new_plane_state)
 9902{
 9903	struct drm_plane *other;
 9904	struct drm_plane_state *old_other_state, *new_other_state;
 9905	struct drm_crtc_state *new_crtc_state;
 9906	struct amdgpu_device *adev = drm_to_adev(plane->dev);
 9907	int i;
 9908
 9909	/*
 9910	 * TODO: Remove this hack for all asics once it proves that the
 9911	 * fast updates works fine on DCN3.2+.
 9912	 */
 9913	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
 9914	    state->allow_modeset)
 9915		return true;
 9916
 9917	/* Exit early if we know that we're adding or removing the plane. */
 9918	if (old_plane_state->crtc != new_plane_state->crtc)
 9919		return true;
 9920
 9921	/* old crtc == new_crtc == NULL, plane not in context. */
 9922	if (!new_plane_state->crtc)
 9923		return false;
 9924
 9925	new_crtc_state =
 9926		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
 9927
 9928	if (!new_crtc_state)
 9929		return true;
 9930
 9931	/* CRTC Degamma changes currently require us to recreate planes. */
 9932	if (new_crtc_state->color_mgmt_changed)
 9933		return true;
 9934
 9935	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
 9936		return true;
 9937
 9938	/*
 9939	 * If there are any new primary or overlay planes being added or
 9940	 * removed then the z-order can potentially change. To ensure
 9941	 * correct z-order and pipe acquisition the current DC architecture
 9942	 * requires us to remove and recreate all existing planes.
 9943	 *
 9944	 * TODO: Come up with a more elegant solution for this.
 9945	 */
 9946	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
 9947		struct amdgpu_framebuffer *old_afb, *new_afb;
 9948		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
 9949
 9950		dm_new_other_state = to_dm_plane_state(new_other_state);
 9951		dm_old_other_state = to_dm_plane_state(old_other_state);
 9952
 9953		if (other->type == DRM_PLANE_TYPE_CURSOR)
 9954			continue;
 9955
 9956		if (old_other_state->crtc != new_plane_state->crtc &&
 9957		    new_other_state->crtc != new_plane_state->crtc)
 9958			continue;
 9959
 9960		if (old_other_state->crtc != new_other_state->crtc)
 9961			return true;
 9962
 9963		/* Src/dst size and scaling updates. */
 9964		if (old_other_state->src_w != new_other_state->src_w ||
 9965		    old_other_state->src_h != new_other_state->src_h ||
 9966		    old_other_state->crtc_w != new_other_state->crtc_w ||
 9967		    old_other_state->crtc_h != new_other_state->crtc_h)
 9968			return true;
 9969
 9970		/* Rotation / mirroring updates. */
 9971		if (old_other_state->rotation != new_other_state->rotation)
 9972			return true;
 9973
 9974		/* Blending updates. */
 9975		if (old_other_state->pixel_blend_mode !=
 9976		    new_other_state->pixel_blend_mode)
 9977			return true;
 9978
 9979		/* Alpha updates. */
 9980		if (old_other_state->alpha != new_other_state->alpha)
 9981			return true;
 9982
 9983		/* Colorspace changes. */
 9984		if (old_other_state->color_range != new_other_state->color_range ||
 9985		    old_other_state->color_encoding != new_other_state->color_encoding)
 9986			return true;
 9987
 9988		/* HDR/Transfer Function changes. */
 9989		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
 9990		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
 9991		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
 9992		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
 9993		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
 9994		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
 9995		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
 9996		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
 9997		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
 9998			return true;
 9999
10000		/* Framebuffer checks fall at the end. */
10001		if (!old_other_state->fb || !new_other_state->fb)
10002			continue;
10003
10004		/* Pixel format changes can require bandwidth updates. */
10005		if (old_other_state->fb->format != new_other_state->fb->format)
10006			return true;
10007
10008		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
10009		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
10010
10011		/* Tiling and DCC changes also require bandwidth updates. */
10012		if (old_afb->tiling_flags != new_afb->tiling_flags ||
10013		    old_afb->base.modifier != new_afb->base.modifier)
10014			return true;
10015	}
10016
10017	return false;
10018}
10019
10020static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
10021			      struct drm_plane_state *new_plane_state,
10022			      struct drm_framebuffer *fb)
10023{
10024	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
10025	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
10026	unsigned int pitch;
10027	bool linear;
10028
10029	if (fb->width > new_acrtc->max_cursor_width ||
10030	    fb->height > new_acrtc->max_cursor_height) {
10031		DRM_DEBUG_ATOMIC("Bad cursor FB size %dx%d\n",
10032				 new_plane_state->fb->width,
10033				 new_plane_state->fb->height);
10034		return -EINVAL;
10035	}
10036	if (new_plane_state->src_w != fb->width << 16 ||
10037	    new_plane_state->src_h != fb->height << 16) {
10038		DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
10039		return -EINVAL;
10040	}
10041
10042	/* Pitch in pixels */
10043	pitch = fb->pitches[0] / fb->format->cpp[0];
10044
10045	if (fb->width != pitch) {
10046		DRM_DEBUG_ATOMIC("Cursor FB width %d doesn't match pitch %d",
10047				 fb->width, pitch);
10048		return -EINVAL;
10049	}
10050
10051	switch (pitch) {
10052	case 64:
10053	case 128:
10054	case 256:
10055		/* FB pitch is supported by cursor plane */
10056		break;
10057	default:
10058		DRM_DEBUG_ATOMIC("Bad cursor FB pitch %d px\n", pitch);
10059		return -EINVAL;
10060	}
10061
10062	/* Core DRM takes care of checking FB modifiers, so we only need to
10063	 * check tiling flags when the FB doesn't have a modifier.
10064	 */
10065	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
10066		if (adev->family < AMDGPU_FAMILY_AI) {
10067			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
10068				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
10069				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
10070		} else {
10071			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
10072		}
10073		if (!linear) {
10074			DRM_DEBUG_ATOMIC("Cursor FB not linear");
10075			return -EINVAL;
10076		}
10077	}
10078
10079	return 0;
10080}
10081
10082static int dm_update_plane_state(struct dc *dc,
10083				 struct drm_atomic_state *state,
10084				 struct drm_plane *plane,
10085				 struct drm_plane_state *old_plane_state,
10086				 struct drm_plane_state *new_plane_state,
10087				 bool enable,
10088				 bool *lock_and_validation_needed,
10089				 bool *is_top_most_overlay)
10090{
10091
10092	struct dm_atomic_state *dm_state = NULL;
10093	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
10094	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10095	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
10096	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
10097	struct amdgpu_crtc *new_acrtc;
10098	bool needs_reset;
10099	int ret = 0;
10100
10101
10102	new_plane_crtc = new_plane_state->crtc;
10103	old_plane_crtc = old_plane_state->crtc;
10104	dm_new_plane_state = to_dm_plane_state(new_plane_state);
10105	dm_old_plane_state = to_dm_plane_state(old_plane_state);
10106
10107	if (plane->type == DRM_PLANE_TYPE_CURSOR) {
10108		if (!enable || !new_plane_crtc ||
10109			drm_atomic_plane_disabling(plane->state, new_plane_state))
10110			return 0;
10111
10112		new_acrtc = to_amdgpu_crtc(new_plane_crtc);
10113
10114		if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
10115			DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
10116			return -EINVAL;
10117		}
10118
10119		if (new_plane_state->fb) {
10120			ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
10121						 new_plane_state->fb);
10122			if (ret)
10123				return ret;
10124		}
10125
10126		return 0;
10127	}
10128
10129	needs_reset = should_reset_plane(state, plane, old_plane_state,
10130					 new_plane_state);
10131
10132	/* Remove any changed/removed planes */
10133	if (!enable) {
10134		if (!needs_reset)
10135			return 0;
10136
10137		if (!old_plane_crtc)
10138			return 0;
10139
10140		old_crtc_state = drm_atomic_get_old_crtc_state(
10141				state, old_plane_crtc);
10142		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10143
10144		if (!dm_old_crtc_state->stream)
10145			return 0;
10146
10147		DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
10148				plane->base.id, old_plane_crtc->base.id);
10149
10150		ret = dm_atomic_get_state(state, &dm_state);
10151		if (ret)
10152			return ret;
10153
10154		if (!dc_state_remove_plane(
10155				dc,
10156				dm_old_crtc_state->stream,
10157				dm_old_plane_state->dc_state,
10158				dm_state->context)) {
10159
10160			return -EINVAL;
10161		}
10162
10163		if (dm_old_plane_state->dc_state)
10164			dc_plane_state_release(dm_old_plane_state->dc_state);
10165
10166		dm_new_plane_state->dc_state = NULL;
10167
10168		*lock_and_validation_needed = true;
10169
10170	} else { /* Add new planes */
10171		struct dc_plane_state *dc_new_plane_state;
10172
10173		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
10174			return 0;
10175
10176		if (!new_plane_crtc)
10177			return 0;
10178
10179		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
10180		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10181
10182		if (!dm_new_crtc_state->stream)
10183			return 0;
10184
10185		if (!needs_reset)
10186			return 0;
10187
10188		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
10189		if (ret)
10190			return ret;
10191
10192		WARN_ON(dm_new_plane_state->dc_state);
10193
10194		dc_new_plane_state = dc_create_plane_state(dc);
10195		if (!dc_new_plane_state)
10196			return -ENOMEM;
10197
10198		/* Block top most plane from being a video plane */
10199		if (plane->type == DRM_PLANE_TYPE_OVERLAY) {
10200			if (amdgpu_dm_plane_is_video_format(new_plane_state->fb->format->format) && *is_top_most_overlay)
10201				return -EINVAL;
10202
10203			*is_top_most_overlay = false;
10204		}
10205
10206		DRM_DEBUG_ATOMIC("Enabling DRM plane: %d on DRM crtc %d\n",
10207				 plane->base.id, new_plane_crtc->base.id);
10208
10209		ret = fill_dc_plane_attributes(
10210			drm_to_adev(new_plane_crtc->dev),
10211			dc_new_plane_state,
10212			new_plane_state,
10213			new_crtc_state);
10214		if (ret) {
10215			dc_plane_state_release(dc_new_plane_state);
10216			return ret;
10217		}
10218
10219		ret = dm_atomic_get_state(state, &dm_state);
10220		if (ret) {
10221			dc_plane_state_release(dc_new_plane_state);
10222			return ret;
10223		}
10224
10225		/*
10226		 * Any atomic check errors that occur after this will
10227		 * not need a release. The plane state will be attached
10228		 * to the stream, and therefore part of the atomic
10229		 * state. It'll be released when the atomic state is
10230		 * cleaned.
10231		 */
10232		if (!dc_state_add_plane(
10233				dc,
10234				dm_new_crtc_state->stream,
10235				dc_new_plane_state,
10236				dm_state->context)) {
10237
10238			dc_plane_state_release(dc_new_plane_state);
10239			return -EINVAL;
10240		}
10241
10242		dm_new_plane_state->dc_state = dc_new_plane_state;
10243
10244		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
10245
10246		/* Tell DC to do a full surface update every time there
10247		 * is a plane change. Inefficient, but works for now.
10248		 */
10249		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
10250
10251		*lock_and_validation_needed = true;
10252	}
10253
10254
10255	return ret;
10256}
10257
10258static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
10259				       int *src_w, int *src_h)
10260{
10261	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
10262	case DRM_MODE_ROTATE_90:
10263	case DRM_MODE_ROTATE_270:
10264		*src_w = plane_state->src_h >> 16;
10265		*src_h = plane_state->src_w >> 16;
10266		break;
10267	case DRM_MODE_ROTATE_0:
10268	case DRM_MODE_ROTATE_180:
10269	default:
10270		*src_w = plane_state->src_w >> 16;
10271		*src_h = plane_state->src_h >> 16;
10272		break;
10273	}
10274}
10275
10276static void
10277dm_get_plane_scale(struct drm_plane_state *plane_state,
10278		   int *out_plane_scale_w, int *out_plane_scale_h)
10279{
10280	int plane_src_w, plane_src_h;
10281
10282	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
10283	*out_plane_scale_w = plane_state->crtc_w * 1000 / plane_src_w;
10284	*out_plane_scale_h = plane_state->crtc_h * 1000 / plane_src_h;
10285}
10286
10287static int dm_check_crtc_cursor(struct drm_atomic_state *state,
10288				struct drm_crtc *crtc,
10289				struct drm_crtc_state *new_crtc_state)
10290{
10291	struct drm_plane *cursor = crtc->cursor, *plane, *underlying;
10292	struct drm_plane_state *old_plane_state, *new_plane_state;
10293	struct drm_plane_state *new_cursor_state, *new_underlying_state;
10294	int i;
10295	int cursor_scale_w, cursor_scale_h, underlying_scale_w, underlying_scale_h;
10296	bool any_relevant_change = false;
10297
10298	/* On DCE and DCN there is no dedicated hardware cursor plane. We get a
10299	 * cursor per pipe but it's going to inherit the scaling and
10300	 * positioning from the underlying pipe. Check the cursor plane's
10301	 * blending properties match the underlying planes'.
10302	 */
10303
10304	/* If no plane was enabled or changed scaling, no need to check again */
10305	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
10306		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
10307
10308		if (!new_plane_state || !new_plane_state->fb || new_plane_state->crtc != crtc)
10309			continue;
10310
10311		if (!old_plane_state || !old_plane_state->fb || old_plane_state->crtc != crtc) {
10312			any_relevant_change = true;
10313			break;
10314		}
10315
10316		if (new_plane_state->fb == old_plane_state->fb &&
10317		    new_plane_state->crtc_w == old_plane_state->crtc_w &&
10318		    new_plane_state->crtc_h == old_plane_state->crtc_h)
10319			continue;
10320
10321		dm_get_plane_scale(new_plane_state, &new_scale_w, &new_scale_h);
10322		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
10323
10324		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
10325			any_relevant_change = true;
10326			break;
10327		}
10328	}
10329
10330	if (!any_relevant_change)
10331		return 0;
10332
10333	new_cursor_state = drm_atomic_get_plane_state(state, cursor);
10334	if (IS_ERR(new_cursor_state))
10335		return PTR_ERR(new_cursor_state);
10336
10337	if (!new_cursor_state->fb)
10338		return 0;
10339
10340	dm_get_plane_scale(new_cursor_state, &cursor_scale_w, &cursor_scale_h);
10341
10342	/* Need to check all enabled planes, even if this commit doesn't change
10343	 * their state
10344	 */
10345	i = drm_atomic_add_affected_planes(state, crtc);
10346	if (i)
10347		return i;
10348
10349	for_each_new_plane_in_state_reverse(state, underlying, new_underlying_state, i) {
10350		/* Narrow down to non-cursor planes on the same CRTC as the cursor */
10351		if (new_underlying_state->crtc != crtc || underlying == crtc->cursor)
10352			continue;
10353
10354		/* Ignore disabled planes */
10355		if (!new_underlying_state->fb)
10356			continue;
10357
10358		dm_get_plane_scale(new_underlying_state,
10359				   &underlying_scale_w, &underlying_scale_h);
10360
10361		if (cursor_scale_w != underlying_scale_w ||
10362		    cursor_scale_h != underlying_scale_h) {
10363			drm_dbg_atomic(crtc->dev,
10364				       "Cursor [PLANE:%d:%s] scaling doesn't match underlying [PLANE:%d:%s]\n",
10365				       cursor->base.id, cursor->name, underlying->base.id, underlying->name);
10366			return -EINVAL;
10367		}
10368
10369		/* If this plane covers the whole CRTC, no need to check planes underneath */
10370		if (new_underlying_state->crtc_x <= 0 &&
10371		    new_underlying_state->crtc_y <= 0 &&
10372		    new_underlying_state->crtc_x + new_underlying_state->crtc_w >= new_crtc_state->mode.hdisplay &&
10373		    new_underlying_state->crtc_y + new_underlying_state->crtc_h >= new_crtc_state->mode.vdisplay)
10374			break;
10375	}
10376
10377	return 0;
10378}
10379
10380static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
10381{
10382	struct drm_connector *connector;
10383	struct drm_connector_state *conn_state, *old_conn_state;
10384	struct amdgpu_dm_connector *aconnector = NULL;
10385	int i;
10386
10387	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
10388		if (!conn_state->crtc)
10389			conn_state = old_conn_state;
10390
10391		if (conn_state->crtc != crtc)
10392			continue;
10393
10394		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10395			continue;
10396
10397		aconnector = to_amdgpu_dm_connector(connector);
10398		if (!aconnector->mst_output_port || !aconnector->mst_root)
10399			aconnector = NULL;
10400		else
10401			break;
10402	}
10403
10404	if (!aconnector)
10405		return 0;
10406
10407	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
10408}
10409
10410/**
10411 * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
10412 *
10413 * @dev: The DRM device
10414 * @state: The atomic state to commit
10415 *
10416 * Validate that the given atomic state is programmable by DC into hardware.
10417 * This involves constructing a &struct dc_state reflecting the new hardware
10418 * state we wish to commit, then querying DC to see if it is programmable. It's
10419 * important not to modify the existing DC state. Otherwise, atomic_check
10420 * may unexpectedly commit hardware changes.
10421 *
10422 * When validating the DC state, it's important that the right locks are
10423 * acquired. For full updates case which removes/adds/updates streams on one
10424 * CRTC while flipping on another CRTC, acquiring global lock will guarantee
10425 * that any such full update commit will wait for completion of any outstanding
10426 * flip using DRMs synchronization events.
10427 *
10428 * Note that DM adds the affected connectors for all CRTCs in state, when that
10429 * might not seem necessary. This is because DC stream creation requires the
10430 * DC sink, which is tied to the DRM connector state. Cleaning this up should
10431 * be possible but non-trivial - a possible TODO item.
10432 *
10433 * Return: -Error code if validation failed.
10434 */
10435static int amdgpu_dm_atomic_check(struct drm_device *dev,
10436				  struct drm_atomic_state *state)
10437{
10438	struct amdgpu_device *adev = drm_to_adev(dev);
10439	struct dm_atomic_state *dm_state = NULL;
10440	struct dc *dc = adev->dm.dc;
10441	struct drm_connector *connector;
10442	struct drm_connector_state *old_con_state, *new_con_state;
10443	struct drm_crtc *crtc;
10444	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10445	struct drm_plane *plane;
10446	struct drm_plane_state *old_plane_state, *new_plane_state;
10447	enum dc_status status;
10448	int ret, i;
10449	bool lock_and_validation_needed = false;
10450	bool is_top_most_overlay = true;
10451	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10452	struct drm_dp_mst_topology_mgr *mgr;
10453	struct drm_dp_mst_topology_state *mst_state;
10454	struct dsc_mst_fairness_vars vars[MAX_PIPES];
10455
10456	trace_amdgpu_dm_atomic_check_begin(state);
10457
10458	ret = drm_atomic_helper_check_modeset(dev, state);
10459	if (ret) {
10460		DRM_DEBUG_DRIVER("drm_atomic_helper_check_modeset() failed\n");
10461		goto fail;
10462	}
10463
10464	/* Check connector changes */
10465	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10466		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
10467		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10468
10469		/* Skip connectors that are disabled or part of modeset already. */
10470		if (!new_con_state->crtc)
10471			continue;
10472
10473		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
10474		if (IS_ERR(new_crtc_state)) {
10475			DRM_DEBUG_DRIVER("drm_atomic_get_crtc_state() failed\n");
10476			ret = PTR_ERR(new_crtc_state);
10477			goto fail;
10478		}
10479
10480		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
10481		    dm_old_con_state->scaling != dm_new_con_state->scaling)
10482			new_crtc_state->connectors_changed = true;
10483	}
10484
10485	if (dc_resource_is_dsc_encoding_supported(dc)) {
10486		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10487			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
10488				ret = add_affected_mst_dsc_crtcs(state, crtc);
10489				if (ret) {
10490					DRM_DEBUG_DRIVER("add_affected_mst_dsc_crtcs() failed\n");
10491					goto fail;
10492				}
10493			}
10494		}
10495	}
10496	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10497		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10498
10499		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
10500		    !new_crtc_state->color_mgmt_changed &&
10501		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
10502			dm_old_crtc_state->dsc_force_changed == false)
10503			continue;
10504
10505		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
10506		if (ret) {
10507			DRM_DEBUG_DRIVER("amdgpu_dm_verify_lut_sizes() failed\n");
10508			goto fail;
10509		}
10510
10511		if (!new_crtc_state->enable)
10512			continue;
10513
10514		ret = drm_atomic_add_affected_connectors(state, crtc);
10515		if (ret) {
10516			DRM_DEBUG_DRIVER("drm_atomic_add_affected_connectors() failed\n");
10517			goto fail;
10518		}
10519
10520		ret = drm_atomic_add_affected_planes(state, crtc);
10521		if (ret) {
10522			DRM_DEBUG_DRIVER("drm_atomic_add_affected_planes() failed\n");
10523			goto fail;
10524		}
10525
10526		if (dm_old_crtc_state->dsc_force_changed)
10527			new_crtc_state->mode_changed = true;
10528	}
10529
10530	/*
10531	 * Add all primary and overlay planes on the CRTC to the state
10532	 * whenever a plane is enabled to maintain correct z-ordering
10533	 * and to enable fast surface updates.
10534	 */
10535	drm_for_each_crtc(crtc, dev) {
10536		bool modified = false;
10537
10538		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
10539			if (plane->type == DRM_PLANE_TYPE_CURSOR)
10540				continue;
10541
10542			if (new_plane_state->crtc == crtc ||
10543			    old_plane_state->crtc == crtc) {
10544				modified = true;
10545				break;
10546			}
10547		}
10548
10549		if (!modified)
10550			continue;
10551
10552		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
10553			if (plane->type == DRM_PLANE_TYPE_CURSOR)
10554				continue;
10555
10556			new_plane_state =
10557				drm_atomic_get_plane_state(state, plane);
10558
10559			if (IS_ERR(new_plane_state)) {
10560				ret = PTR_ERR(new_plane_state);
10561				DRM_DEBUG_DRIVER("new_plane_state is BAD\n");
10562				goto fail;
10563			}
10564		}
10565	}
10566
10567	/*
10568	 * DC consults the zpos (layer_index in DC terminology) to determine the
10569	 * hw plane on which to enable the hw cursor (see
10570	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
10571	 * atomic state, so call drm helper to normalize zpos.
10572	 */
10573	ret = drm_atomic_normalize_zpos(dev, state);
10574	if (ret) {
10575		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
10576		goto fail;
10577	}
10578
10579	/* Remove exiting planes if they are modified */
10580	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
10581		if (old_plane_state->fb && new_plane_state->fb &&
10582		    get_mem_type(old_plane_state->fb) !=
10583		    get_mem_type(new_plane_state->fb))
10584			lock_and_validation_needed = true;
10585
10586		ret = dm_update_plane_state(dc, state, plane,
10587					    old_plane_state,
10588					    new_plane_state,
10589					    false,
10590					    &lock_and_validation_needed,
10591					    &is_top_most_overlay);
10592		if (ret) {
10593			DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
10594			goto fail;
10595		}
10596	}
10597
10598	/* Disable all crtcs which require disable */
10599	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10600		ret = dm_update_crtc_state(&adev->dm, state, crtc,
10601					   old_crtc_state,
10602					   new_crtc_state,
10603					   false,
10604					   &lock_and_validation_needed);
10605		if (ret) {
10606			DRM_DEBUG_DRIVER("DISABLE: dm_update_crtc_state() failed\n");
10607			goto fail;
10608		}
10609	}
10610
10611	/* Enable all crtcs which require enable */
10612	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10613		ret = dm_update_crtc_state(&adev->dm, state, crtc,
10614					   old_crtc_state,
10615					   new_crtc_state,
10616					   true,
10617					   &lock_and_validation_needed);
10618		if (ret) {
10619			DRM_DEBUG_DRIVER("ENABLE: dm_update_crtc_state() failed\n");
10620			goto fail;
10621		}
10622	}
10623
10624	/* Add new/modified planes */
10625	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
10626		ret = dm_update_plane_state(dc, state, plane,
10627					    old_plane_state,
10628					    new_plane_state,
10629					    true,
10630					    &lock_and_validation_needed,
10631					    &is_top_most_overlay);
10632		if (ret) {
10633			DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
10634			goto fail;
10635		}
10636	}
10637
10638	if (dc_resource_is_dsc_encoding_supported(dc)) {
10639		ret = pre_validate_dsc(state, &dm_state, vars);
10640		if (ret != 0)
10641			goto fail;
10642	}
10643
10644	/* Run this here since we want to validate the streams we created */
10645	ret = drm_atomic_helper_check_planes(dev, state);
10646	if (ret) {
10647		DRM_DEBUG_DRIVER("drm_atomic_helper_check_planes() failed\n");
10648		goto fail;
10649	}
10650
10651	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10652		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10653		if (dm_new_crtc_state->mpo_requested)
10654			DRM_DEBUG_DRIVER("MPO enablement requested on crtc:[%p]\n", crtc);
10655	}
10656
10657	/* Check cursor planes scaling */
10658	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10659		ret = dm_check_crtc_cursor(state, crtc, new_crtc_state);
10660		if (ret) {
10661			DRM_DEBUG_DRIVER("dm_check_crtc_cursor() failed\n");
10662			goto fail;
10663		}
10664	}
10665
10666	if (state->legacy_cursor_update) {
10667		/*
10668		 * This is a fast cursor update coming from the plane update
10669		 * helper, check if it can be done asynchronously for better
10670		 * performance.
10671		 */
10672		state->async_update =
10673			!drm_atomic_helper_async_check(dev, state);
10674
10675		/*
10676		 * Skip the remaining global validation if this is an async
10677		 * update. Cursor updates can be done without affecting
10678		 * state or bandwidth calcs and this avoids the performance
10679		 * penalty of locking the private state object and
10680		 * allocating a new dc_state.
10681		 */
10682		if (state->async_update)
10683			return 0;
10684	}
10685
10686	/* Check scaling and underscan changes*/
10687	/* TODO Removed scaling changes validation due to inability to commit
10688	 * new stream into context w\o causing full reset. Need to
10689	 * decide how to handle.
10690	 */
10691	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10692		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
10693		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10694		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10695
10696		/* Skip any modesets/resets */
10697		if (!acrtc || drm_atomic_crtc_needs_modeset(
10698				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
10699			continue;
10700
10701		/* Skip any thing not scale or underscan changes */
10702		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
10703			continue;
10704
10705		lock_and_validation_needed = true;
10706	}
10707
10708	/* set the slot info for each mst_state based on the link encoding format */
10709	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
10710		struct amdgpu_dm_connector *aconnector;
10711		struct drm_connector *connector;
10712		struct drm_connector_list_iter iter;
10713		u8 link_coding_cap;
10714
10715		drm_connector_list_iter_begin(dev, &iter);
10716		drm_for_each_connector_iter(connector, &iter) {
10717			if (connector->index == mst_state->mgr->conn_base_id) {
10718				aconnector = to_amdgpu_dm_connector(connector);
10719				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
10720				drm_dp_mst_update_slots(mst_state, link_coding_cap);
10721
10722				break;
10723			}
10724		}
10725		drm_connector_list_iter_end(&iter);
10726	}
10727
10728	/**
10729	 * Streams and planes are reset when there are changes that affect
10730	 * bandwidth. Anything that affects bandwidth needs to go through
10731	 * DC global validation to ensure that the configuration can be applied
10732	 * to hardware.
10733	 *
10734	 * We have to currently stall out here in atomic_check for outstanding
10735	 * commits to finish in this case because our IRQ handlers reference
10736	 * DRM state directly - we can end up disabling interrupts too early
10737	 * if we don't.
10738	 *
10739	 * TODO: Remove this stall and drop DM state private objects.
10740	 */
10741	if (lock_and_validation_needed) {
10742		ret = dm_atomic_get_state(state, &dm_state);
10743		if (ret) {
10744			DRM_DEBUG_DRIVER("dm_atomic_get_state() failed\n");
10745			goto fail;
10746		}
10747
10748		ret = do_aquire_global_lock(dev, state);
10749		if (ret) {
10750			DRM_DEBUG_DRIVER("do_aquire_global_lock() failed\n");
10751			goto fail;
10752		}
10753
10754		if (dc_resource_is_dsc_encoding_supported(dc)) {
10755			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
10756			if (ret) {
10757				DRM_DEBUG_DRIVER("compute_mst_dsc_configs_for_state() failed\n");
10758				ret = -EINVAL;
10759				goto fail;
10760			}
10761		}
10762
10763		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
10764		if (ret) {
10765			DRM_DEBUG_DRIVER("dm_update_mst_vcpi_slots_for_dsc() failed\n");
10766			goto fail;
10767		}
10768
10769		/*
10770		 * Perform validation of MST topology in the state:
10771		 * We need to perform MST atomic check before calling
10772		 * dc_validate_global_state(), or there is a chance
10773		 * to get stuck in an infinite loop and hang eventually.
10774		 */
10775		ret = drm_dp_mst_atomic_check(state);
10776		if (ret) {
10777			DRM_DEBUG_DRIVER("drm_dp_mst_atomic_check() failed\n");
10778			goto fail;
10779		}
10780		status = dc_validate_global_state(dc, dm_state->context, true);
10781		if (status != DC_OK) {
10782			DRM_DEBUG_DRIVER("DC global validation failure: %s (%d)",
10783				       dc_status_to_str(status), status);
10784			ret = -EINVAL;
10785			goto fail;
10786		}
10787	} else {
10788		/*
10789		 * The commit is a fast update. Fast updates shouldn't change
10790		 * the DC context, affect global validation, and can have their
10791		 * commit work done in parallel with other commits not touching
10792		 * the same resource. If we have a new DC context as part of
10793		 * the DM atomic state from validation we need to free it and
10794		 * retain the existing one instead.
10795		 *
10796		 * Furthermore, since the DM atomic state only contains the DC
10797		 * context and can safely be annulled, we can free the state
10798		 * and clear the associated private object now to free
10799		 * some memory and avoid a possible use-after-free later.
10800		 */
10801
10802		for (i = 0; i < state->num_private_objs; i++) {
10803			struct drm_private_obj *obj = state->private_objs[i].ptr;
10804
10805			if (obj->funcs == adev->dm.atomic_obj.funcs) {
10806				int j = state->num_private_objs-1;
10807
10808				dm_atomic_destroy_state(obj,
10809						state->private_objs[i].state);
10810
10811				/* If i is not at the end of the array then the
10812				 * last element needs to be moved to where i was
10813				 * before the array can safely be truncated.
10814				 */
10815				if (i != j)
10816					state->private_objs[i] =
10817						state->private_objs[j];
10818
10819				state->private_objs[j].ptr = NULL;
10820				state->private_objs[j].state = NULL;
10821				state->private_objs[j].old_state = NULL;
10822				state->private_objs[j].new_state = NULL;
10823
10824				state->num_private_objs = j;
10825				break;
10826			}
10827		}
10828	}
10829
10830	/* Store the overall update type for use later in atomic check. */
10831	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10832		struct dm_crtc_state *dm_new_crtc_state =
10833			to_dm_crtc_state(new_crtc_state);
10834
10835		/*
10836		 * Only allow async flips for fast updates that don't change
10837		 * the FB pitch, the DCC state, rotation, etc.
10838		 */
10839		if (new_crtc_state->async_flip && lock_and_validation_needed) {
10840			drm_dbg_atomic(crtc->dev,
10841				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
10842				       crtc->base.id, crtc->name);
10843			ret = -EINVAL;
10844			goto fail;
10845		}
10846
10847		dm_new_crtc_state->update_type = lock_and_validation_needed ?
10848			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
10849	}
10850
10851	/* Must be success */
10852	WARN_ON(ret);
10853
10854	trace_amdgpu_dm_atomic_check_finish(state, ret);
10855
10856	return ret;
10857
10858fail:
10859	if (ret == -EDEADLK)
10860		DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
10861	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
10862		DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
10863	else
10864		DRM_DEBUG_DRIVER("Atomic check failed with err: %d\n", ret);
10865
10866	trace_amdgpu_dm_atomic_check_finish(state, ret);
10867
10868	return ret;
10869}
10870
10871static bool is_dp_capable_without_timing_msa(struct dc *dc,
10872					     struct amdgpu_dm_connector *amdgpu_dm_connector)
10873{
10874	u8 dpcd_data;
10875	bool capable = false;
10876
10877	if (amdgpu_dm_connector->dc_link &&
10878		dm_helpers_dp_read_dpcd(
10879				NULL,
10880				amdgpu_dm_connector->dc_link,
10881				DP_DOWN_STREAM_PORT_COUNT,
10882				&dpcd_data,
10883				sizeof(dpcd_data))) {
10884		capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
10885	}
10886
10887	return capable;
10888}
10889
10890static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
10891		unsigned int offset,
10892		unsigned int total_length,
10893		u8 *data,
10894		unsigned int length,
10895		struct amdgpu_hdmi_vsdb_info *vsdb)
10896{
10897	bool res;
10898	union dmub_rb_cmd cmd;
10899	struct dmub_cmd_send_edid_cea *input;
10900	struct dmub_cmd_edid_cea_output *output;
10901
10902	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
10903		return false;
10904
10905	memset(&cmd, 0, sizeof(cmd));
10906
10907	input = &cmd.edid_cea.data.input;
10908
10909	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
10910	cmd.edid_cea.header.sub_type = 0;
10911	cmd.edid_cea.header.payload_bytes =
10912		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
10913	input->offset = offset;
10914	input->length = length;
10915	input->cea_total_length = total_length;
10916	memcpy(input->payload, data, length);
10917
10918	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
10919	if (!res) {
10920		DRM_ERROR("EDID CEA parser failed\n");
10921		return false;
10922	}
10923
10924	output = &cmd.edid_cea.data.output;
10925
10926	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
10927		if (!output->ack.success) {
10928			DRM_ERROR("EDID CEA ack failed at offset %d\n",
10929					output->ack.offset);
10930		}
10931	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
10932		if (!output->amd_vsdb.vsdb_found)
10933			return false;
10934
10935		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
10936		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
10937		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
10938		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
10939	} else {
10940		DRM_WARN("Unknown EDID CEA parser results\n");
10941		return false;
10942	}
10943
10944	return true;
10945}
10946
10947static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
10948		u8 *edid_ext, int len,
10949		struct amdgpu_hdmi_vsdb_info *vsdb_info)
10950{
10951	int i;
10952
10953	/* send extension block to DMCU for parsing */
10954	for (i = 0; i < len; i += 8) {
10955		bool res;
10956		int offset;
10957
10958		/* send 8 bytes a time */
10959		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
10960			return false;
10961
10962		if (i+8 == len) {
10963			/* EDID block sent completed, expect result */
10964			int version, min_rate, max_rate;
10965
10966			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
10967			if (res) {
10968				/* amd vsdb found */
10969				vsdb_info->freesync_supported = 1;
10970				vsdb_info->amd_vsdb_version = version;
10971				vsdb_info->min_refresh_rate_hz = min_rate;
10972				vsdb_info->max_refresh_rate_hz = max_rate;
10973				return true;
10974			}
10975			/* not amd vsdb */
10976			return false;
10977		}
10978
10979		/* check for ack*/
10980		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
10981		if (!res)
10982			return false;
10983	}
10984
10985	return false;
10986}
10987
10988static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
10989		u8 *edid_ext, int len,
10990		struct amdgpu_hdmi_vsdb_info *vsdb_info)
10991{
10992	int i;
10993
10994	/* send extension block to DMCU for parsing */
10995	for (i = 0; i < len; i += 8) {
10996		/* send 8 bytes a time */
10997		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
10998			return false;
10999	}
11000
11001	return vsdb_info->freesync_supported;
11002}
11003
11004static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
11005		u8 *edid_ext, int len,
11006		struct amdgpu_hdmi_vsdb_info *vsdb_info)
11007{
11008	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
11009	bool ret;
11010
11011	mutex_lock(&adev->dm.dc_lock);
11012	if (adev->dm.dmub_srv)
11013		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
11014	else
11015		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
11016	mutex_unlock(&adev->dm.dc_lock);
11017	return ret;
11018}
11019
11020static int parse_amd_vsdb(struct amdgpu_dm_connector *aconnector,
11021			  struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
11022{
11023	u8 *edid_ext = NULL;
11024	int i;
11025	int j = 0;
11026
11027	if (edid == NULL || edid->extensions == 0)
11028		return -ENODEV;
11029
11030	/* Find DisplayID extension */
11031	for (i = 0; i < edid->extensions; i++) {
11032		edid_ext = (void *)(edid + (i + 1));
11033		if (edid_ext[0] == DISPLAYID_EXT)
11034			break;
11035	}
11036
11037	while (j < EDID_LENGTH) {
11038		struct amd_vsdb_block *amd_vsdb = (struct amd_vsdb_block *)&edid_ext[j];
11039		unsigned int ieeeId = (amd_vsdb->ieee_id[2] << 16) | (amd_vsdb->ieee_id[1] << 8) | (amd_vsdb->ieee_id[0]);
11040
11041		if (ieeeId == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_IEEE_REGISTRATION_ID &&
11042				amd_vsdb->version == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3) {
11043			vsdb_info->replay_mode = (amd_vsdb->feature_caps & AMD_VSDB_VERSION_3_FEATURECAP_REPLAYMODE) ? true : false;
11044			vsdb_info->amd_vsdb_version = HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3;
11045			DRM_DEBUG_KMS("Panel supports Replay Mode: %d\n", vsdb_info->replay_mode);
11046
11047			return true;
11048		}
11049		j++;
11050	}
11051
11052	return false;
11053}
11054
11055static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
11056		struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
11057{
11058	u8 *edid_ext = NULL;
11059	int i;
11060	bool valid_vsdb_found = false;
11061
11062	/*----- drm_find_cea_extension() -----*/
11063	/* No EDID or EDID extensions */
11064	if (edid == NULL || edid->extensions == 0)
11065		return -ENODEV;
11066
11067	/* Find CEA extension */
11068	for (i = 0; i < edid->extensions; i++) {
11069		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
11070		if (edid_ext[0] == CEA_EXT)
11071			break;
11072	}
11073
11074	if (i == edid->extensions)
11075		return -ENODEV;
11076
11077	/*----- cea_db_offsets() -----*/
11078	if (edid_ext[0] != CEA_EXT)
11079		return -ENODEV;
11080
11081	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
11082
11083	return valid_vsdb_found ? i : -ENODEV;
11084}
11085
11086/**
11087 * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
11088 *
11089 * @connector: Connector to query.
11090 * @edid: EDID from monitor
11091 *
11092 * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
11093 * track of some of the display information in the internal data struct used by
11094 * amdgpu_dm. This function checks which type of connector we need to set the
11095 * FreeSync parameters.
11096 */
11097void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
11098				    struct edid *edid)
11099{
11100	int i = 0;
11101	struct detailed_timing *timing;
11102	struct detailed_non_pixel *data;
11103	struct detailed_data_monitor_range *range;
11104	struct amdgpu_dm_connector *amdgpu_dm_connector =
11105			to_amdgpu_dm_connector(connector);
11106	struct dm_connector_state *dm_con_state = NULL;
11107	struct dc_sink *sink;
11108
11109	struct amdgpu_device *adev = drm_to_adev(connector->dev);
11110	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
11111	bool freesync_capable = false;
11112	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
11113
11114	if (!connector->state) {
11115		DRM_ERROR("%s - Connector has no state", __func__);
11116		goto update;
11117	}
11118
11119	sink = amdgpu_dm_connector->dc_sink ?
11120		amdgpu_dm_connector->dc_sink :
11121		amdgpu_dm_connector->dc_em_sink;
11122
11123	if (!edid || !sink) {
11124		dm_con_state = to_dm_connector_state(connector->state);
11125
11126		amdgpu_dm_connector->min_vfreq = 0;
11127		amdgpu_dm_connector->max_vfreq = 0;
11128		amdgpu_dm_connector->pixel_clock_mhz = 0;
11129		connector->display_info.monitor_range.min_vfreq = 0;
11130		connector->display_info.monitor_range.max_vfreq = 0;
11131		freesync_capable = false;
11132
11133		goto update;
11134	}
11135
11136	dm_con_state = to_dm_connector_state(connector->state);
11137
11138	if (!adev->dm.freesync_module)
11139		goto update;
11140
11141	if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
11142		|| sink->sink_signal == SIGNAL_TYPE_EDP) {
11143		bool edid_check_required = false;
11144
11145		if (edid) {
11146			edid_check_required = is_dp_capable_without_timing_msa(
11147						adev->dm.dc,
11148						amdgpu_dm_connector);
11149		}
11150
11151		if (edid_check_required == true && (edid->version > 1 ||
11152		   (edid->version == 1 && edid->revision > 1))) {
11153			for (i = 0; i < 4; i++) {
11154
11155				timing	= &edid->detailed_timings[i];
11156				data	= &timing->data.other_data;
11157				range	= &data->data.range;
11158				/*
11159				 * Check if monitor has continuous frequency mode
11160				 */
11161				if (data->type != EDID_DETAIL_MONITOR_RANGE)
11162					continue;
11163				/*
11164				 * Check for flag range limits only. If flag == 1 then
11165				 * no additional timing information provided.
11166				 * Default GTF, GTF Secondary curve and CVT are not
11167				 * supported
11168				 */
11169				if (range->flags != 1)
11170					continue;
11171
11172				connector->display_info.monitor_range.min_vfreq = range->min_vfreq;
11173				connector->display_info.monitor_range.max_vfreq = range->max_vfreq;
11174
11175				if (edid->revision >= 4) {
11176					if (data->pad2 & DRM_EDID_RANGE_OFFSET_MIN_VFREQ)
11177						connector->display_info.monitor_range.min_vfreq += 255;
11178					if (data->pad2 & DRM_EDID_RANGE_OFFSET_MAX_VFREQ)
11179						connector->display_info.monitor_range.max_vfreq += 255;
11180				}
11181
11182				amdgpu_dm_connector->min_vfreq =
11183					connector->display_info.monitor_range.min_vfreq;
11184				amdgpu_dm_connector->max_vfreq =
11185					connector->display_info.monitor_range.max_vfreq;
11186				amdgpu_dm_connector->pixel_clock_mhz =
11187					range->pixel_clock_mhz * 10;
11188
11189				break;
11190			}
11191
11192			if (amdgpu_dm_connector->max_vfreq -
11193			    amdgpu_dm_connector->min_vfreq > 10) {
11194
11195				freesync_capable = true;
11196			}
11197		}
11198		parse_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
11199
11200		if (vsdb_info.replay_mode) {
11201			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
11202			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
11203			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
11204		}
11205
11206	} else if (edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
11207		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
11208		if (i >= 0 && vsdb_info.freesync_supported) {
11209			timing  = &edid->detailed_timings[i];
11210			data    = &timing->data.other_data;
11211
11212			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
11213			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
11214			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
11215				freesync_capable = true;
11216
11217			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
11218			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
11219		}
11220	}
11221
11222	as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
11223
11224	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
11225		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
11226		if (i >= 0 && vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
11227
11228			amdgpu_dm_connector->pack_sdp_v1_3 = true;
11229			amdgpu_dm_connector->as_type = as_type;
11230			amdgpu_dm_connector->vsdb_info = vsdb_info;
11231
11232			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
11233			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
11234			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
11235				freesync_capable = true;
11236
11237			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
11238			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
11239		}
11240	}
11241
11242update:
11243	if (dm_con_state)
11244		dm_con_state->freesync_capable = freesync_capable;
11245
11246	if (connector->vrr_capable_property)
11247		drm_connector_set_vrr_capable_property(connector,
11248						       freesync_capable);
11249}
11250
11251void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
11252{
11253	struct amdgpu_device *adev = drm_to_adev(dev);
11254	struct dc *dc = adev->dm.dc;
11255	int i;
11256
11257	mutex_lock(&adev->dm.dc_lock);
11258	if (dc->current_state) {
11259		for (i = 0; i < dc->current_state->stream_count; ++i)
11260			dc->current_state->streams[i]
11261				->triggered_crtc_reset.enabled =
11262				adev->dm.force_timing_sync;
11263
11264		dm_enable_per_frame_crtc_master_sync(dc->current_state);
11265		dc_trigger_sync(dc, dc->current_state);
11266	}
11267	mutex_unlock(&adev->dm.dc_lock);
11268}
11269
11270void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
11271		       u32 value, const char *func_name)
11272{
11273#ifdef DM_CHECK_ADDR_0
11274	if (address == 0) {
11275		drm_err(adev_to_drm(ctx->driver_context),
11276			"invalid register write. address = 0");
11277		return;
11278	}
11279#endif
11280	cgs_write_register(ctx->cgs_device, address, value);
11281	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
11282}
11283
11284uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
11285			  const char *func_name)
11286{
11287	u32 value;
11288#ifdef DM_CHECK_ADDR_0
11289	if (address == 0) {
11290		drm_err(adev_to_drm(ctx->driver_context),
11291			"invalid register read; address = 0\n");
11292		return 0;
11293	}
11294#endif
11295
11296	if (ctx->dmub_srv &&
11297	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
11298	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
11299		ASSERT(false);
11300		return 0;
11301	}
11302
11303	value = cgs_read_register(ctx->cgs_device, address);
11304
11305	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
11306
11307	return value;
11308}
11309
11310int amdgpu_dm_process_dmub_aux_transfer_sync(
11311		struct dc_context *ctx,
11312		unsigned int link_index,
11313		struct aux_payload *payload,
11314		enum aux_return_code_type *operation_result)
11315{
11316	struct amdgpu_device *adev = ctx->driver_context;
11317	struct dmub_notification *p_notify = adev->dm.dmub_notify;
11318	int ret = -1;
11319
11320	mutex_lock(&adev->dm.dpia_aux_lock);
11321	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
11322		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
11323		goto out;
11324	}
11325
11326	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
11327		DRM_ERROR("wait_for_completion_timeout timeout!");
11328		*operation_result = AUX_RET_ERROR_TIMEOUT;
11329		goto out;
11330	}
11331
11332	if (p_notify->result != AUX_RET_SUCCESS) {
11333		/*
11334		 * Transient states before tunneling is enabled could
11335		 * lead to this error. We can ignore this for now.
11336		 */
11337		if (p_notify->result != AUX_RET_ERROR_PROTOCOL_ERROR) {
11338			DRM_WARN("DPIA AUX failed on 0x%x(%d), error %d\n",
11339					payload->address, payload->length,
11340					p_notify->result);
11341		}
11342		*operation_result = AUX_RET_ERROR_INVALID_REPLY;
11343		goto out;
11344	}
11345
11346
11347	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command;
11348	if (!payload->write && p_notify->aux_reply.length &&
11349			(payload->reply[0] == AUX_TRANSACTION_REPLY_AUX_ACK)) {
11350
11351		if (payload->length != p_notify->aux_reply.length) {
11352			DRM_WARN("invalid read length %d from DPIA AUX 0x%x(%d)!\n",
11353				p_notify->aux_reply.length,
11354					payload->address, payload->length);
11355			*operation_result = AUX_RET_ERROR_INVALID_REPLY;
11356			goto out;
11357		}
11358
11359		memcpy(payload->data, p_notify->aux_reply.data,
11360				p_notify->aux_reply.length);
11361	}
11362
11363	/* success */
11364	ret = p_notify->aux_reply.length;
11365	*operation_result = p_notify->result;
11366out:
11367	reinit_completion(&adev->dm.dmub_aux_transfer_done);
11368	mutex_unlock(&adev->dm.dpia_aux_lock);
11369	return ret;
11370}
11371
11372int amdgpu_dm_process_dmub_set_config_sync(
11373		struct dc_context *ctx,
11374		unsigned int link_index,
11375		struct set_config_cmd_payload *payload,
11376		enum set_config_status *operation_result)
11377{
11378	struct amdgpu_device *adev = ctx->driver_context;
11379	bool is_cmd_complete;
11380	int ret;
11381
11382	mutex_lock(&adev->dm.dpia_aux_lock);
11383	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
11384			link_index, payload, adev->dm.dmub_notify);
11385
11386	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
11387		ret = 0;
11388		*operation_result = adev->dm.dmub_notify->sc_status;
11389	} else {
11390		DRM_ERROR("wait_for_completion_timeout timeout!");
11391		ret = -1;
11392		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
11393	}
11394
11395	if (!is_cmd_complete)
11396		reinit_completion(&adev->dm.dmub_aux_transfer_done);
11397	mutex_unlock(&adev->dm.dpia_aux_lock);
11398	return ret;
11399}
11400
11401bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
11402{
11403	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
11404}
11405
11406bool dm_execute_dmub_cmd_list(const struct dc_context *ctx, unsigned int count, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
11407{
11408	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
11409}