1 /*
2 * Copyright (c) 2014 - 2016, The Linux Foundation. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *     * Redistributions of source code must retain the above copyright
8 *       notice, this list of conditions and the following disclaimer.
9 *     * Redistributions in binary form must reproduce the above
10 *       copyright notice, this list of conditions and the following
11 *       disclaimer in the documentation and/or other materials provided
12 *       with the distribution.
13 *     * Neither the name of The Linux Foundation nor the names of its
14 *       contributors may be used to endorse or promote products derived
15 *       from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
21 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
24 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
26 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
27 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29 
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <math.h>
33 #include <errno.h>
34 #include <gralloc_priv.h>
35 #include <gr.h>
36 #include <utils/constants.h>
37 #include <utils/formats.h>
38 #include <utils/rect.h>
39 #include <utils/debug.h>
40 #include <sync/sync.h>
41 #include <cutils/properties.h>
42 #include <map>
43 #include <utility>
44 #include <vector>
45 
46 #include "hwc_display.h"
47 #include "hwc_debugger.h"
48 #include "blit_engine_c2d.h"
49 
50 #ifdef QTI_BSP
51 #include <hardware/display_defs.h>
52 #endif
53 
54 #define __CLASS__ "HWCDisplay"
55 
56 namespace sdm {
57 
ApplyDeInterlaceAdjustment(Layer * layer)58 static void ApplyDeInterlaceAdjustment(Layer *layer) {
59   // De-interlacing adjustment
60   if (layer->input_buffer->flags.interlace) {
61     float height = (layer->src_rect.bottom - layer->src_rect.top) / 2.0f;
62     layer->src_rect.top = ROUND_UP_ALIGN_DOWN(layer->src_rect.top / 2.0f, 2);
63     layer->src_rect.bottom = layer->src_rect.top + floorf(height);
64   }
65 }
66 
HWCDisplay(CoreInterface * core_intf,hwc_procs_t const ** hwc_procs,DisplayType type,int id,bool needs_blit,qService::QService * qservice,DisplayClass display_class)67 HWCDisplay::HWCDisplay(CoreInterface *core_intf, hwc_procs_t const **hwc_procs, DisplayType type,
68                        int id, bool needs_blit, qService::QService *qservice,
69                        DisplayClass display_class)
70   : core_intf_(core_intf), hwc_procs_(hwc_procs), type_(type), id_(id), needs_blit_(needs_blit),
71     qservice_(qservice), display_class_(display_class) {
72 }
73 
Init()74 int HWCDisplay::Init() {
75   DisplayError error = core_intf_->CreateDisplay(type_, this, &display_intf_);
76   if (error != kErrorNone) {
77     DLOGE("Display create failed. Error = %d display_type %d event_handler %p disp_intf %p",
78       error, type_, this, &display_intf_);
79     return -EINVAL;
80   }
81 
82   int property_swap_interval = 1;
83   HWCDebugHandler::Get()->GetProperty("debug.egl.swapinterval", &property_swap_interval);
84   if (property_swap_interval == 0) {
85     swap_interval_zero_ = true;
86   }
87 
88   int blit_enabled = 0;
89   HWCDebugHandler::Get()->GetProperty("persist.hwc.blit.comp", &blit_enabled);
90   if (needs_blit_ && blit_enabled) {
91     blit_engine_ = new BlitEngineC2d();
92     if (!blit_engine_) {
93       DLOGI("Create Blit Engine C2D failed");
94     } else {
95       if (blit_engine_->Init() < 0) {
96         DLOGI("Blit Engine Init failed, Blit Composition will not be used!!");
97         delete blit_engine_;
98         blit_engine_ = NULL;
99       }
100     }
101   }
102 
103   display_intf_->GetRefreshRateRange(&min_refresh_rate_, &max_refresh_rate_);
104   current_refresh_rate_ = max_refresh_rate_;
105 
106   s3d_format_hwc_to_sdm_.insert(std::pair<int, LayerBufferS3DFormat>(HAL_NO_3D, kS3dFormatNone));
107   s3d_format_hwc_to_sdm_.insert(std::pair<int, LayerBufferS3DFormat>(HAL_3D_SIDE_BY_SIDE_L_R,
108                                 kS3dFormatLeftRight));
109   s3d_format_hwc_to_sdm_.insert(std::pair<int, LayerBufferS3DFormat>(HAL_3D_SIDE_BY_SIDE_R_L,
110                                 kS3dFormatRightLeft));
111   s3d_format_hwc_to_sdm_.insert(std::pair<int, LayerBufferS3DFormat>(HAL_3D_TOP_BOTTOM,
112                                 kS3dFormatTopBottom));
113 
114   return 0;
115 }
116 
Deinit()117 int HWCDisplay::Deinit() {
118   DisplayError error = core_intf_->DestroyDisplay(display_intf_);
119   if (error != kErrorNone) {
120     DLOGE("Display destroy failed. Error = %d", error);
121     return -EINVAL;
122   }
123 
124   if (blit_engine_) {
125     blit_engine_->DeInit();
126     delete blit_engine_;
127     blit_engine_ = NULL;
128   }
129 
130   return 0;
131 }
132 
EventControl(int event,int enable)133 int HWCDisplay::EventControl(int event, int enable) {
134   DisplayError error = kErrorNone;
135 
136   if (shutdown_pending_) {
137     return 0;
138   }
139 
140   switch (event) {
141   case HWC_EVENT_VSYNC:
142     error = display_intf_->SetVSyncState(enable);
143     break;
144   default:
145     DLOGW("Unsupported event = %d", event);
146   }
147 
148   if (error != kErrorNone) {
149     if (error == kErrorShutDown) {
150       shutdown_pending_ = true;
151       return 0;
152     }
153     DLOGE("Failed. event = %d, enable = %d, error = %d", event, enable, error);
154     return -EINVAL;
155   }
156 
157   return 0;
158 }
159 
SetPowerMode(int mode)160 int HWCDisplay::SetPowerMode(int mode) {
161   DLOGI("display = %d, mode = %d", id_, mode);
162   DisplayState state = kStateOff;
163   bool flush_on_error = flush_on_error_;
164 
165   if (shutdown_pending_) {
166     return 0;
167   }
168 
169   switch (mode) {
170   case HWC_POWER_MODE_OFF:
171     // During power off, all of the buffers are released.
172     // Do not flush until a buffer is successfully submitted again.
173     flush_on_error = false;
174     state = kStateOff;
175     break;
176 
177   case HWC_POWER_MODE_NORMAL:
178     state = kStateOn;
179     last_power_mode_ = HWC_POWER_MODE_NORMAL;
180     break;
181 
182   case HWC_POWER_MODE_DOZE:
183     state = kStateDoze;
184     last_power_mode_ = HWC_POWER_MODE_DOZE;
185     break;
186 
187   case HWC_POWER_MODE_DOZE_SUSPEND:
188     state = kStateDozeSuspend;
189     last_power_mode_ = HWC_POWER_MODE_DOZE_SUSPEND;
190     break;
191 
192   default:
193     return -EINVAL;
194   }
195 
196   DisplayError error = display_intf_->SetDisplayState(state);
197   if (error == kErrorNone) {
198     flush_on_error_ = flush_on_error;
199   } else {
200     if (error == kErrorShutDown) {
201       shutdown_pending_ = true;
202       return 0;
203     }
204     DLOGE("Set state failed. Error = %d", error);
205     return -EINVAL;
206   }
207 
208   return 0;
209 }
210 
GetDisplayConfigs(uint32_t * configs,size_t * num_configs)211 int HWCDisplay::GetDisplayConfigs(uint32_t *configs, size_t *num_configs) {
212   if (*num_configs > 0) {
213     configs[0] = 0;
214     *num_configs = 1;
215   }
216 
217   return 0;
218 }
219 
GetDisplayAttributes(uint32_t config,const uint32_t * display_attributes,int32_t * values)220 int HWCDisplay::GetDisplayAttributes(uint32_t config, const uint32_t *display_attributes,
221                                      int32_t *values) {
222   DisplayConfigVariableInfo variable_config;
223   DisplayError error = display_intf_->GetFrameBufferConfig(&variable_config);
224   if (error != kErrorNone) {
225     DLOGV("Get variable config failed. Error = %d", error);
226     return -EINVAL;
227   }
228 
229   for (int i = 0; display_attributes[i] != HWC_DISPLAY_NO_ATTRIBUTE; i++) {
230     switch (display_attributes[i]) {
231     case HWC_DISPLAY_VSYNC_PERIOD:
232       values[i] = INT32(variable_config.vsync_period_ns);
233       break;
234     case HWC_DISPLAY_WIDTH:
235       values[i] = INT32(variable_config.x_pixels);
236       break;
237     case HWC_DISPLAY_HEIGHT:
238       values[i] = INT32(variable_config.y_pixels);
239       break;
240     case HWC_DISPLAY_DPI_X:
241       values[i] = INT32(variable_config.x_dpi * 1000.0f);
242       break;
243     case HWC_DISPLAY_DPI_Y:
244       values[i] = INT32(variable_config.y_dpi * 1000.0f);
245       break;
246     default:
247       DLOGW("Spurious attribute type = %d", display_attributes[i]);
248       return -EINVAL;
249     }
250   }
251 
252   return 0;
253 }
254 
GetActiveConfig()255 int HWCDisplay::GetActiveConfig() {
256   return 0;
257 }
258 
SetActiveConfig(int index)259 int HWCDisplay::SetActiveConfig(int index) {
260   return -1;
261 }
262 
SetMixerResolution(uint32_t width,uint32_t height)263 DisplayError HWCDisplay::SetMixerResolution(uint32_t width, uint32_t height) {
264   return kErrorNotSupported;
265 }
266 
SetFrameDumpConfig(uint32_t count,uint32_t bit_mask_layer_type)267 void HWCDisplay::SetFrameDumpConfig(uint32_t count, uint32_t bit_mask_layer_type) {
268   dump_frame_count_ = count;
269   dump_frame_index_ = 0;
270   dump_input_layers_ = ((bit_mask_layer_type & (1 << INPUT_LAYER_DUMP)) != 0);
271 
272   if (blit_engine_) {
273     blit_engine_->SetFrameDumpConfig(count);
274   }
275 
276   DLOGI("num_frame_dump %d, input_layer_dump_enable %d", dump_frame_count_, dump_input_layers_);
277 }
278 
GetLastPowerMode()279 uint32_t HWCDisplay::GetLastPowerMode() {
280   return last_power_mode_;
281 }
282 
VSync(const DisplayEventVSync & vsync)283 DisplayError HWCDisplay::VSync(const DisplayEventVSync &vsync) {
284   const hwc_procs_t *hwc_procs = *hwc_procs_;
285 
286   if (!hwc_procs) {
287     return kErrorParameters;
288   }
289 
290   hwc_procs->vsync(hwc_procs, id_, vsync.timestamp);
291 
292   return kErrorNone;
293 }
294 
Refresh()295 DisplayError HWCDisplay::Refresh() {
296   return kErrorNotSupported;
297 }
298 
CECMessage(char * message)299 DisplayError HWCDisplay::CECMessage(char *message) {
300   if (qservice_) {
301     qservice_->onCECMessageReceived(message, 0);
302   } else {
303     DLOGW("Qservice instance not available.");
304   }
305 
306   return kErrorNone;
307 }
308 
AllocateLayerStack(hwc_display_contents_1_t * content_list)309 int HWCDisplay::AllocateLayerStack(hwc_display_contents_1_t *content_list) {
310   if (!content_list || !content_list->numHwLayers) {
311     DLOGW("Invalid content list");
312     return -EINVAL;
313   }
314 
315   size_t num_hw_layers = content_list->numHwLayers;
316   uint32_t blit_target_count = 0;
317 
318   if (blit_engine_) {
319     blit_target_count = kMaxBlitTargetLayers;
320   }
321 
322   FreeLayerStack();
323 
324   for (size_t i = 0; i < num_hw_layers + blit_target_count; i++) {
325     Layer *layer = new Layer();
326     LayerBuffer *layer_buffer = new LayerBuffer();
327     layer->input_buffer = layer_buffer;
328     layer_stack_.layers.push_back(layer);
329   }
330 
331   return 0;
332 }
333 
FreeLayerStack()334 void HWCDisplay::FreeLayerStack() {
335   for (Layer *layer : layer_stack_.layers) {
336     delete layer->input_buffer;
337     delete layer;
338   }
339   layer_stack_ = {};
340 }
341 
PrepareLayerParams(hwc_layer_1_t * hwc_layer,Layer * layer)342 int HWCDisplay::PrepareLayerParams(hwc_layer_1_t *hwc_layer, Layer* layer) {
343   const private_handle_t *pvt_handle = static_cast<const private_handle_t *>(hwc_layer->handle);
344 
345   LayerBuffer *layer_buffer = layer->input_buffer;
346 
347   if (pvt_handle) {
348     layer_buffer->format = GetSDMFormat(pvt_handle->format, pvt_handle->flags);
349     layer_buffer->width = UINT32(pvt_handle->width);
350     layer_buffer->height = UINT32(pvt_handle->height);
351 
352     if (SetMetaData(pvt_handle, layer) != kErrorNone) {
353       return -EINVAL;
354     }
355 
356     if (pvt_handle->bufferType == BUFFER_TYPE_VIDEO) {
357       layer_stack_.flags.video_present = true;
358       layer_buffer->flags.video = true;
359     }
360     // TZ Protected Buffer - L1
361     if (pvt_handle->flags & private_handle_t::PRIV_FLAGS_SECURE_BUFFER) {
362       layer_stack_.flags.secure_present = true;
363       layer_buffer->flags.secure = true;
364     }
365     // Gralloc Usage Protected Buffer - L3 - which needs to be treated as Secure & avoid fallback
366     if (pvt_handle->flags & private_handle_t::PRIV_FLAGS_PROTECTED_BUFFER) {
367       layer_stack_.flags.secure_present = true;
368     }
369     if (pvt_handle->flags & private_handle_t::PRIV_FLAGS_SECURE_DISPLAY) {
370       layer_buffer->flags.secure_display = true;
371     }
372 
373     // check if this is special solid_fill layer without input_buffer.
374     if (solid_fill_enable_ && pvt_handle->fd == -1) {
375       layer->flags.solid_fill = true;
376       layer->solid_fill_color = solid_fill_color_;
377     }
378   } else {
379     // for FBT layer
380     if (hwc_layer->compositionType == HWC_FRAMEBUFFER_TARGET) {
381       uint32_t x_pixels;
382       uint32_t y_pixels;
383       int aligned_width;
384       int aligned_height;
385       int usage = GRALLOC_USAGE_HW_FB;
386       int format = HAL_PIXEL_FORMAT_RGBA_8888;
387       int ubwc_enabled = 0;
388       int flags = 0;
389       HWCDebugHandler::Get()->GetProperty("debug.gralloc.enable_fb_ubwc", &ubwc_enabled);
390       if (ubwc_enabled == 1) {
391         usage |= GRALLOC_USAGE_PRIVATE_ALLOC_UBWC;
392         flags |= private_handle_t::PRIV_FLAGS_UBWC_ALIGNED;
393       }
394 
395       GetFrameBufferResolution(&x_pixels, &y_pixels);
396 
397       AdrenoMemInfo::getInstance().getAlignedWidthAndHeight(INT(x_pixels), INT(y_pixels), format,
398                                                             usage, aligned_width, aligned_height);
399       layer_buffer->width = UINT32(aligned_width);
400       layer_buffer->height = UINT32(aligned_height);
401       layer_buffer->format = GetSDMFormat(format, flags);
402     }
403   }
404 
405   return 0;
406 }
407 
CommitLayerParams(hwc_layer_1_t * hwc_layer,Layer * layer)408 void HWCDisplay::CommitLayerParams(hwc_layer_1_t *hwc_layer, Layer *layer) {
409   const private_handle_t *pvt_handle = static_cast<const private_handle_t *>(hwc_layer->handle);
410   LayerBuffer *layer_buffer = layer->input_buffer;
411 
412   if (pvt_handle) {
413     layer_buffer->planes[0].fd = pvt_handle->fd;
414     layer_buffer->planes[0].offset = pvt_handle->offset;
415     layer_buffer->planes[0].stride = UINT32(pvt_handle->width);
416     layer_buffer->size = pvt_handle->size;
417   }
418 
419   // if swapinterval property is set to 0 then close and reset the acquireFd
420   if (swap_interval_zero_ && hwc_layer->acquireFenceFd >= 0) {
421     close(hwc_layer->acquireFenceFd);
422     hwc_layer->acquireFenceFd = -1;
423   }
424   layer_buffer->acquire_fence_fd = hwc_layer->acquireFenceFd;
425 }
426 
PrePrepareLayerStack(hwc_display_contents_1_t * content_list)427 int HWCDisplay::PrePrepareLayerStack(hwc_display_contents_1_t *content_list) {
428   if (shutdown_pending_) {
429     return 0;
430   }
431 
432   size_t num_hw_layers = content_list->numHwLayers;
433 
434   use_blit_comp_ = false;
435   metadata_refresh_rate_ = 0;
436   display_rect_ = LayerRect();
437 
438   // Configure each layer
439   for (size_t i = 0; i < num_hw_layers; i++) {
440     hwc_layer_1_t &hwc_layer = content_list->hwLayers[i];
441 
442     Layer *layer = layer_stack_.layers.at(i);
443     int ret = PrepareLayerParams(&content_list->hwLayers[i], layer);
444 
445     if (ret != kErrorNone) {
446       return ret;
447     }
448 
449     layer->flags.skip = ((hwc_layer.flags & HWC_SKIP_LAYER) > 0);
450     layer->flags.solid_fill = (hwc_layer.flags & kDimLayer) || solid_fill_enable_;
451     if (layer->flags.skip || layer->flags.solid_fill) {
452       layer->dirty_regions.clear();
453     }
454 
455     hwc_rect_t scaled_display_frame = hwc_layer.displayFrame;
456     ApplyScanAdjustment(&scaled_display_frame);
457 
458     SetRect(scaled_display_frame, &layer->dst_rect);
459     SetRect(hwc_layer.sourceCropf, &layer->src_rect);
460     ApplyDeInterlaceAdjustment(layer);
461 
462     uint32_t num_visible_rects = UINT32(hwc_layer.visibleRegionScreen.numRects);
463     uint32_t num_dirty_rects = UINT32(hwc_layer.surfaceDamage.numRects);
464 
465     for (uint32_t j = 0; j < num_visible_rects; j++) {
466       LayerRect visible_rect = {};
467       SetRect(hwc_layer.visibleRegionScreen.rects[j], &visible_rect);
468       layer->visible_regions.push_back(visible_rect);
469     }
470 
471     for (uint32_t j = 0; j < num_dirty_rects; j++) {
472       LayerRect dirty_rect = {};
473       SetRect(hwc_layer.surfaceDamage.rects[j], &dirty_rect);
474       layer->dirty_regions.push_back(dirty_rect);
475     }
476 
477     if (blit_engine_) {
478       for (uint32_t j = 0; j < kMaxBlitTargetLayers; j++) {
479         LayerRect blit_rect = {};
480         layer->blit_regions.push_back(blit_rect);
481       }
482     }
483 
484     SetComposition(hwc_layer.compositionType, &layer->composition);
485     if (hwc_layer.compositionType != HWC_FRAMEBUFFER_TARGET) {
486       display_rect_ = Union(display_rect_, layer->dst_rect);
487     }
488 
489     // For dim layers, SurfaceFlinger
490     //    - converts planeAlpha to per pixel alpha,
491     //    - sets RGB color to 000,
492     //    - sets planeAlpha to 0xff,
493     //    - blending to Premultiplied.
494     // This can be achieved at hardware by
495     //    - solid fill ARGB to 0xff000000,
496     //    - incoming planeAlpha,
497     //    - blending to Coverage.
498     if (hwc_layer.flags & kDimLayer) {
499       layer->input_buffer->format = kFormatARGB8888;
500       layer->solid_fill_color = 0xff000000;
501       SetBlending(HWC_BLENDING_COVERAGE, &layer->blending);
502     } else {
503       SetBlending(hwc_layer.blending, &layer->blending);
504       LayerTransform &layer_transform = layer->transform;
505       uint32_t &hwc_transform = hwc_layer.transform;
506       layer_transform.flip_horizontal = ((hwc_transform & HWC_TRANSFORM_FLIP_H) > 0);
507       layer_transform.flip_vertical = ((hwc_transform & HWC_TRANSFORM_FLIP_V) > 0);
508       layer_transform.rotation = ((hwc_transform & HWC_TRANSFORM_ROT_90) ? 90.0f : 0.0f);
509     }
510 
511     // TODO(user): Remove below block.
512     // For solid fill, only dest rect need to be specified.
513     if (layer->flags.solid_fill) {
514       LayerBuffer *input_buffer = layer->input_buffer;
515       input_buffer->width = UINT32(layer->dst_rect.right - layer->dst_rect.left);
516       input_buffer->height = UINT32(layer->dst_rect.bottom - layer->dst_rect.top);
517       layer->src_rect.left = 0;
518       layer->src_rect.top = 0;
519       layer->src_rect.right = input_buffer->width;
520       layer->src_rect.bottom = input_buffer->height;
521     }
522 
523     layer->plane_alpha = hwc_layer.planeAlpha;
524     layer->flags.cursor = ((hwc_layer.flags & HWC_IS_CURSOR_LAYER) > 0);
525     layer->flags.updating = true;
526 
527     if (num_hw_layers <= kMaxLayerCount) {
528       layer->flags.updating = IsLayerUpdating(content_list, layer);
529     }
530 #ifdef QTI_BSP
531     if (hwc_layer.flags & HWC_SCREENSHOT_ANIMATOR_LAYER) {
532       layer_stack_.flags.animating = true;
533     }
534 #endif
535     if (layer->flags.skip) {
536       layer_stack_.flags.skip_present = true;
537     }
538 
539     if (layer->flags.cursor) {
540       layer_stack_.flags.cursor_present = true;
541     }
542 
543     PrepareDynamicRefreshRate(layer);
544 
545     layer->input_buffer->buffer_id = reinterpret_cast<uint64_t>(hwc_layer.handle);
546   }
547 
548   // Prepare the Blit Target
549   if (blit_engine_) {
550   // TODO(user): Fix this to enable BLIT
551 #if 0
552     int ret = blit_engine_->Prepare(&layer_stack_);
553     if (ret) {
554       // Blit engine cannot handle this layer stack, hence set the layer stack
555       // count to num_hw_layers
556       layer_stack_.layer_count -= kMaxBlitTargetLayers;
557     } else {
558       use_blit_comp_ = true;
559     }
560 #endif
561   }
562 
563   // Configure layer stack
564   layer_stack_.flags.geometry_changed = ((content_list->flags & HWC_GEOMETRY_CHANGED) > 0);
565 
566   return 0;
567 }
568 
PrepareLayerStack(hwc_display_contents_1_t * content_list)569 int HWCDisplay::PrepareLayerStack(hwc_display_contents_1_t *content_list) {
570   if (shutdown_pending_) {
571     return 0;
572   }
573 
574   size_t num_hw_layers = content_list->numHwLayers;
575 
576   if (!skip_prepare_) {
577     DisplayError error = display_intf_->Prepare(&layer_stack_);
578     if (error != kErrorNone) {
579       if (error == kErrorShutDown) {
580         shutdown_pending_ = true;
581       } else if (error != kErrorPermission) {
582         DLOGE("Prepare failed. Error = %d", error);
583         // To prevent surfaceflinger infinite wait, flush the previous frame during Commit()
584         // so that previous buffer and fences are released, and override the error.
585         flush_ = true;
586       }
587 
588       return 0;
589     }
590   } else {
591     // Skip is not set
592     MarkLayersForGPUBypass(content_list);
593     skip_prepare_ = false;
594     DLOGI("SecureDisplay %s, Skip Prepare/Commit and Flush", secure_display_active_ ? "Starting" :
595           "Stopping");
596     flush_ = true;
597   }
598 
599   for (size_t i = 0; i < num_hw_layers; i++) {
600     hwc_layer_1_t &hwc_layer = content_list->hwLayers[i];
601     Layer *layer = layer_stack_.layers.at(i);
602     LayerComposition composition = layer->composition;
603 
604     if ((composition == kCompositionSDE) || (composition == kCompositionHybrid) ||
605         (composition == kCompositionBlit)) {
606       hwc_layer.hints |= HWC_HINT_CLEAR_FB;
607     }
608     SetComposition(composition, &hwc_layer.compositionType);
609   }
610 
611   return 0;
612 }
613 
CommitLayerStack(hwc_display_contents_1_t * content_list)614 int HWCDisplay::CommitLayerStack(hwc_display_contents_1_t *content_list) {
615   if (!content_list || !content_list->numHwLayers) {
616     DLOGW("Invalid content list");
617     return -EINVAL;
618   }
619 
620   if (shutdown_pending_) {
621     return 0;
622   }
623 
624   int status = 0;
625 
626   size_t num_hw_layers = content_list->numHwLayers;
627 
628   DumpInputBuffers(content_list);
629 
630   if (!flush_) {
631     for (size_t i = 0; i < num_hw_layers; i++) {
632       CommitLayerParams(&content_list->hwLayers[i], layer_stack_.layers.at(i));
633     }
634 
635     if (use_blit_comp_) {
636       status = blit_engine_->PreCommit(content_list, &layer_stack_);
637       if (status == 0) {
638         status = blit_engine_->Commit(content_list, &layer_stack_);
639         if (status != 0) {
640           DLOGE("Blit Comp Failed!");
641         }
642       }
643     }
644 
645     DisplayError error = kErrorUndefined;
646     if (status == 0) {
647       error = display_intf_->Commit(&layer_stack_);
648       status = 0;
649     }
650 
651     if (error == kErrorNone) {
652       // A commit is successfully submitted, start flushing on failure now onwards.
653       flush_on_error_ = true;
654     } else {
655       if (error == kErrorShutDown) {
656         shutdown_pending_ = true;
657         return status;
658       } else if (error != kErrorPermission) {
659         DLOGE("Commit failed. Error = %d", error);
660         // To prevent surfaceflinger infinite wait, flush the previous frame during Commit()
661         // so that previous buffer and fences are released, and override the error.
662         flush_ = true;
663       }
664     }
665   }
666 
667   return status;
668 }
669 
PostCommitLayerStack(hwc_display_contents_1_t * content_list)670 int HWCDisplay::PostCommitLayerStack(hwc_display_contents_1_t *content_list) {
671   size_t num_hw_layers = content_list->numHwLayers;
672   int status = 0;
673 
674   // Do no call flush on errors, if a successful buffer is never submitted.
675   if (flush_ && flush_on_error_) {
676     display_intf_->Flush();
677   }
678 
679   // Set the release fence fd to the blit engine
680   if (use_blit_comp_ && blit_engine_->BlitActive()) {
681     blit_engine_->PostCommit(&layer_stack_);
682   }
683 
684   for (size_t i = 0; i < num_hw_layers; i++) {
685     hwc_layer_1_t &hwc_layer = content_list->hwLayers[i];
686     Layer *layer = layer_stack_.layers.at(i);
687     LayerBuffer *layer_buffer = layer->input_buffer;
688 
689     if (!flush_) {
690       // If swapinterval property is set to 0 or for single buffer layers, do not update f/w
691       // release fences and discard fences from driver
692       if (swap_interval_zero_ || layer->flags.single_buffer) {
693         hwc_layer.releaseFenceFd = -1;
694         close(layer_buffer->release_fence_fd);
695         layer_buffer->release_fence_fd = -1;
696       } else if (layer->composition != kCompositionGPU) {
697         hwc_layer.releaseFenceFd = layer_buffer->release_fence_fd;
698       }
699 
700       // During animation on external/virtual display, SDM will use the cached
701       // framebuffer layer throughout animation and do not allow framework to do eglswapbuffer on
702       // framebuffer target. So graphics doesn't close the release fence fd of framebuffer target,
703       // Hence close the release fencefd of framebuffer target here.
704       if (layer->composition == kCompositionGPUTarget && animating_) {
705         close(hwc_layer.releaseFenceFd);
706         hwc_layer.releaseFenceFd = -1;
707       }
708     }
709 
710     if (hwc_layer.acquireFenceFd >= 0) {
711       close(hwc_layer.acquireFenceFd);
712       hwc_layer.acquireFenceFd = -1;
713     }
714   }
715 
716   if (!flush_) {
717     animating_ = layer_stack_.flags.animating;
718     // if swapinterval property is set to 0 then close and reset the list retire fence
719     if (swap_interval_zero_) {
720       close(layer_stack_.retire_fence_fd);
721       layer_stack_.retire_fence_fd = -1;
722     }
723     content_list->retireFenceFd = layer_stack_.retire_fence_fd;
724 
725     if (dump_frame_count_) {
726       dump_frame_count_--;
727       dump_frame_index_++;
728     }
729   }
730 
731   flush_ = false;
732 
733   return status;
734 }
735 
IsLayerUpdating(hwc_display_contents_1_t * content_list,const Layer * layer)736 bool HWCDisplay::IsLayerUpdating(hwc_display_contents_1_t *content_list, const Layer *layer) {
737   // Layer should be considered updating if
738   //   a) layer is in single buffer mode, or
739   //   b) valid dirty_regions(android specific hint for updating status), or
740   //   c) layer stack geometry has changed
741   return (layer->flags.single_buffer || IsSurfaceUpdated(layer->dirty_regions) ||
742          (layer_stack_.flags.geometry_changed));
743 }
744 
SetRect(const hwc_rect_t & source,LayerRect * target)745 void HWCDisplay::SetRect(const hwc_rect_t &source, LayerRect *target) {
746   target->left = FLOAT(source.left);
747   target->top = FLOAT(source.top);
748   target->right = FLOAT(source.right);
749   target->bottom = FLOAT(source.bottom);
750 }
751 
SetRect(const hwc_frect_t & source,LayerRect * target)752 void HWCDisplay::SetRect(const hwc_frect_t &source, LayerRect *target) {
753   target->left = floorf(source.left);
754   target->top = floorf(source.top);
755   target->right = ceilf(source.right);
756   target->bottom = ceilf(source.bottom);
757 }
758 
SetComposition(const int32_t & source,LayerComposition * target)759 void HWCDisplay::SetComposition(const int32_t &source, LayerComposition *target) {
760   switch (source) {
761   case HWC_FRAMEBUFFER_TARGET:  *target = kCompositionGPUTarget;  break;
762   default:                      *target = kCompositionGPU;        break;
763   }
764 }
765 
SetComposition(const LayerComposition & source,int32_t * target)766 void HWCDisplay::SetComposition(const LayerComposition &source, int32_t *target) {
767   switch (source) {
768   case kCompositionGPUTarget:   *target = HWC_FRAMEBUFFER_TARGET; break;
769   case kCompositionGPU:         *target = HWC_FRAMEBUFFER;        break;
770   case kCompositionHWCursor:    *target = HWC_CURSOR_OVERLAY;     break;
771   default:                      *target = HWC_OVERLAY;            break;
772   }
773 }
774 
SetBlending(const int32_t & source,LayerBlending * target)775 void HWCDisplay::SetBlending(const int32_t &source, LayerBlending *target) {
776   switch (source) {
777   case HWC_BLENDING_PREMULT:    *target = kBlendingPremultiplied;   break;
778   case HWC_BLENDING_COVERAGE:   *target = kBlendingCoverage;        break;
779   default:                      *target = kBlendingOpaque;          break;
780   }
781 }
782 
SetIdleTimeoutMs(uint32_t timeout_ms)783 void HWCDisplay::SetIdleTimeoutMs(uint32_t timeout_ms) {
784   return;
785 }
786 
SetMaxMixerStages(uint32_t max_mixer_stages)787 DisplayError HWCDisplay::SetMaxMixerStages(uint32_t max_mixer_stages) {
788   DisplayError error = kErrorNone;
789 
790   if (display_intf_) {
791     error = display_intf_->SetMaxMixerStages(max_mixer_stages);
792   }
793 
794   return error;
795 }
796 
GetSDMFormat(const int32_t & source,const int flags)797 LayerBufferFormat HWCDisplay::GetSDMFormat(const int32_t &source, const int flags) {
798   LayerBufferFormat format = kFormatInvalid;
799   if (flags & private_handle_t::PRIV_FLAGS_UBWC_ALIGNED) {
800     switch (source) {
801     case HAL_PIXEL_FORMAT_RGBA_8888:           format = kFormatRGBA8888Ubwc;            break;
802     case HAL_PIXEL_FORMAT_RGBX_8888:           format = kFormatRGBX8888Ubwc;            break;
803     case HAL_PIXEL_FORMAT_BGR_565:             format = kFormatBGR565Ubwc;              break;
804     case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS:
805     case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC:
806     case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:     format = kFormatYCbCr420SPVenusUbwc;     break;
807     case HAL_PIXEL_FORMAT_RGBA_1010102:        format = kFormatRGBA1010102Ubwc;         break;
808     case HAL_PIXEL_FORMAT_RGBX_1010102:        format = kFormatRGBX1010102Ubwc;         break;
809     case HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC: format = kFormatYCbCr420TP10Ubwc;        break;
810     default:
811       DLOGE("Unsupported format type for UBWC %d", source);
812       return kFormatInvalid;
813     }
814     return format;
815   }
816 
817   switch (source) {
818   case HAL_PIXEL_FORMAT_RGBA_8888:                format = kFormatRGBA8888;                 break;
819   case HAL_PIXEL_FORMAT_RGBA_5551:                format = kFormatRGBA5551;                 break;
820   case HAL_PIXEL_FORMAT_RGBA_4444:                format = kFormatRGBA4444;                 break;
821   case HAL_PIXEL_FORMAT_BGRA_8888:                format = kFormatBGRA8888;                 break;
822   case HAL_PIXEL_FORMAT_RGBX_8888:                format = kFormatRGBX8888;                 break;
823   case HAL_PIXEL_FORMAT_BGRX_8888:                format = kFormatBGRX8888;                 break;
824   case HAL_PIXEL_FORMAT_RGB_888:                  format = kFormatRGB888;                   break;
825   case HAL_PIXEL_FORMAT_RGB_565:                  format = kFormatRGB565;                   break;
826   case HAL_PIXEL_FORMAT_BGR_565:                  format = kFormatBGR565;                   break;
827   case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
828   case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS:       format = kFormatYCbCr420SemiPlanarVenus;  break;
829   case HAL_PIXEL_FORMAT_YCrCb_420_SP_VENUS:       format = kFormatYCrCb420SemiPlanarVenus;  break;
830   case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC:  format = kFormatYCbCr420SPVenusUbwc;      break;
831   case HAL_PIXEL_FORMAT_YV12:                     format = kFormatYCrCb420PlanarStride16;   break;
832   case HAL_PIXEL_FORMAT_YCrCb_420_SP:             format = kFormatYCrCb420SemiPlanar;       break;
833   case HAL_PIXEL_FORMAT_YCbCr_420_SP:             format = kFormatYCbCr420SemiPlanar;       break;
834   case HAL_PIXEL_FORMAT_YCbCr_422_SP:             format = kFormatYCbCr422H2V1SemiPlanar;   break;
835   case HAL_PIXEL_FORMAT_YCbCr_422_I:              format = kFormatYCbCr422H2V1Packed;       break;
836   case HAL_PIXEL_FORMAT_RGBA_1010102:             format = kFormatRGBA1010102;              break;
837   case HAL_PIXEL_FORMAT_ARGB_2101010:             format = kFormatARGB2101010;              break;
838   case HAL_PIXEL_FORMAT_RGBX_1010102:             format = kFormatRGBX1010102;              break;
839   case HAL_PIXEL_FORMAT_XRGB_2101010:             format = kFormatXRGB2101010;              break;
840   case HAL_PIXEL_FORMAT_BGRA_1010102:             format = kFormatBGRA1010102;              break;
841   case HAL_PIXEL_FORMAT_ABGR_2101010:             format = kFormatABGR2101010;              break;
842   case HAL_PIXEL_FORMAT_BGRX_1010102:             format = kFormatBGRX1010102;              break;
843   case HAL_PIXEL_FORMAT_XBGR_2101010:             format = kFormatXBGR2101010;              break;
844   case HAL_PIXEL_FORMAT_YCbCr_420_P010:           format = kFormatYCbCr420P010;             break;
845   case HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC:      format = kFormatYCbCr420TP10Ubwc;         break;
846   default:
847     DLOGW("Unsupported format type = %d", source);
848     return kFormatInvalid;
849   }
850 
851   return format;
852 }
853 
DumpInputBuffers(hwc_display_contents_1_t * content_list)854 void HWCDisplay::DumpInputBuffers(hwc_display_contents_1_t *content_list) {
855   size_t num_hw_layers = content_list->numHwLayers;
856   char dir_path[PATH_MAX];
857 
858   if (!dump_frame_count_ || flush_ || !dump_input_layers_) {
859     return;
860   }
861 
862   snprintf(dir_path, sizeof(dir_path), "/data/misc/display/frame_dump_%s", GetDisplayString());
863 
864   if (mkdir(dir_path, 0777) != 0 && errno != EEXIST) {
865     DLOGW("Failed to create %s directory errno = %d, desc = %s", dir_path, errno, strerror(errno));
866     return;
867   }
868 
869   // if directory exists already, need to explicitly change the permission.
870   if (errno == EEXIST && chmod(dir_path, 0777) != 0) {
871     DLOGW("Failed to change permissions on %s directory", dir_path);
872     return;
873   }
874 
875   for (uint32_t i = 0; i < num_hw_layers; i++) {
876     hwc_layer_1_t &hwc_layer = content_list->hwLayers[i];
877     const private_handle_t *pvt_handle = static_cast<const private_handle_t *>(hwc_layer.handle);
878 
879     if (hwc_layer.acquireFenceFd >= 0) {
880       int error = sync_wait(hwc_layer.acquireFenceFd, 1000);
881       if (error < 0) {
882         DLOGW("sync_wait error errno = %d, desc = %s", errno, strerror(errno));
883         return;
884       }
885     }
886 
887     if (pvt_handle && pvt_handle->base) {
888       char dump_file_name[PATH_MAX];
889       size_t result = 0;
890 
891       snprintf(dump_file_name, sizeof(dump_file_name), "%s/input_layer%d_%dx%d_%s_frame%d.raw",
892                dir_path, i, pvt_handle->width, pvt_handle->height,
893                GetHALPixelFormatString(pvt_handle->format), dump_frame_index_);
894 
895       FILE* fp = fopen(dump_file_name, "w+");
896       if (fp) {
897         result = fwrite(reinterpret_cast<void *>(pvt_handle->base), pvt_handle->size, 1, fp);
898         fclose(fp);
899       }
900 
901       DLOGI("Frame Dump %s: is %s", dump_file_name, result ? "Successful" : "Failed");
902     }
903   }
904 }
905 
DumpOutputBuffer(const BufferInfo & buffer_info,void * base,int fence)906 void HWCDisplay::DumpOutputBuffer(const BufferInfo& buffer_info, void *base, int fence) {
907   char dir_path[PATH_MAX];
908 
909   snprintf(dir_path, sizeof(dir_path), "/data/misc/display/frame_dump_%s", GetDisplayString());
910 
911   if (mkdir(dir_path, 777) != 0 && errno != EEXIST) {
912     DLOGW("Failed to create %s directory errno = %d, desc = %s", dir_path, errno, strerror(errno));
913     return;
914   }
915 
916   // if directory exists already, need to explicitly change the permission.
917   if (errno == EEXIST && chmod(dir_path, 0777) != 0) {
918     DLOGW("Failed to change permissions on %s directory", dir_path);
919     return;
920   }
921 
922   if (base) {
923     char dump_file_name[PATH_MAX];
924     size_t result = 0;
925 
926     if (fence >= 0) {
927       int error = sync_wait(fence, 1000);
928       if (error < 0) {
929         DLOGW("sync_wait error errno = %d, desc = %s", errno,  strerror(errno));
930         return;
931       }
932     }
933 
934     snprintf(dump_file_name, sizeof(dump_file_name), "%s/output_layer_%dx%d_%s_frame%d.raw",
935              dir_path, buffer_info.buffer_config.width, buffer_info.buffer_config.height,
936              GetFormatString(buffer_info.buffer_config.format), dump_frame_index_);
937 
938     FILE* fp = fopen(dump_file_name, "w+");
939     if (fp) {
940       result = fwrite(base, buffer_info.alloc_buffer_info.size, 1, fp);
941       fclose(fp);
942     }
943 
944     DLOGI("Frame Dump of %s is %s", dump_file_name, result ? "Successful" : "Failed");
945   }
946 }
947 
GetHALPixelFormatString(int format)948 const char *HWCDisplay::GetHALPixelFormatString(int format) {
949   switch (format) {
950   case HAL_PIXEL_FORMAT_RGBA_8888:
951     return "RGBA_8888";
952   case HAL_PIXEL_FORMAT_RGBX_8888:
953     return "RGBX_8888";
954   case HAL_PIXEL_FORMAT_RGB_888:
955     return "RGB_888";
956   case HAL_PIXEL_FORMAT_RGB_565:
957     return "RGB_565";
958   case HAL_PIXEL_FORMAT_BGR_565:
959     return "BGR_565";
960   case HAL_PIXEL_FORMAT_BGRA_8888:
961     return "BGRA_8888";
962   case HAL_PIXEL_FORMAT_RGBA_5551:
963     return "RGBA_5551";
964   case HAL_PIXEL_FORMAT_RGBA_4444:
965     return "RGBA_4444";
966   case HAL_PIXEL_FORMAT_YV12:
967     return "YV12";
968   case HAL_PIXEL_FORMAT_YCbCr_422_SP:
969     return "YCbCr_422_SP_NV16";
970   case HAL_PIXEL_FORMAT_YCrCb_420_SP:
971     return "YCrCb_420_SP_NV21";
972   case HAL_PIXEL_FORMAT_YCbCr_422_I:
973     return "YCbCr_422_I_YUY2";
974   case HAL_PIXEL_FORMAT_YCrCb_422_I:
975     return "YCrCb_422_I_YVYU";
976   case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
977     return "NV12_ENCODEABLE";
978   case HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED:
979     return "YCbCr_420_SP_TILED_TILE_4x2";
980   case HAL_PIXEL_FORMAT_YCbCr_420_SP:
981     return "YCbCr_420_SP";
982   case HAL_PIXEL_FORMAT_YCrCb_420_SP_ADRENO:
983     return "YCrCb_420_SP_ADRENO";
984   case HAL_PIXEL_FORMAT_YCrCb_422_SP:
985     return "YCrCb_422_SP";
986   case HAL_PIXEL_FORMAT_R_8:
987     return "R_8";
988   case HAL_PIXEL_FORMAT_RG_88:
989     return "RG_88";
990   case HAL_PIXEL_FORMAT_INTERLACE:
991     return "INTERLACE";
992   case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS:
993     return "YCbCr_420_SP_VENUS";
994   case HAL_PIXEL_FORMAT_YCrCb_420_SP_VENUS:
995     return "YCrCb_420_SP_VENUS";
996   case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC:
997     return "YCbCr_420_SP_VENUS_UBWC";
998   case HAL_PIXEL_FORMAT_RGBA_1010102:
999     return "RGBA_1010102";
1000   case HAL_PIXEL_FORMAT_ARGB_2101010:
1001     return "ARGB_2101010";
1002   case HAL_PIXEL_FORMAT_RGBX_1010102:
1003     return "RGBX_1010102";
1004   case HAL_PIXEL_FORMAT_XRGB_2101010:
1005     return "XRGB_2101010";
1006   case HAL_PIXEL_FORMAT_BGRA_1010102:
1007     return "BGRA_1010102";
1008   case HAL_PIXEL_FORMAT_ABGR_2101010:
1009     return "ABGR_2101010";
1010   case HAL_PIXEL_FORMAT_BGRX_1010102:
1011     return "BGRX_1010102";
1012   case HAL_PIXEL_FORMAT_XBGR_2101010:
1013     return "XBGR_2101010";
1014   case HAL_PIXEL_FORMAT_YCbCr_420_P010:
1015     return "YCbCr_420_P010";
1016   case HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC:
1017     return "YCbCr_420_TP10_UBWC";
1018   default:
1019     return "Unknown_format";
1020   }
1021 }
1022 
GetDisplayString()1023 const char *HWCDisplay::GetDisplayString() {
1024   switch (type_) {
1025   case kPrimary:
1026     return "primary";
1027   case kHDMI:
1028     return "hdmi";
1029   case kVirtual:
1030     return "virtual";
1031   default:
1032     return "invalid";
1033   }
1034 }
1035 
SetFrameBufferResolution(uint32_t x_pixels,uint32_t y_pixels)1036 int HWCDisplay::SetFrameBufferResolution(uint32_t x_pixels, uint32_t y_pixels) {
1037   DisplayConfigVariableInfo fb_config;
1038   DisplayError error = display_intf_->GetFrameBufferConfig(&fb_config);
1039   if (error != kErrorNone) {
1040     DLOGV("Get frame buffer config failed. Error = %d", error);
1041     return -EINVAL;
1042   }
1043 
1044   fb_config.x_pixels = x_pixels;
1045   fb_config.y_pixels = y_pixels;
1046 
1047   error = display_intf_->SetFrameBufferConfig(fb_config);
1048   if (error != kErrorNone) {
1049     DLOGV("Set frame buffer config failed. Error = %d", error);
1050     return -EINVAL;
1051   }
1052 
1053   DLOGI("New framebuffer resolution (%dx%d)", x_pixels, y_pixels);
1054 
1055   return 0;
1056 }
1057 
GetFrameBufferResolution(uint32_t * x_pixels,uint32_t * y_pixels)1058 void HWCDisplay::GetFrameBufferResolution(uint32_t *x_pixels, uint32_t *y_pixels) {
1059   DisplayConfigVariableInfo fb_config;
1060   display_intf_->GetFrameBufferConfig(&fb_config);
1061 
1062   *x_pixels = fb_config.x_pixels;
1063   *y_pixels = fb_config.y_pixels;
1064 }
1065 
GetMixerResolution(uint32_t * x_pixels,uint32_t * y_pixels)1066 DisplayError HWCDisplay::GetMixerResolution(uint32_t *x_pixels, uint32_t *y_pixels) {
1067   return display_intf_->GetMixerResolution(x_pixels, y_pixels);
1068 }
1069 
1070 
GetPanelResolution(uint32_t * x_pixels,uint32_t * y_pixels)1071 void HWCDisplay::GetPanelResolution(uint32_t *x_pixels, uint32_t *y_pixels) {
1072   DisplayConfigVariableInfo display_config;
1073   uint32_t active_index = 0;
1074 
1075   display_intf_->GetActiveConfig(&active_index);
1076   display_intf_->GetConfig(active_index, &display_config);
1077 
1078   *x_pixels = display_config.x_pixels;
1079   *y_pixels = display_config.y_pixels;
1080 }
1081 
SetDisplayStatus(uint32_t display_status)1082 int HWCDisplay::SetDisplayStatus(uint32_t display_status) {
1083   int status = 0;
1084   const hwc_procs_t *hwc_procs = *hwc_procs_;
1085 
1086   switch (display_status) {
1087   case kDisplayStatusResume:
1088     display_paused_ = false;
1089   case kDisplayStatusOnline:
1090     status = SetPowerMode(HWC_POWER_MODE_NORMAL);
1091     break;
1092   case kDisplayStatusPause:
1093     display_paused_ = true;
1094   case kDisplayStatusOffline:
1095     status = SetPowerMode(HWC_POWER_MODE_OFF);
1096     break;
1097   default:
1098     DLOGW("Invalid display status %d", display_status);
1099     return -EINVAL;
1100   }
1101 
1102   if (display_status == kDisplayStatusResume ||
1103       display_status == kDisplayStatusPause) {
1104     hwc_procs->invalidate(hwc_procs);
1105   }
1106 
1107   return status;
1108 }
1109 
SetCursorPosition(int x,int y)1110 int HWCDisplay::SetCursorPosition(int x, int y) {
1111   DisplayError error = kErrorNone;
1112 
1113   if (shutdown_pending_) {
1114     return 0;
1115   }
1116 
1117   error = display_intf_->SetCursorPosition(x, y);
1118   if (error != kErrorNone) {
1119     if (error == kErrorShutDown) {
1120       shutdown_pending_ = true;
1121       return 0;
1122     }
1123     DLOGE("Failed for x = %d y = %d, Error = %d", x, y, error);
1124     return -1;
1125   }
1126 
1127   return 0;
1128 }
1129 
OnMinHdcpEncryptionLevelChange(uint32_t min_enc_level)1130 int HWCDisplay::OnMinHdcpEncryptionLevelChange(uint32_t min_enc_level) {
1131   DisplayError error = display_intf_->OnMinHdcpEncryptionLevelChange(min_enc_level);
1132   if (error != kErrorNone) {
1133     DLOGE("Failed. Error = %d", error);
1134     return -1;
1135   }
1136 
1137   return 0;
1138 }
1139 
MarkLayersForGPUBypass(hwc_display_contents_1_t * content_list)1140 void HWCDisplay::MarkLayersForGPUBypass(hwc_display_contents_1_t *content_list) {
1141   for (size_t i = 0 ; i < (content_list->numHwLayers - 1); i++) {
1142     hwc_layer_1_t *layer = &content_list->hwLayers[i];
1143     layer->compositionType = HWC_OVERLAY;
1144   }
1145 }
1146 
ApplyScanAdjustment(hwc_rect_t * display_frame)1147 void HWCDisplay::ApplyScanAdjustment(hwc_rect_t *display_frame) {
1148 }
1149 
SetCSC(ColorSpace_t source,LayerCSC * target)1150 DisplayError HWCDisplay::SetCSC(ColorSpace_t source, LayerCSC *target) {
1151   switch (source) {
1152   case ITU_R_601:       *target = kCSCLimitedRange601;   break;
1153   case ITU_R_601_FR:    *target = kCSCFullRange601;      break;
1154   case ITU_R_709:       *target = kCSCLimitedRange709;   break;
1155   default:
1156     DLOGE("Unsupported CSC: %d", source);
1157     return kErrorNotSupported;
1158   }
1159 
1160   return kErrorNone;
1161 }
1162 
SetIGC(IGC_t source,LayerIGC * target)1163 DisplayError HWCDisplay::SetIGC(IGC_t source, LayerIGC *target) {
1164   switch (source) {
1165   case IGC_NotSpecified:    *target = kIGCNotSpecified; break;
1166   case IGC_sRGB:            *target = kIGCsRGB;   break;
1167   default:
1168     DLOGE("Unsupported IGC: %d", source);
1169     return kErrorNotSupported;
1170   }
1171 
1172   return kErrorNone;
1173 }
1174 
SetMetaData(const private_handle_t * pvt_handle,Layer * layer)1175 DisplayError HWCDisplay::SetMetaData(const private_handle_t *pvt_handle, Layer *layer) {
1176   const MetaData_t *meta_data = reinterpret_cast<MetaData_t *>(pvt_handle->base_metadata);
1177   LayerBuffer *layer_buffer = layer->input_buffer;
1178 
1179   if (!meta_data) {
1180     return kErrorNone;
1181   }
1182 
1183   if (meta_data->operation & UPDATE_COLOR_SPACE) {
1184     if (SetCSC(meta_data->colorSpace, &layer_buffer->csc) != kErrorNone) {
1185       return kErrorNotSupported;
1186     }
1187   }
1188 
1189   if (meta_data->operation & SET_IGC) {
1190     if (SetIGC(meta_data->igc, &layer_buffer->igc) != kErrorNone) {
1191       return kErrorNotSupported;
1192     }
1193   }
1194 
1195   if (meta_data->operation & UPDATE_REFRESH_RATE) {
1196     layer->frame_rate = RoundToStandardFPS(meta_data->refreshrate);
1197   }
1198 
1199   if ((meta_data->operation & PP_PARAM_INTERLACED) && meta_data->interlaced) {
1200     layer_buffer->flags.interlace = true;
1201   }
1202 
1203   if (meta_data->operation & LINEAR_FORMAT) {
1204     layer_buffer->format = GetSDMFormat(INT32(meta_data->linearFormat), 0);
1205   }
1206 
1207   if (meta_data->operation & UPDATE_BUFFER_GEOMETRY) {
1208     int actual_width = pvt_handle->width;
1209     int actual_height = pvt_handle->height;
1210     AdrenoMemInfo::getInstance().getAlignedWidthAndHeight(pvt_handle, actual_width, actual_height);
1211     layer_buffer->width = UINT32(actual_width);
1212     layer_buffer->height = UINT32(actual_height);
1213   }
1214 
1215   if (meta_data->operation & SET_SINGLE_BUFFER_MODE) {
1216     layer->flags.single_buffer = meta_data->isSingleBufferMode;
1217     // Graphics can set this operation on all types of layers including FB and set the actual value
1218     // to 0. To protect against SET operations of 0 value, we need to do a logical OR.
1219     layer_stack_.flags.single_buffered_layer_present |= meta_data->isSingleBufferMode;
1220   }
1221 
1222   if (meta_data->operation & S3D_FORMAT) {
1223     std::map<int, LayerBufferS3DFormat>::iterator it =
1224         s3d_format_hwc_to_sdm_.find(INT32(meta_data->s3dFormat));
1225     if (it != s3d_format_hwc_to_sdm_.end()) {
1226       layer->input_buffer->s3d_format = it->second;
1227     } else {
1228       DLOGW("Invalid S3D format %d", meta_data->s3dFormat);
1229     }
1230   }
1231 
1232   return kErrorNone;
1233 }
1234 
SetPanelBrightness(int level)1235 int HWCDisplay::SetPanelBrightness(int level) {
1236   int ret = 0;
1237   if (display_intf_)
1238     ret = display_intf_->SetPanelBrightness(level);
1239   else
1240     ret = -EINVAL;
1241 
1242   return ret;
1243 }
1244 
GetPanelBrightness(int * level)1245 int HWCDisplay::GetPanelBrightness(int *level) {
1246   return display_intf_->GetPanelBrightness(level);
1247 }
1248 
ToggleScreenUpdates(bool enable)1249 int HWCDisplay::ToggleScreenUpdates(bool enable) {
1250   const hwc_procs_t *hwc_procs = *hwc_procs_;
1251   display_paused_ = enable ? false : true;
1252   hwc_procs->invalidate(hwc_procs);
1253   return 0;
1254 }
1255 
ColorSVCRequestRoute(const PPDisplayAPIPayload & in_payload,PPDisplayAPIPayload * out_payload,PPPendingParams * pending_action)1256 int HWCDisplay::ColorSVCRequestRoute(const PPDisplayAPIPayload &in_payload,
1257                                      PPDisplayAPIPayload *out_payload,
1258                                      PPPendingParams *pending_action) {
1259   int ret = 0;
1260 
1261   if (display_intf_)
1262     ret = display_intf_->ColorSVCRequestRoute(in_payload, out_payload, pending_action);
1263   else
1264     ret = -EINVAL;
1265 
1266   return ret;
1267 }
1268 
GetVisibleDisplayRect(hwc_rect_t * visible_rect)1269 int HWCDisplay::GetVisibleDisplayRect(hwc_rect_t* visible_rect) {
1270   if (!IsValid(display_rect_)) {
1271     return -EINVAL;
1272   }
1273 
1274   visible_rect->left = INT(display_rect_.left);
1275   visible_rect->top = INT(display_rect_.top);
1276   visible_rect->right = INT(display_rect_.right);
1277   visible_rect->bottom = INT(display_rect_.bottom);
1278   DLOGI("Dpy = %d Visible Display Rect(%d %d %d %d)", visible_rect->left, visible_rect->top,
1279         visible_rect->right, visible_rect->bottom);
1280 
1281   return 0;
1282 }
1283 
SetSecureDisplay(bool secure_display_active)1284 void HWCDisplay::SetSecureDisplay(bool secure_display_active) {
1285   secure_display_active_ = secure_display_active;
1286   return;
1287 }
1288 
SetActiveDisplayConfig(int config)1289 int HWCDisplay::SetActiveDisplayConfig(int config) {
1290   return display_intf_->SetActiveConfig(UINT32(config)) == kErrorNone ? 0 : -1;
1291 }
1292 
GetActiveDisplayConfig(uint32_t * config)1293 int HWCDisplay::GetActiveDisplayConfig(uint32_t *config) {
1294   return display_intf_->GetActiveConfig(config) == kErrorNone ? 0 : -1;
1295 }
1296 
GetDisplayConfigCount(uint32_t * count)1297 int HWCDisplay::GetDisplayConfigCount(uint32_t *count) {
1298   return display_intf_->GetNumVariableInfoConfigs(count) == kErrorNone ? 0 : -1;
1299 }
1300 
GetDisplayAttributesForConfig(int config,DisplayConfigVariableInfo * display_attributes)1301 int HWCDisplay::GetDisplayAttributesForConfig(int config,
1302                                             DisplayConfigVariableInfo *display_attributes) {
1303   return display_intf_->GetConfig(UINT32(config), display_attributes) == kErrorNone ? 0 : -1;
1304 }
1305 
1306 // TODO(user): HWC needs to know updating for dyn_fps, cpu hint features,
1307 // once the features are moved to SDM, the two functions below can be removed.
SingleLayerUpdating(uint32_t app_layer_count)1308 bool HWCDisplay::SingleLayerUpdating(uint32_t app_layer_count) {
1309   uint32_t updating_count = 0;
1310 
1311   for (uint i = 0; i < app_layer_count; i++) {
1312     Layer *layer = layer_stack_.layers.at(i);
1313     if (layer->flags.updating) {
1314       updating_count++;
1315     }
1316   }
1317 
1318   return (updating_count == 1);
1319 }
1320 
SingleVideoLayerUpdating(uint32_t app_layer_count)1321 bool HWCDisplay::SingleVideoLayerUpdating(uint32_t app_layer_count) {
1322   uint32_t updating_count = 0;
1323 
1324   for (uint i = 0; i < app_layer_count; i++) {
1325     Layer *layer = layer_stack_.layers[i];
1326     if (layer->flags.updating && (layer->input_buffer->flags.video == true)) {
1327       updating_count++;
1328     }
1329   }
1330 
1331   return (updating_count == 1);
1332 }
1333 
RoundToStandardFPS(float fps)1334 uint32_t HWCDisplay::RoundToStandardFPS(float fps) {
1335   static const uint32_t standard_fps[4] = {30, 24, 48, 60};
1336   uint32_t frame_rate = (uint32_t)(fps);
1337 
1338   int count = INT(sizeof(standard_fps) / sizeof(standard_fps[0]));
1339   for (int i = 0; i < count; i++) {
1340     if ((standard_fps[i] - frame_rate) < 2) {
1341       // Most likely used for video, the fps can fluctuate
1342       // Ex: b/w 29 and 30 for 30 fps clip
1343       return standard_fps[i];
1344     }
1345   }
1346 
1347   return frame_rate;
1348 }
1349 
SanitizeRefreshRate(uint32_t req_refresh_rate)1350 uint32_t HWCDisplay::SanitizeRefreshRate(uint32_t req_refresh_rate) {
1351   uint32_t refresh_rate = req_refresh_rate;
1352 
1353   if (refresh_rate < min_refresh_rate_) {
1354     // Pick the next multiple of request which is within the range
1355     refresh_rate = (((min_refresh_rate_ / refresh_rate) +
1356                      ((min_refresh_rate_ % refresh_rate) ? 1 : 0)) * refresh_rate);
1357   }
1358 
1359   if (refresh_rate > max_refresh_rate_) {
1360     refresh_rate = max_refresh_rate_;
1361   }
1362 
1363   return refresh_rate;
1364 }
1365 
GetDisplayClass()1366 DisplayClass HWCDisplay::GetDisplayClass() {
1367   return display_class_;
1368 }
1369 
PrepareDynamicRefreshRate(Layer * layer)1370 void HWCDisplay::PrepareDynamicRefreshRate(Layer *layer) {
1371   if (layer->frame_rate > metadata_refresh_rate_) {
1372     metadata_refresh_rate_ = SanitizeRefreshRate(layer->frame_rate);
1373   } else {
1374     layer->frame_rate = current_refresh_rate_;
1375   }
1376 }
1377 
IsSurfaceUpdated(const std::vector<LayerRect> & dirty_regions)1378 bool HWCDisplay::IsSurfaceUpdated(const std::vector<LayerRect> &dirty_regions) {
1379   // based on dirty_regions determine if its updating
1380   // dirty_rect count = 0 - whole layer - updating.
1381   // dirty_rect count = 1 or more valid rects - updating.
1382   // dirty_rect count = 1 with (0,0,0,0) - not updating.
1383   return (dirty_regions.empty() || IsValid(dirty_regions.at(0)));
1384 }
1385 
1386 }  // namespace sdm
1387