1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #ifndef ALLOCATOR_H
16 #define ALLOCATOR_H
17 #include <cerrno>
18 #include <cstdint>
19 #include <sys/mman.h>
20 #include <linux/dma-buf.h>
21 #include "securec.h"
22 #include "display_type.h"
23 #include "display_gralloc_private.h"
24 namespace OHOS {
25 namespace HDI {
26 namespace DISPLAY {
27 template <typename T>
AlignUp(T value,T align)28 T AlignUp(T value, T align)
29 {
30 if (align == 0) {
31 return 0;
32 }
33 return (value + align - 1) / align * align;
34 }
35
36 template <typename T>
DivRoundUp(T numerator,T denominator)37 T DivRoundUp(T numerator, T denominator)
38 {
39 if (denominator == 0) {
40 return 0;
41 }
42 return (numerator + denominator - 1) / denominator;
43 }
44
45 struct BufferInfo {
46 uint32_t width_ = 0;
47 uint32_t height_ = 0;
48 uint32_t widthStride_ = 0;
49 uint32_t heightStride_ = 0;
50 uint32_t bitsPerPixel_ = 0;
51 uint32_t bytesPerPixel_ = 0;
52 uint32_t size_ = 0;
53 uint64_t usage_ = 0;
54 PixelFormat format_ = PIXEL_FMT_BUTT;
55 };
56
57 class Allocator {
58 public:
59 virtual int32_t AllocMem(const AllocInfo &info, BufferHandle **handle);
60 virtual int32_t Allocate(const BufferInfo &bufferInfo, BufferHandle &handle);
61 virtual int32_t Init();
62 virtual int32_t FreeMem(BufferHandle *handle);
63 virtual void *Mmap(BufferHandle &handle);
64 virtual int32_t Unmap(BufferHandle &handle);
65 virtual int32_t InvalidateCache(BufferHandle &handle);
66 virtual int32_t FlushCache(BufferHandle &handle);
~Allocator()67 virtual ~Allocator() {}
68 static constexpr uint32_t BITS_PER_BYTES = 8;
69 static constexpr uint32_t HEIGHT_ALIGN = 2;
70 static constexpr uint32_t WIDTH_ALIGN = 8;
71
72 private:
73 int32_t DmaBufferSync(const BufferHandle &handle, uint64_t flag);
74 uint32_t UpdatePixelInfo(BufferInfo &bufferInfo);
75 int32_t UpdateStrideAndSize(BufferInfo &bufferInfo);
76 int32_t UpdateRGBStrideAndSize(BufferInfo &bufferInfo);
77 int32_t UpdateYuvStrideAndSize(BufferInfo &bufferInfo);
78 int32_t ConvertToBufferInfo(BufferInfo &bufferInfo, const AllocInfo &info);
79 bool IsYuv(PixelFormat format);
80 void DumpBufferHandle(BufferHandle &handle) const;
81 };
82 } // namespace DISPLAY
83 } // namespace HDI
84 } // namespace OHOS
85 #endif // ALLOCATOR_H