Debian Codegraph @

media_softlet/linux/common/os/osservice/mos_utilities_specific.cpp

raw
1 /*
2 * Copyright (c) 2019-2022, Intel Corporation
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
12 * in all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS 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 //!
23 //! \file mos_utilities_specific.cpp
24 //! \brief This module implements the MOS wrapper functions for Linux/Android
25 //!
26
27 #include <fcntl.h> // open
28 #include <stdlib.h> // atoi
29 #include <string.h> // strlen, strcat, etc.
30 #include <errno.h> // strerror(errno)
31 #include <time.h> // get_clocktime
32 #include <dlfcn.h> // dlopen, dlsym, dlclose
33 #include <unistd.h>
34 #include <signal.h>
35 #include <unistd.h> // fork
36 #include <algorithm>
37 #include <string>
38 #include <sys/types.h>
39 #include <sys/stat.h> // fstat
40 #include <sys/ipc.h> // System V IPC
41 #include <sys/types.h>
42 #include <sys/sem.h>
43 #include <sys/mman.h>
44 #include "mos_user_setting.h"
45 #include "mos_utilities_specific.h"
46 #include "mos_utilities.h"
47 #include "mos_util_debug.h"
48 #include "inttypes.h"
49
50 int32_t g_mosMemAllocCounter = 0;
51 int32_t g_mosMemAllocFakeCounter = 0;
52 int32_t g_mosMemAllocCounterGfx = 0;
53 uint8_t g_mosUltFlag = 0;
54 int32_t g_mosMemAllocIndex = 0;
55
56 int32_t *MosUtilities::m_mosMemAllocCounter = &g_mosMemAllocCounter;
57 int32_t *MosUtilities::m_mosMemAllocFakeCounter = &g_mosMemAllocFakeCounter;
58 int32_t *MosUtilities::m_mosMemAllocCounterGfx = &g_mosMemAllocCounterGfx;
59 uint8_t *MosUtilities::m_mosUltFlag = &g_mosUltFlag;
60 int32_t *MosUtilities::m_mosMemAllocIndex = &g_mosMemAllocIndex;
61
62 const char *MosUtilitiesSpecificNext::m_szUserFeatureFile = USER_FEATURE_FILE;
63 std::string MosUtilitiesSpecificNext::m_szUserFeatureFileNext = USER_FEATURE_FILE_NEXT;
64 std::string MosUtilitiesSpecificNext::m_szUserFeatureFileReport = USER_FEATURE_FILE_REPORT;
65 MOS_PUF_KEYLIST MosUtilitiesSpecificNext::m_ufKeyList = nullptr;
66
67 #if (_DEBUG || _RELEASE_INTERNAL)
68 int32_t g_mosMemoryFailSimulateAllocCounter = 0;
69 int32_t *MosUtilities::m_mosAllocMemoryFailSimulateAllocCounter = &g_mosMemoryFailSimulateAllocCounter;
70 #endif
71
72 double MosUtilities::MosGetTime()
73 {
74 struct timespec ts = {};
75 clock_gettime(CLOCK_REALTIME, &ts);
76 return double(ts.tv_sec) * 1000000.0 + double(ts.tv_nsec) / 1000.0;
77 }
78
79 //!
80 //! \brief Linux specific user feature define, used in MosUtilities::MosUserFeatureParsePath
81 //! They can be unified with the win definitions, since they are identical.
82 //!
83 #define MOS_UF_SEPARATOR "\\"
84 #define MOS_UFKEY_EXT "UFKEY_EXTERNAL"
85 #define MOS_UFKEY_INT "UFKEY_INTERNAL"
86
87 //!
88 //! \brief trace setting definition
89 //!
90 #define TRACE_SETTING_PATH "/dev/shm/GFX_MEDIA_TRACE"
91 #define TRACE_SETTING_SIZE sizeof(MtControlData)
92
93 //!
94 //! \brief Linux specific trace entry path and file description.
95 //!
96 const char *const MosUtilitiesSpecificNext::m_mosTracePath = "/sys/kernel/debug/tracing/trace_marker_raw";
97 int32_t MosUtilitiesSpecificNext::m_mosTraceFd = -1;
98 uint64_t MosUtilitiesSpecificNext::m_filterEnv = 0;
99 uint32_t MosUtilitiesSpecificNext::m_levelEnv = 0;
100
101 MosMutex MosUtilitiesSpecificNext::m_userSettingMutex;
102
103 //!
104 //! \brief trace event size definition
105 //!
106 #define TRACE_EVENT_MAX_SIZE (1020)
107 #define TRACE_EVENT_HEADER_SIZE (sizeof(uint32_t)*3)
108 #define TRACE_EVENT_MAX_DATA_SIZE (TRACE_EVENT_MAX_SIZE - TRACE_EVENT_HEADER_SIZE - sizeof(uint32_t)) // in 4bytes aligned size
109
110 //!
111 //! \brief for int64_t/uint64_t format print warning
112 //!
113 #if __WORDSIZE == 64
114 #define __MOS64_PREFIX "l"
115 #else
116 #define __MOS64_PREFIX "ll"
117 #endif
118
119 #define MOSd64 __MOS64_PREFIX "d"
120 #define MOSu64 __MOS64_PREFIX "u"
121
122
123 //!
124 //! \brief mutex for mos utilities multi-threading protection
125 //!
126 MosMutex MosUtilities::m_mutexLock;
127 uint32_t MosUtilities::m_mosUtilInitCount = 0; // number count of mos utilities init
128
129 MediaUserSettingsMgr *MosUtilities::m_mediaUserFeatureSpecific = nullptr;
130
131 MOS_STATUS MosUtilities::MosSecureStrcat(char *strDestination, size_t numberOfElements, const char * const strSource)
132 {
133 if ( (strDestination == nullptr) || (strSource == nullptr) )
134 {
135 return MOS_STATUS_INVALID_PARAMETER;
136 }
137
138 if(strnlen(strDestination, numberOfElements) == numberOfElements) // Not null terminated
139 {
140 return MOS_STATUS_INVALID_PARAMETER;
141 }
142
143 if((strlen(strDestination) + strlen(strSource)) >= numberOfElements) // checks space for null termination.
144 {
145 return MOS_STATUS_INVALID_PARAMETER;
146 }
147
148 strcat(strDestination, strSource);
149 return MOS_STATUS_SUCCESS;
150 }
151
152 char *MosUtilities::MosSecureStrtok(
153 char *strToken,
154 const char *strDelimit,
155 char **contex)
156 {
157 return strtok_r(strToken, strDelimit, contex);
158 }
159
160 MOS_STATUS MosUtilities::MosSecureStrcpy(char *strDestination, size_t numberOfElements, const char * const strSource)
161 {
162 if ( (strDestination == nullptr) || (strSource == nullptr) )
163 {
164 return MOS_STATUS_INVALID_PARAMETER;
165 }
166
167 if ( numberOfElements <= strlen(strSource) ) // checks if there is space for null termination after copy.
168 {
169 return MOS_STATUS_INVALID_PARAMETER;
170 }
171
172 strcpy(strDestination, strSource);
173
174 return MOS_STATUS_SUCCESS;
175 }
176
177 MOS_STATUS MosUtilities::MosSecureStrncpy(char *strDestination, size_t destSz, const char* const strSource, size_t maxCount)
178 {
179 if ( (strDestination == nullptr) || (strSource == nullptr) )
180 {
181 return MOS_STATUS_INVALID_PARAMETER;
182 }
183
184 if ( destSz <= maxCount ) // checks if there is space for null termination after copy.
185 {
186 return MOS_STATUS_INVALID_PARAMETER;
187 }
188
189 strncpy(strDestination, strSource, maxCount);
190
191 return MOS_STATUS_SUCCESS;
192 }
193
194 MOS_STATUS MosUtilities::MosSecureMemcpy(void *pDestination, size_t dstLength, PCVOID pSource, size_t srcLength)
195 {
196 if ( (pDestination == nullptr) || (pSource == nullptr) )
197 {
198 return MOS_STATUS_INVALID_PARAMETER;
199 }
200
201 if ( dstLength < srcLength )
202 {
203 return MOS_STATUS_INVALID_PARAMETER;
204 }
205 if(pDestination != pSource)
206 {
207 memcpy(pDestination, pSource, srcLength);
208 }
209
210 return MOS_STATUS_SUCCESS;
211 }
212
213 MOS_STATUS MosUtilities::MosSecureFileOpen(
214 FILE **ppFile,
215 const char *filename,
216 const char *mode)
217 {
218 PFILE fp;
219
220 if ((ppFile == nullptr) || (filename == nullptr) || (mode == nullptr))
221 {
222 return MOS_STATUS_INVALID_PARAMETER;
223 }
224
225 fp = fopen(filename, mode);
226
227 if (fp == nullptr)
228 {
229 *ppFile = nullptr;
230 return MOS_STATUS_FILE_OPEN_FAILED;
231 }
232 else
233 {
234 *ppFile = fp;
235 return MOS_STATUS_SUCCESS;
236 }
237 }
238
239 int32_t MosUtilities::MosSecureStringPrint(char *buffer, size_t bufSize, size_t length, const char * const format, ...)
240 {
241 int32_t iRet = -1;
242 va_list var_args;
243
244 if((buffer == nullptr) || (format == nullptr) || (bufSize < length))
245 {
246 return iRet;
247 }
248
249 va_start(var_args, format);
250
251 iRet = vsnprintf(buffer, length, format, var_args);
252
253 va_end(var_args);
254
255 return iRet;
256 }
257
258 MOS_STATUS MosUtilities::MosSecureVStringPrint(char *buffer, size_t bufSize, size_t length, const char * const format, va_list var_args)
259 {
260 if((buffer == nullptr) || (format == nullptr) || (bufSize < length))
261 {
262 return MOS_STATUS_INVALID_PARAMETER;
263 }
264
265 vsnprintf(buffer, length, format, var_args);
266
267 return MOS_STATUS_SUCCESS;
268 }
269
270 MOS_STATUS MosUtilities::MosGetFileSize(
271 HANDLE hFile,
272 uint32_t *lpFileSizeLow,
273 uint32_t *lpFileSizeHigh)
274 {
275 struct stat Buf;
276 MOS_UNUSED(lpFileSizeHigh);
277
278 if((hFile == nullptr) || (lpFileSizeLow == nullptr))
279 {
280 return MOS_STATUS_INVALID_PARAMETER;
281 }
282
283 if ( (fstat((intptr_t)hFile, &Buf)) < 0 )
284 {
285 *lpFileSizeLow = 0;
286 return MOS_STATUS_INVALID_FILE_SIZE;
287 }
288 *lpFileSizeLow = (uint32_t)Buf.st_size;
289
290 //to-do, lpFileSizeHigh store high 32-bit of File size
291 return MOS_STATUS_SUCCESS;
292 }
293
294 MOS_STATUS MosUtilities::MosCreateDirectory(
295 char * const lpPathName)
296 {
297 uint32_t mode;
298
299 MOS_OS_CHK_NULL_RETURN(lpPathName);
300
301 // Set read/write access right for usr/group.
302 mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP;
303 if (mkdir(lpPathName, mode) < 0 &&
304 errno != EEXIST) // Directory already exists, don't return failure in this case.
305 {
306 MOS_OS_ASSERTMESSAGE("Failed to create the directory '%s'. Error = %s", lpPathName, strerror(errno));
307 return MOS_STATUS_DIR_CREATE_FAILED;
308 }
309
310 return MOS_STATUS_SUCCESS;
311 }
312
313 MOS_STATUS MosUtilities::MosCreateFile(
314 PHANDLE pHandle,
315 char * const lpFileName,
316 uint32_t iOpenFlag)
317 {
318 int32_t iFileDescriptor;
319 uint32_t mode;
320
321 if((lpFileName == nullptr) || (pHandle == nullptr))
322 {
323 return MOS_STATUS_INVALID_PARAMETER;
324 }
325 //set read/write access right for usr/group, mMode only takes effect when
326 //O_CREAT is set
327 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
328 if ( (iFileDescriptor = open(lpFileName, iOpenFlag, mode)) < 0 )
329 {
330 *pHandle = (HANDLE)((intptr_t) iFileDescriptor);
331 return MOS_STATUS_INVALID_HANDLE;
332 }
333
334 *pHandle = (HANDLE)((intptr_t) iFileDescriptor);
335 return MOS_STATUS_SUCCESS;
336 }
337
338 MOS_STATUS MosUtilities::MosReadFile(
339 HANDLE hFile,
340 void *lpBuffer,
341 uint32_t bytesToRead,
342 uint32_t *pBytesRead,
343 void *lpOverlapped)
344 {
345 size_t nNumBytesToRead;
346 ssize_t nNumBytesRead;
347 MOS_UNUSED(lpOverlapped);
348
349 if((hFile == nullptr) || (lpBuffer == nullptr) || (pBytesRead == nullptr))
350 {
351 return MOS_STATUS_INVALID_PARAMETER;
352 }
353
354 nNumBytesToRead = (size_t)bytesToRead;
355 nNumBytesRead = 0;
356
357 //To-do: process lpOverlapped
358
359 if ((nNumBytesRead = read((intptr_t)hFile, lpBuffer, nNumBytesToRead)) < 0)
360 {
361 *pBytesRead = 0;
362 return MOS_STATUS_FILE_READ_FAILED;
363 }
364
365 *pBytesRead = (uint32_t)nNumBytesRead;
366 return MOS_STATUS_SUCCESS;
367 }
368
369 MOS_STATUS MosUtilities::MosWriteFile(
370 HANDLE hFile,
371 void *lpBuffer,
372 uint32_t bytesToWrite,
373 uint32_t *pbytesWritten,
374 void *lpOverlapped)
375 {
376 size_t nNumBytesToWrite;
377 ssize_t nNumBytesWritten;
378 MOS_UNUSED(lpOverlapped);
379
380 if((hFile == nullptr) || (lpBuffer == nullptr) || (pbytesWritten == nullptr))
381 {
382 return MOS_STATUS_INVALID_PARAMETER;
383 }
384
385 nNumBytesToWrite = (size_t)bytesToWrite;
386 nNumBytesWritten = 0;
387
388 //To-do, process lpOverlapped
389
390 if ((nNumBytesWritten = write((intptr_t)hFile, lpBuffer, nNumBytesToWrite)) < 0)
391 {
392 *pbytesWritten = 0;
393 return MOS_STATUS_FILE_WRITE_FAILED;
394 }
395
396 *pbytesWritten = (uint32_t)nNumBytesWritten;
397 return MOS_STATUS_SUCCESS;
398 }
399
400 MOS_STATUS MosUtilities::MosSetFilePointer(
401 HANDLE hFile,
402 int32_t lDistanceToMove,
403 int32_t *lpDistanceToMoveHigh,
404 int32_t dwMoveMethod)
405 {
406 int32_t iOffSet;
407 int32_t iCurPos;
408
409 if(hFile == nullptr)
410 {
411 return MOS_STATUS_INVALID_PARAMETER;
412 }
413
414 if (lpDistanceToMoveHigh == nullptr)
415 {
416 iOffSet = lDistanceToMove;
417 }
418 else
419 {
420 //to-do, let lpDistanceToMoveHigh and lDistanceToMove form a 64-bit iOffSet
421 iOffSet = (int32_t)lDistanceToMove;
422 }
423
424 if ((iCurPos = lseek((intptr_t)hFile, iOffSet, dwMoveMethod)) < 0)
425 {
426 return MOS_STATUS_SET_FILE_POINTER_FAILED;
427 }
428
429 return MOS_STATUS_SUCCESS;
430 }
431
432 int32_t MosUtilities::MosCloseHandle(HANDLE hObject)
433 {
434 int32_t iRet = false;
435
436 if(hObject != nullptr)
437 {
438 close((intptr_t)hObject);
439 iRet = true;
440 }
441
442 return iRet;
443 }
444
445 //library
446 MOS_STATUS MosUtilities::MosLoadLibrary(const char * const lpLibFileName, PHMODULE phModule)
447 {
448 if (lpLibFileName == nullptr)
449 {
450 return MOS_STATUS_INVALID_PARAMETER;
451 }
452
453 *phModule = dlopen((const char *)lpLibFileName, RTLD_LAZY);
454
455 return ((*phModule != nullptr) ? MOS_STATUS_SUCCESS : MOS_STATUS_LOAD_LIBRARY_FAILED);
456 }
457
458 int32_t MosUtilities::MosFreeLibrary(HMODULE hLibModule)
459 {
460 uint32_t iRet = 10; // Initialize to some non-zero value
461
462 if(hLibModule != nullptr)
463 {
464 iRet = dlclose(hLibModule);
465 }
466 return (iRet == 0) ? true : false;
467 }
468
469 void *MosUtilities::MosGetProcAddress(HMODULE hModule, const char *lpProcName)
470 {
471 void *pSym = nullptr;
472
473 if (hModule == nullptr ||
474 lpProcName == nullptr)
475 {
476 MOS_OS_ASSERTMESSAGE("Invalid parameter.");
477 }
478 else
479 {
480 pSym = dlsym(hModule, lpProcName);
481 }
482
483 return pSym;
484 }
485
486 int32_t MosUtilities::MosGetPid()
487 {
488 return(getpid());
489 }
490
491 //Performace
492 int32_t MosUtilities::MosQueryPerformanceFrequency(uint64_t *pFrequency)
493 {
494 struct timespec Res;
495 int32_t iRet;
496
497 if(pFrequency == nullptr)
498 {
499 return false;
500 }
501
502 if ( (iRet = clock_getres(CLOCK_MONOTONIC, &Res)) != 0 )
503 {
504 return false;
505 }
506
507 // resolution (precision) can't be in seconds for current machine and OS
508 if (Res.tv_sec != 0)
509 {
510 return false;
511 }
512 *pFrequency = (uint64_t)((1000 * 1000 * 1000) / Res.tv_nsec);
513
514 return true;
515 }
516
517 int32_t MosUtilities::MosQueryPerformanceCounter(uint64_t *pPerformanceCount)
518 {
519 struct timespec Res;
520 struct timespec t;
521 int32_t iRet;
522
523 if(pPerformanceCount == nullptr)
524 {
525 return false;
526 }
527 if ( (iRet = clock_getres (CLOCK_MONOTONIC, &Res)) != 0 )
528 {
529 return false;
530 }
531 if (Res.tv_sec != 0)
532 { // resolution (precision) can't be in seconds for current machine and OS
533 return false;
534 }
535 if( (iRet = clock_gettime(CLOCK_MONOTONIC, &t)) != 0)
536 {
537 return false;
538 }
539 *pPerformanceCount = (uint64_t)((1000 * 1000 * 1000 * t.tv_sec + t.tv_nsec) / Res.tv_nsec);
540
541 return true;
542 }
543
544 void MosUtilities::MosSleep(uint32_t mSec)
545 {
546 usleep(1000 * mSec);
547 }
548
549 //User Feature
550 MOS_UF_KEY* MosUtilitiesSpecificNext::UserFeatureFindKey(MOS_PUF_KEYLIST pKeyList, char * const pcKeyName)
551 {
552 int32_t iResult;
553 MOS_PUF_KEYLIST pTempNode;
554
555 iResult = -1;
556
557 for(pTempNode = pKeyList; pTempNode; pTempNode = pTempNode->pNext)
558 {
559 iResult = strcmp(pTempNode->pElem->pcKeyName, pcKeyName);
560 if ( iResult == 0 )
561 {
562 return pTempNode->pElem;
563 }
564 }
565 return nullptr; //not found
566 }
567
568 int32_t MosUtilitiesSpecificNext::UserFeatureFindValue(MOS_UF_KEY UFKey, char * const pcValueName)
569 {
570 int32_t iResult;
571 int32_t i;
572
573 iResult = -1;
574
575 for ( i = 0; i < UFKey.valueNum; i++ )
576 {
577 iResult = strcmp(UFKey.pValueArray[i].pcValueName, pcValueName);
578 if ( iResult == 0 )
579 {
580 return i;
581 }
582 }
583 return NOT_FOUND;
584 }
585
586 MOS_STATUS MosUtilitiesSpecificNext::UserFeatureAdd(MOS_PUF_KEYLIST *pKeyList, MOS_UF_KEY *NewKey)
587 {
588 MOS_UF_KEYNODE *pNewNode;
589 MOS_UF_KEYNODE *pTempNode;
590 MOS_UF_KEYNODE *pStartNode;
591
592 pNewNode = nullptr;
593 pTempNode = nullptr;
594 pStartNode = *pKeyList;
595
596 if ( NewKey == nullptr )
597 {
598 return MOS_STATUS_INVALID_PARAMETER;
599 }
600
601 pNewNode = (MOS_UF_KEYNODE *)MOS_AllocAndZeroMemory(sizeof(MOS_UF_KEYNODE));
602 if (pNewNode == nullptr)
603 {
604 return MOS_STATUS_NO_SPACE;
605 }
606 pNewNode->pElem = NewKey;
607
608 if (*pKeyList == nullptr ) // the key list is empty
609 {
610 pNewNode->pNext = nullptr;
611 (*pKeyList) = pNewNode;
612 }
613 else // the key list is not empty, append to the front
614 {
615 pTempNode = pStartNode->pNext;
616 pStartNode->pNext = pNewNode;
617 pNewNode->pNext = pTempNode;
618 }
619 return MOS_STATUS_SUCCESS;
620 }
621
622 MOS_STATUS MosUtilitiesSpecificNext::UserFeatureSet(MOS_PUF_KEYLIST *pKeyList, MOS_UF_KEY NewKey)
623 {
624 int32_t iPos;
625 MOS_UF_VALUE *pValueArray;
626 MOS_UF_KEY *Key;
627 void *ulValueBuf;
628
629 iPos = -1;
630 pValueArray = nullptr;
631
632 if ( (Key = UserFeatureFindKey(*pKeyList, NewKey.pcKeyName)) == nullptr )
633 {
634 // can't find key in File
635 return MOS_STATUS_UNKNOWN;
636 }
637
638 // Prepare the ValueBuff of the NewKey
639 if ((ulValueBuf = MOS_AllocAndZeroMemory(NewKey.pValueArray[0].ulValueLen)) == nullptr)
640 {
641 return MOS_STATUS_NO_SPACE;
642 }
643 MosUtilities::MosAtomicIncrement(MosUtilities::m_mosMemAllocFakeCounter); //ulValueBuf does not count it, because it is freed after the MEMNJA final report.
644 MOS_OS_NORMALMESSAGE("ulValueBuf %p for key %s", ulValueBuf, NewKey.pValueArray[0].pcValueName);
645
646 m_userSettingMutex.Lock();
647 if ((iPos = UserFeatureFindValue(*Key, NewKey.pValueArray[0].pcValueName)) == NOT_FOUND)
648 {
649 //not found, add a new value to key struct.
650 //reallocate memory for appending this value.
651 iPos = MosUtilities::MosAtomicIncrement(&Key->valueNum);
652 iPos = iPos - 1;
653 if (iPos >= UF_CAPABILITY)
654 {
655 MOS_OS_ASSERTMESSAGE("user setting requires iPos (%d) < UF_CAPABILITY(64)", iPos);
656 Key->valueNum = UF_CAPABILITY;
657 MOS_SafeFreeMemory(ulValueBuf);
658 m_userSettingMutex.Unlock();
659 return MOS_STATUS_USER_FEATURE_KEY_READ_FAILED;
660 }
661 MosUtilities::MosSecureStrcpy(Key->pValueArray[iPos].pcValueName,
662 MAX_USERFEATURE_LINE_LENGTH,
663 NewKey.pValueArray[0].pcValueName);
664 }
665 else
666 {
667 //if found, the previous value buffer needs to be freed before reallocating
668 MOS_FreeMemory(Key->pValueArray[iPos].ulValueBuf);
669 MosUtilities::MosAtomicDecrement(MosUtilities::m_mosMemAllocFakeCounter);
670 MOS_OS_NORMALMESSAGE("ulValueBuf %p for key %s", ulValueBuf, NewKey.pValueArray[0].pcValueName);
671 }
672
673 Key->pValueArray[iPos].ulValueLen = NewKey.pValueArray[0].ulValueLen;
674 Key->pValueArray[iPos].ulValueType = NewKey.pValueArray[0].ulValueType;
675 Key->pValueArray[iPos].ulValueBuf = ulValueBuf;
676
677 MosUtilities::MosZeroMemory(Key->pValueArray[iPos].ulValueBuf, NewKey.pValueArray[0].ulValueLen);
678
679 MosUtilities::MosSecureMemcpy(Key->pValueArray[iPos].ulValueBuf,
680 NewKey.pValueArray[0].ulValueLen,
681 NewKey.pValueArray[0].ulValueBuf,
682 NewKey.pValueArray[0].ulValueLen);
683
684 m_userSettingMutex.Unlock();
685 return MOS_STATUS_SUCCESS;
686 }
687
688 MOS_STATUS MosUtilitiesSpecificNext::UserFeatureQuery(MOS_PUF_KEYLIST pKeyList, MOS_UF_KEY *NewKey)
689 {
690 int32_t iPos;
691 MOS_UF_VALUE *pValueArray;
692 MOS_UF_KEY *Key;
693
694 iPos = -1;
695 pValueArray = nullptr;
696
697 // can't find key in user feature
698 if ( (Key = UserFeatureFindKey(pKeyList, NewKey->pcKeyName)) == nullptr )
699 {
700 return MOS_STATUS_UNKNOWN;
701 }
702
703 // can't find Value in the key
704 if ( (iPos = UserFeatureFindValue(*Key, NewKey->pValueArray[0].pcValueName)) == NOT_FOUND)
705 {
706 return MOS_STATUS_UNKNOWN;
707 }
708
709 //get key content from user feature
710 MosUtilities::MosSecureMemcpy(NewKey->pValueArray[0].ulValueBuf,
711 Key->pValueArray[iPos].ulValueLen,
712 Key->pValueArray[iPos].ulValueBuf,
713 Key->pValueArray[iPos].ulValueLen);
714
715 NewKey->pValueArray[0].ulValueLen = Key->pValueArray[iPos].ulValueLen;
716 NewKey->pValueArray[0].ulValueType = Key->pValueArray[iPos].ulValueType;
717
718 return MOS_STATUS_SUCCESS;
719 }
720
721 MOS_STATUS MosUtilitiesSpecificNext::UserFeatureReadNextTokenFromFile(FILE *pFile, const char *szFormat, char *szToken)
722 {
723 size_t nTokenSize = 0;
724
725 // Reads the next token from the given pFile.
726 if (fscanf(pFile, szFormat, szToken) <= 0)
727 {
728 MOS_OS_VERBOSEMESSAGE("Failed reading the next token from the user feature file. This is probably because the token does not exist in the user feature file.");
729 return MOS_STATUS_FILE_READ_FAILED;
730 }
731
732 // Converts to Unix-style line endings to prevent compatibility problems.
733 nTokenSize = strnlen(szToken, MAX_USERFEATURE_LINE_LENGTH);
734 if (szToken[nTokenSize-1] == '\r')
735 {
736 szToken[nTokenSize-1] = '\0';
737 }
738
739 return MOS_STATUS_SUCCESS;
740 }
741
742 MOS_STATUS MosUtilitiesSpecificNext::UserFeatureDumpFile(const char * const szFileName, MOS_PUF_KEYLIST* pKeyList)
743 {
744 MOS_UF_KEY *CurKey;
745 MOS_UF_VALUE *CurValue;
746 char szTmp[MAX_USERFEATURE_LINE_LENGTH];
747 int32_t iResult;
748 size_t nSize;
749 int32_t bFirst;
750 int32_t iCount;
751 PFILE File;
752 int32_t bEmpty;
753 uint32_t iCurId;
754 MOS_STATUS eStatus;
755 char *tmpChar; // Used in the 64-bit case to read uint64_t
756
757 CurValue = nullptr;
758 nSize = 0;
759 bFirst = 1; // 1 stand for "is the first key".
760 iCount = 0;
761 File = nullptr;
762 bEmpty = 0;
763 iCurId = 0;
764 eStatus = MOS_STATUS_SUCCESS;
765
766 CurKey = (MOS_UF_KEY *)MOS_AllocAndZeroMemory(sizeof(MOS_UF_KEY));
767 if (CurKey == nullptr)
768 {
769 return MOS_STATUS_NO_SPACE;
770 }
771 CurKey->valueNum = 0;
772 CurKey->pcKeyName[0] = '\0';
773 CurKey->pValueArray = nullptr;
774
775 if ( (File = fopen(szFileName, "r")) == nullptr)
776 {
777 MOS_FreeMemory(CurKey);
778 return MOS_STATUS_USER_FEATURE_KEY_READ_FAILED;
779 }
780 while (feof(File) != EOF)
781 {
782 MosUtilities::MosZeroMemory(szTmp, MAX_USERFEATURE_LINE_LENGTH*sizeof(char ));
783 if (MOS_FAILED(UserFeatureReadNextTokenFromFile(File, MAX_UF_LINE_STRING_FORMAT, szTmp)))
784 {
785 break;
786 }
787
788 // set szDumpData with extracted File content.
789 iResult = strcmp(szTmp, UF_KEY_ID);
790 if ( iResult == 0 )
791 {
792 // It is a new key starting!
793 if (! bFirst )
794 {
795 // Add last key struct to contents when the key is not first.
796 // otherwise, continue to load key struct data.
797 CurKey->pValueArray = CurValue;
798 CurKey->valueNum = iCount;
799 if(UserFeatureAdd(pKeyList, CurKey) != MOS_STATUS_SUCCESS)
800 {
801 // if the CurKey didn't be added in pKeyList, free it.
802 MOS_FreeMemory(CurKey);
803 }
804 CurKey = (MOS_UF_KEY *)MOS_AllocAndZeroMemory(sizeof(MOS_UF_KEY));
805 if (CurKey == nullptr)
806 {
807 eStatus = MOS_STATUS_NO_SPACE;
808 break;
809 }
810 } // if (! bFirst )
811
812 if (fscanf(File, "%x\n", &iCurId) <= 0)
813 {
814 break;
815 }
816
817 CurKey->UFKey = (void *)(intptr_t)iCurId;
818
819 MosUtilities::MosZeroMemory(szTmp, MAX_USERFEATURE_LINE_LENGTH * sizeof(char));
820 if (MOS_FAILED(UserFeatureReadNextTokenFromFile(File, MAX_UF_LINE_STRING_FORMAT, szTmp)))
821 {
822 break;
823 }
824
825 MosUtilities::MosSecureStrcpy(CurKey->pcKeyName, MAX_USERFEATURE_LINE_LENGTH, szTmp);
826 CurKey->valueNum = 0;
827
828 // allocate capability length for valuearray.
829 CurValue = (MOS_UF_VALUE *)MOS_AllocAndZeroMemory(sizeof(MOS_UF_VALUE) * UF_CAPABILITY);
830 if (CurValue == nullptr)
831 {
832 eStatus = MOS_STATUS_NO_SPACE;
833 break;
834 }
835 bFirst = 0;
836 iCount = 0; // next key's array number.
837 bEmpty = 1;
838 } // if ( iResult == 0 )
839 else // not a key
840 {
841 // Is it a value starting?
842 iResult = strcmp(szTmp, UF_VALUE_ID);
843 if ( iResult == 0 )
844 {
845 if (MOS_FAILED(UserFeatureReadNextTokenFromFile(File, MAX_UF_LINE_STRING_FORMAT, szTmp)))
846 {
847 break;
848 }
849
850 if (CurValue == nullptr)
851 {
852 break;
853 }
854
855 // Out of bounds technically based on how much memory we allocated
856 if (iCount < 0 || iCount >= UF_CAPABILITY)
857 {
858 eStatus = MOS_STATUS_USER_FEATURE_KEY_READ_FAILED;
859 MOS_OS_ASSERTMESSAGE("user setting value icount %d, and it must meet 0 < icount < UF_CAPABILITY(64)", iCount);
860 break;
861 }
862
863 // Load value name;
864 MosUtilities::MosSecureStrcpy(CurValue[iCount].pcValueName, MAX_USERFEATURE_LINE_LENGTH, szTmp);
865
866 // Load value type
867 if (MOS_FAILED(UserFeatureReadNextTokenFromFile(File, MAX_UF_LINE_STRING_FORMAT, szTmp)))
868 {
869 break;
870 }
871
872 CurValue[iCount].ulValueType = atoi(szTmp);
873
874 // Load value buffer.
875 switch ( CurValue[iCount].ulValueType )
876 {
877 case UF_DWORD: // 32-bit
878 if (MOS_FAILED(UserFeatureReadNextTokenFromFile(File, MAX_UF_LINE_STRING_FORMAT, szTmp)))
879 {
880 break;
881 }
882
883 CurValue[iCount].ulValueLen = sizeof(uint32_t);
884 CurValue[iCount].ulValueBuf = MOS_AllocMemory(sizeof(uint32_t));
885 if(CurValue[iCount].ulValueBuf == nullptr)
886 {
887 eStatus = MOS_STATUS_NO_SPACE;
888 break;
889 }
890 *(uint32_t*)(CurValue[iCount].ulValueBuf) = atoi(szTmp);
891 break;
892 case UF_QWORD: // 64-bit
893 if (MOS_FAILED(UserFeatureReadNextTokenFromFile(File, MAX_UF_LINE_STRING_FORMAT, szTmp)))
894 {
895 break;
896 }
897
898 CurValue[iCount].ulValueLen = sizeof(uint64_t);
899 CurValue[iCount].ulValueBuf = MOS_AllocMemory(sizeof(uint64_t));
900 if(CurValue[iCount].ulValueBuf == nullptr)
901 {
902 eStatus = MOS_STATUS_NO_SPACE;
903 break;
904 }
905 tmpChar = &szTmp[0];
906 *(uint64_t*)(CurValue[iCount].ulValueBuf) = strtoll(tmpChar,&tmpChar,0);
907 break;
908 case UF_SZ:
909 case UF_MULTI_SZ:
910 if (MOS_FAILED(UserFeatureReadNextTokenFromFile(File, MAX_UF_LINE_STRING_FORMAT, szTmp)))
911 {
912 break;
913 }
914
915 nSize = strlen(szTmp);
916 CurValue[iCount].ulValueLen = (nSize+1)*sizeof(char );
917 CurValue[iCount].ulValueBuf = MOS_AllocMemory(nSize+1);
918 if(CurValue[iCount].ulValueBuf == nullptr)
919 {
920 eStatus = MOS_STATUS_NO_SPACE;
921 break;
922 }
923 MosUtilities::MosZeroMemory(CurValue[iCount].ulValueBuf, nSize+1);
924 MosUtilities::MosSecureMemcpy(CurValue[iCount].ulValueBuf, nSize, szTmp, nSize);
925 break;
926 default:
927 eStatus = MOS_STATUS_UNKNOWN;
928 }
929 if (eStatus != MOS_STATUS_SUCCESS)
930 {
931 break;
932 }
933
934 iCount ++; // do the error checking near the top
935
936 } // if ( iResult == 0 )
937 else // It is not a value starting, it's bad User Feature File.
938 {
939 int32_t iResult = strcmp(szTmp, "");
940 if ( !iResult )
941 {
942 continue;
943 }
944 else
945 {
946 eStatus = MOS_STATUS_INVALID_PARAMETER;
947 break;
948 }
949 } // else ( iResult == 0 )
950 }
951 } // while (feof(File) != EOF)
952
953 if (eStatus == MOS_STATUS_SUCCESS)
954 {
955 if ( bEmpty && (strlen(CurKey->pcKeyName) > 0) &&
956 (CurKey->valueNum == 0) )
957 {
958 CurKey->pValueArray = CurValue;
959 CurKey->valueNum = iCount;
960 if(UserFeatureAdd(pKeyList, CurKey) != MOS_STATUS_SUCCESS)
961 {
962 // if the CurKey didn't be added in pKeyList, free it.
963 for (uint32_t i = 0; i < iCount; i++)
964 {
965 if (CurValue)
966 {
967 MOS_FreeMemory(CurValue[i].ulValueBuf);
968 }
969 }
970 MOS_FreeMemory(CurValue);
971 MOS_FreeMemory(CurKey);
972 }
973 }
974 else
975 {
976 for (uint32_t i = 0; i < iCount; i++)
977 {
978 if (CurValue)
979 {
980 MOS_FreeMemory(CurValue[i].ulValueBuf);
981 }
982 }
983 MOS_FreeMemory(CurValue);
984 MOS_FreeMemory(CurKey);
985 }
986 }
987 else
988 {
989 for (uint32_t i = 0; i < iCount; i++)
990 {
991 if (CurValue)
992 {
993 MOS_FreeMemory(CurValue[i].ulValueBuf);
994 }
995 }
996 MOS_FreeMemory(CurValue);
997 MOS_FreeMemory(CurKey);
998 }
999 fclose(File);
1000 return eStatus;
1001 }
1002
1003 MOS_STATUS MosUtilitiesSpecificNext::UserFeatureDumpDataToFile(const char *szFileName, MOS_PUF_KEYLIST pKeyList)
1004 {
1005 int32_t iResult;
1006 PFILE File;
1007 MOS_PUF_KEYLIST pKeyTmp;
1008 int32_t j;
1009
1010 // For release version: writes to the file if it exists,
1011 // skips if it does not exist
1012 // For other version: always writes to the file
1013
1014 #if(_RELEASE)
1015 File = fopen(szFileName, "r");
1016 if (File == NULL)
1017 {
1018 return MOS_STATUS_SUCCESS;
1019 }
1020 else
1021 {
1022 fclose(File);
1023 File = fopen(szFileName, "w+");
1024 }
1025 #else
1026 File = fopen(szFileName, "w+");
1027 #endif
1028
1029 if ( !File )
1030 {
1031 return MOS_STATUS_USER_FEATURE_KEY_WRITE_FAILED;
1032 }
1033
1034 for (pKeyTmp = pKeyList; pKeyTmp; pKeyTmp = pKeyTmp->pNext)
1035 {
1036 fprintf(File, "%s\n", UF_KEY_ID);
1037 fprintf(File, "\t0x%.8x\n", (uint32_t)(uintptr_t)pKeyTmp->pElem->UFKey);
1038 fprintf(File, "\t%s\n", pKeyTmp->pElem->pcKeyName);
1039 for ( j = 0; j < pKeyTmp->pElem->valueNum; j ++ )
1040 {
1041 fprintf(File, "\t\t%s\n", UF_VALUE_ID);
1042 if ( strlen(pKeyTmp->pElem->pValueArray[j].pcValueName) > 0 )
1043 {
1044 fprintf(File, "\t\t\t%s\n",
1045 pKeyTmp->pElem->pValueArray[j].pcValueName);
1046 }
1047 fprintf(File, "\t\t\t%d\n", pKeyTmp->pElem->pValueArray[j].ulValueType);
1048 if (pKeyTmp->pElem->pValueArray[j].ulValueBuf != nullptr)
1049 {
1050 switch (pKeyTmp->pElem->pValueArray[j].ulValueType)
1051 {
1052 case UF_SZ:
1053 fprintf(File, "\t\t\t%s\n",
1054 (char *)(pKeyTmp->pElem->pValueArray[j].ulValueBuf));
1055 break;
1056 case UF_DWORD:
1057 fprintf(File, "\t\t\t%u\n",
1058 *(uint32_t*)(pKeyTmp->pElem->pValueArray[j].ulValueBuf));
1059 break;
1060 case UF_QWORD:
1061 fprintf(File, "\t\t\t%" PRIu64"\n", *(uint64_t*)(pKeyTmp->pElem->pValueArray[j].ulValueBuf));
1062 break;
1063 default:
1064 fprintf(File, "\t\t\t%s\n",
1065 (char *)(pKeyTmp->pElem->pValueArray[j].ulValueBuf));
1066 break;
1067 } //switch (pKeyTmp->pElem->pValueArray[j].ulValueType)
1068 }
1069 } // for ( j = 0; j < pKeyTmp->pElem->valueNum; j ++ )
1070 } //for (pKeyTmp = pKeyList; pKeyTmp; pKeyTmp = pKeyTmp->pNext)
1071 fclose(File);
1072
1073 return MOS_STATUS_SUCCESS;
1074 }
1075
1076 void MosUtilitiesSpecificNext::UserFeatureFreeKeyList(MOS_PUF_KEYLIST pKeyList)
1077 {
1078 MOS_PUF_KEYLIST pKeyTmp;
1079 MOS_PUF_KEYLIST pKeyTmpNext;
1080 uint32_t i;
1081
1082 pKeyTmp = pKeyList;
1083 while(pKeyTmp)
1084 {
1085 pKeyTmpNext = pKeyTmp->pNext;
1086 for(i=0;i<pKeyTmp->pElem->valueNum;i++)
1087 {
1088 MOS_FreeMemory(pKeyTmp->pElem->pValueArray[i].ulValueBuf);
1089 }
1090 MOS_FreeMemory(pKeyTmp->pElem->pValueArray);
1091 MOS_FreeMemory(pKeyTmp->pElem);
1092 MOS_FreeMemory(pKeyTmp);
1093 pKeyTmp = pKeyTmpNext;
1094 }
1095 return;
1096 }
1097
1098 MOS_STATUS MosUtilitiesSpecificNext::UserFeatureSetValue(
1099 char * const strKey,
1100 const char * const pcValueName,
1101 uint32_t uiValueType,
1102 void *pData,
1103 int32_t nDataSize)
1104 {
1105 MOS_UF_KEY NewKey;
1106 MOS_UF_VALUE NewValue;
1107 MOS_STATUS eStatus;
1108
1109 eStatus = MOS_STATUS_UNKNOWN;
1110
1111 if ((strKey == nullptr) || (pcValueName == nullptr) || (m_ufKeyList == nullptr))
1112 {
1113 return MOS_STATUS_INVALID_PARAMETER;
1114 }
1115
1116 MosUtilities::MosZeroMemory(NewValue.pcValueName, MAX_USERFEATURE_LINE_LENGTH);
1117 MosUtilities::MosSecureStrcpy(NewValue.pcValueName, MAX_USERFEATURE_LINE_LENGTH, pcValueName);
1118 NewValue.ulValueType = uiValueType;
1119 if( NewValue.ulValueType == UF_DWORD)
1120 {
1121 NewValue.ulValueLen = sizeof(uint32_t);
1122 }
1123 else
1124 {
1125 NewValue.ulValueLen = nDataSize;
1126 }
1127 NewValue.ulValueBuf = pData;
1128
1129 MosUtilities::MosZeroMemory(NewKey.pcKeyName, MAX_USERFEATURE_LINE_LENGTH);
1130 MosUtilities::MosSecureStrcpy(NewKey.pcKeyName, MAX_USERFEATURE_LINE_LENGTH, strKey);
1131 NewKey.pValueArray = &NewValue;
1132 NewKey.valueNum = 1;
1133
1134 if ( ( eStatus = UserFeatureSet(&MosUtilitiesSpecificNext::m_ufKeyList, NewKey)) == MOS_STATUS_SUCCESS )
1135 {
1136 MosUtilities::MosUserFeatureNotifyChangeKeyValue(nullptr, false, nullptr, true);
1137 }
1138
1139 return eStatus;
1140 }
1141
1142 MOS_STATUS MosUtilitiesSpecificNext::UserFeatureQueryValue(
1143 char * const strKey,
1144 const char * const pcValueName,
1145 uint32_t *uiValueType,
1146 void *pData,
1147 int32_t *nDataSize)
1148 {
1149 MOS_UF_KEY NewKey;
1150 MOS_UF_VALUE NewValue;
1151 size_t nKeyLen, nValueLen;
1152 MOS_STATUS eStatus;
1153 MOS_PUF_KEYLIST pKeyList;
1154 char strTempKey[MAX_USERFEATURE_LINE_LENGTH];
1155 char strTempValueName[MAX_USERFEATURE_LINE_LENGTH];
1156
1157 eStatus = MOS_STATUS_UNKNOWN;
1158 pKeyList = MosUtilitiesSpecificNext::m_ufKeyList;
1159
1160 if ( (strKey == nullptr) || (pcValueName == nullptr) || (pKeyList == nullptr))
1161 {
1162 return MOS_STATUS_INVALID_PARAMETER;
1163 }
1164 MosUtilities::MosZeroMemory(NewValue.pcValueName, MAX_USERFEATURE_LINE_LENGTH);
1165 MosUtilities::MosSecureStrcpy(NewValue.pcValueName, MAX_USERFEATURE_LINE_LENGTH, pcValueName);
1166 NewValue.ulValueBuf = pData;
1167
1168 MosUtilities::MosZeroMemory(NewKey.pcKeyName, MAX_USERFEATURE_LINE_LENGTH);
1169 MosUtilities::MosSecureStrcpy(NewKey.pcKeyName, MAX_USERFEATURE_LINE_LENGTH, strKey);
1170 NewKey.pValueArray = &NewValue;
1171 NewKey.valueNum = 1;
1172
1173 if ( (eStatus = UserFeatureQuery(pKeyList, &NewKey)) == MOS_STATUS_SUCCESS )
1174 {
1175 if(uiValueType != nullptr)
1176 {
1177 *uiValueType = NewKey.pValueArray[0].ulValueType;
1178 }
1179 if (nDataSize != nullptr)
1180 {
1181 *nDataSize = NewKey.pValueArray[0].ulValueLen;
1182 }
1183 }
1184
1185 return eStatus;
1186 }
1187
1188 MOS_STATUS MosUtilitiesSpecificNext::UserFeatureGetKeyIdbyName(const char *pcKeyName, void **pUFKey)
1189 {
1190 MOS_PUF_KEYLIST pKeyList;
1191 int32_t iResult;
1192 MOS_STATUS eStatus;
1193 MOS_PUF_KEYLIST pTempNode;
1194
1195 pKeyList = MosUtilitiesSpecificNext::m_ufKeyList;
1196 iResult = -1;
1197
1198 eStatus = MOS_STATUS_INVALID_PARAMETER;
1199
1200 for(pTempNode=pKeyList; pTempNode; pTempNode=pTempNode->pNext)
1201 {
1202 iResult = strcmp(pTempNode->pElem->pcKeyName, pcKeyName);
1203 if ( iResult == 0 )
1204 {
1205 *pUFKey = pTempNode->pElem->UFKey;
1206 eStatus = MOS_STATUS_SUCCESS;
1207 break;
1208 }
1209 }
1210
1211 return eStatus;
1212 }
1213
1214 MOS_STATUS MosUtilitiesSpecificNext::UserFeatureGetKeyNamebyId(void *UFKey, char *pcKeyName)
1215 {
1216 MOS_PUF_KEYLIST pKeyList;
1217 MOS_PUF_KEYLIST pTempNode;
1218 MOS_STATUS eStatus;
1219
1220 pKeyList = MosUtilitiesSpecificNext::m_ufKeyList;
1221
1222 switch((uintptr_t)UFKey)
1223 {
1224 case UFKEY_INTERNAL:
1225 MosUtilities::MosSecureStrcpy(pcKeyName, MAX_USERFEATURE_LINE_LENGTH, USER_FEATURE_KEY_INTERNAL);
1226 eStatus = MOS_STATUS_SUCCESS;
1227 break;
1228 case UFKEY_EXTERNAL:
1229 MosUtilities::MosSecureStrcpy(pcKeyName, MAX_USERFEATURE_LINE_LENGTH, USER_FEATURE_KEY_EXTERNAL);
1230 eStatus = MOS_STATUS_SUCCESS;
1231 break;
1232 default:
1233 eStatus = MOS_STATUS_UNKNOWN;
1234
1235 for(pTempNode=pKeyList;pTempNode;pTempNode=pTempNode->pNext)
1236 {
1237 if(pTempNode->pElem->UFKey == UFKey)
1238 {
1239 MosUtilities::MosSecureStrcpy(pcKeyName, MAX_USERFEATURE_LINE_LENGTH, pTempNode->pElem->pcKeyName);
1240 eStatus = MOS_STATUS_SUCCESS;
1241 break;
1242 }
1243 }
1244 break;
1245 }
1246
1247 return eStatus;
1248
1249 }
1250
1251 MOS_STATUS MosUtilitiesSpecificNext::MosUserFeatureOpenKeyFile(
1252 void *UFKey,
1253 const char *lpSubKey,
1254 uint32_t ulOptions, // reserved
1255 uint32_t samDesired,
1256 void **phkResult)
1257 {
1258 char pcKeyName[MAX_USERFEATURE_LINE_LENGTH];
1259 MOS_STATUS iRet;
1260 uintptr_t h_key = (uintptr_t)UFKey;
1261 MOS_UNUSED(ulOptions);
1262 MOS_UNUSED(samDesired);
1263
1264 if((h_key == 0) /*|| (lpSubKey == nullptr)*/ || (phkResult == nullptr)) //[SH]: subkey can be NULL???
1265 {
1266 return MOS_STATUS_INVALID_PARAMETER;
1267 }
1268
1269 MosUtilities::MosZeroMemory(pcKeyName, MAX_USERFEATURE_LINE_LENGTH*sizeof(char));
1270 switch(h_key)
1271 {
1272 case UFKEY_INTERNAL:
1273 MosUtilities::MosSecureStrcpy(pcKeyName, MAX_USERFEATURE_LINE_LENGTH, USER_FEATURE_KEY_INTERNAL);
1274 break;
1275 case UFKEY_EXTERNAL:
1276 MosUtilities::MosSecureStrcpy(pcKeyName, MAX_USERFEATURE_LINE_LENGTH, USER_FEATURE_KEY_EXTERNAL);
1277 break;
1278 default:
1279 break;
1280 }
1281
1282 MosUtilities::MosSecureStrcat(pcKeyName, sizeof(pcKeyName), lpSubKey);
1283 iRet = UserFeatureGetKeyIdbyName(pcKeyName, phkResult);
1284
1285 return iRet;
1286 }
1287
1288 MOS_STATUS MosUtilitiesSpecificNext::MosUserFeatureGetValueFile(
1289 void *UFKey,
1290 const char *lpSubKey,
1291 const char *lpValue,
1292 uint32_t dwFlags,
1293 uint32_t *pdwType,
1294 void *pvData,
1295 uint32_t *pcbData)
1296 {
1297 char pcKeyName[MAX_USERFEATURE_LINE_LENGTH];
1298 MOS_STATUS eStatus;
1299 MOS_UNUSED(dwFlags);
1300
1301 if(UFKey == nullptr)
1302 {
1303 return MOS_STATUS_INVALID_PARAMETER;
1304 }
1305
1306 eStatus = MOS_STATUS_UNKNOWN;
1307 MosUtilities::MosZeroMemory(pcKeyName, MAX_USERFEATURE_LINE_LENGTH * sizeof(char));
1308 if ( (eStatus = UserFeatureGetKeyNamebyId(UFKey,pcKeyName)) != MOS_STATUS_SUCCESS)
1309 {
1310 return eStatus;
1311 }
1312
1313 if(lpSubKey != nullptr)
1314 {
1315 MosUtilities::MosSecureStrcat(pcKeyName, sizeof(pcKeyName), lpSubKey);
1316 }
1317 eStatus = UserFeatureQueryValue(pcKeyName,
1318 lpValue,
1319 (uint32_t*)pdwType,
1320 pvData,
1321 (int32_t*)pcbData);
1322
1323 return eStatus;
1324 }
1325
1326 MOS_STATUS MosUtilitiesSpecificNext::MosUserFeatureSetValueExFile(
1327 void *UFKey,
1328 const char *lpValueName,
1329 uint32_t Reserved,
1330 uint32_t dwType,
1331 uint8_t *lpData,
1332 uint32_t cbData)
1333 {
1334 char pcKeyName[MAX_USERFEATURE_LINE_LENGTH];
1335 MOS_STATUS eStatus;
1336 MOS_UNUSED(Reserved);
1337
1338 if (UFKey == nullptr)
1339 {
1340 return MOS_STATUS_INVALID_PARAMETER;
1341 }
1342 MosUtilities::MosZeroMemory(pcKeyName, MAX_USERFEATURE_LINE_LENGTH*sizeof(char));
1343 if ((eStatus = UserFeatureGetKeyNamebyId(UFKey,pcKeyName)) != MOS_STATUS_SUCCESS)
1344 {
1345 return eStatus;
1346 }
1347
1348 eStatus = UserFeatureSetValue(pcKeyName,lpValueName,dwType,lpData,cbData);
1349
1350 return eStatus;
1351 }
1352
1353 // Read an env var value from GFX_CONF_FILE first, then fall back to getenv().
1354 // Modeled on va_parseConfig() in libva/va/va.c.
1355 // Returns the value string, or empty if the variable is not set in either source.
1356 static std::string MosParseEnvFromConfig(const char *env)
1357 {
1358 if (env == nullptr)
1359 return "";
1360
1361 char oneline[1024];
1362 char *token, *value, *saveptr;
1363 FILE *fp = fopen(GFX_CONF_FILE, "r");
1364 while (fp && fgets(oneline, sizeof(oneline), fp) != NULL)
1365 {
1366 if (strlen(oneline) == 1)
1367 continue;
1368 token = strtok_r(oneline, "=\n", &saveptr);
1369 value = strtok_r(NULL, "=\n", &saveptr);
1370 if (token == nullptr || value == nullptr)
1371 continue;
1372 if (strcmp(token, env) == 0)
1373 {
1374 fclose(fp);
1375 return value;
1376 }
1377 }
1378 if (fp)
1379 fclose(fp);
1380
1381 // No setting in config file; fall back to process environment.
1382 const char *env_val = getenv(env);
1383 return env_val ? env_val : "";
1384 }
1385
1386 MOS_STATUS MosUtilities::MosOsUtilitiesInit(MediaUserSettingSharedPtr userSettingPtr)
1387 {
1388 MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
1389
1390 // lock mutex to avoid multi init in multi-threading env
1391 m_mutexLock.Lock();
1392
1393 #if (_DEBUG || _RELEASE_INTERNAL)
1394 // Get use user feature file from env, instead of default.
1395 FILE* fp = nullptr;
1396 static char* tmpFile = getenv("GFX_FEATURE_FILE");
1397
1398 if (tmpFile != nullptr)
1399 {
1400 if ((fp = fopen(tmpFile, "r")) != nullptr)
1401 {
1402 MosUtilitiesSpecificNext::m_szUserFeatureFile = tmpFile;
1403 fclose(fp);
1404 MOS_OS_NORMALMESSAGE("using %s for USER_FEATURE_FILE", MosUtilitiesSpecificNext::m_szUserFeatureFile);
1405 }
1406 else
1407 {
1408 MOS_OS_ASSERTMESSAGE("Can't open %s for USER_FEATURE_FILE!!!", tmpFile);
1409 m_mutexLock.Unlock();
1410 return MOS_STATUS_FILE_NOT_FOUND;
1411 }
1412 }
1413 #endif
1414
1415 //The user setting is device based, no need to guard with the reference count.
1416 //It will be destroyed in media context termiation.
1417 eStatus = MosUserSetting::InitMosUserSetting(userSettingPtr);
1418
1419 if (m_mosUtilInitCount == 0)
1420 {
1421 //Init MOS User Feature Key from mos desc table
1422 MosUtilitiesSpecificNext::UserFeatureDumpFile(MosUtilitiesSpecificNext::m_szUserFeatureFile, &MosUtilitiesSpecificNext::m_ufKeyList);
1423 MosDeclareUserFeature();
1424
1425 #if MOS_MESSAGES_ENABLED
1426 // Initialize MOS message params structure and HLT
1427 MosUtilDebug::MosMessageInit(userSettingPtr);
1428 #endif // MOS_MESSAGES_ENABLED
1429 if (m_mosMemAllocCounter &&
1430 m_mosMemAllocCounterGfx &&
1431 m_mosMemAllocFakeCounter)
1432 {
1433 *m_mosMemAllocCounter = 0;
1434 *m_mosMemAllocFakeCounter = 0;
1435 *m_mosMemAllocCounterGfx = 0;
1436 }
1437 else
1438 {
1439 MOS_OS_ASSERTMESSAGE("MemNinja count pointers are nullptr");
1440 }
1441
1442 MosTraceEventInit();
1443 }
1444 m_mosUtilInitCount++;
1445
1446 m_mutexLock.Unlock();
1447 return eStatus;
1448 }
1449
1450 MOS_STATUS MosUtilities::MosOsUtilitiesClose(MediaUserSettingSharedPtr userSettingPtr)
1451 {
1452 int32_t memoryCounter = 0;
1453 MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
1454
1455 // lock mutex to avoid multi close in multi-threading env
1456 m_mutexLock.Lock();
1457 m_mosUtilInitCount--;
1458 if (m_mosUtilInitCount == 0)
1459 {
1460 MosTraceEventClose();
1461 if (m_mosMemAllocCounter &&
1462 m_mosMemAllocCounterGfx &&
1463 m_mosMemAllocFakeCounter)
1464 {
1465 *m_mosMemAllocCounter -= *m_mosMemAllocFakeCounter;
1466 memoryCounter = *m_mosMemAllocCounter + *m_mosMemAllocCounterGfx;
1467 m_mosMemAllocCounterNoUserFeature = *m_mosMemAllocCounter;
1468 m_mosMemAllocCounterNoUserFeatureGfx = *m_mosMemAllocCounterGfx;
1469 MOS_OS_VERBOSEMESSAGE("MemNinja leak detection end");
1470 ReportUserSetting(
1471 userSettingPtr,
1472 __MEDIA_USER_FEATURE_VALUE_MEMNINJA_COUNTER,
1473 memoryCounter,
1474 MediaUserSetting::Group::Device);
1475 }
1476 MosDestroyUserFeature();
1477
1478 #if (_DEBUG || _RELEASE_INTERNAL)
1479 // MOS maintains a reference counter,
1480 // so if there still is another active lib instance, logs would still be printed.
1481 MosUtilDebug::MosMessageClose();
1482 #endif
1483 MosUtilitiesSpecificNext::UserFeatureDumpDataToFile(MosUtilitiesSpecificNext::m_szUserFeatureFile, MosUtilitiesSpecificNext::m_ufKeyList);
1484 MosUtilitiesSpecificNext::UserFeatureFreeKeyList(MosUtilitiesSpecificNext::m_ufKeyList);
1485 MosUtilitiesSpecificNext::m_ufKeyList = nullptr;
1486 }
1487 m_mutexLock.Unlock();
1488 return eStatus;
1489 }
1490
1491 MOS_STATUS MosUtilities::MosUserFeatureOpenKey(
1492 void *ufKey,
1493 const char *lpSubKey,
1494 uint32_t ulOptions,
1495 uint32_t samDesired,
1496 void **phkResult,
1497 MOS_USER_FEATURE_KEY_PATH_INFO *ufInfo)
1498 {
1499 MOS_UNUSED(ufInfo);
1500
1501 return MosUtilitiesSpecificNext::MosUserFeatureOpenKeyFile(ufKey, lpSubKey, ulOptions, samDesired, phkResult);
1502 }
1503
1504 MOS_STATUS MosUtilities::MosUserFeatureCloseKey(void *ufKey)
1505 {
1506 MOS_UNUSED(ufKey);
1507 //always return success, because we actually dong't have a key opened.
1508 return MOS_STATUS_SUCCESS;
1509 }
1510
1511 MOS_STATUS MosUtilities::MosUserFeatureGetValue(
1512 void *UFKey,
1513 const char *lpSubKey,
1514 const char *lpValue,
1515 uint32_t dwFlags,
1516 uint32_t *pdwType,
1517 void *pvData,
1518 uint32_t *pcbData)
1519 {
1520 return MosUtilitiesSpecificNext::MosUserFeatureGetValueFile(UFKey, lpSubKey, lpValue, dwFlags, pdwType, pvData, pcbData);
1521
1522 }
1523
1524 MOS_STATUS MosUtilities::MosUserFeatureQueryValueEx(
1525 void *UFKey,
1526 char *lpValueName,
1527 uint32_t *lpReserved,
1528 uint32_t *lpType,
1529 char *lpData,
1530 uint32_t *lpcbData)
1531 {
1532 MOS_UNUSED(lpReserved);
1533 return MosUserFeatureGetValue(UFKey, "", lpValueName, 0, lpType, lpData, lpcbData);
1534 }
1535
1536 MOS_STATUS MosUtilities::MosUserFeatureSetValueEx(
1537 void *UFKey,
1538 const char *lpValueName,
1539 uint32_t Reserved,
1540 uint32_t dwType,
1541 uint8_t *lpData,
1542 uint32_t cbData)
1543 {
1544 if (dwType == UF_SZ || dwType == UF_MULTI_SZ)
1545 {
1546 if (lpData == nullptr || strlen((const char*)lpData) == 0)
1547 {
1548 MOS_OS_NORMALMESSAGE("NULL string, skip to report");
1549 return MOS_STATUS_SUCCESS;
1550 }
1551 }
1552
1553 return MosUtilitiesSpecificNext::MosUserFeatureSetValueExFile(UFKey, lpValueName, Reserved, dwType, lpData, cbData);
1554 }
1555
1556 MOS_STATUS MosUtilities::MosUserFeatureNotifyChangeKeyValue(
1557 void *UFKey,
1558 int32_t bWatchSubtree,
1559 HANDLE hEvent,
1560 int32_t fAsynchronous)
1561 {
1562 key_t key;
1563 int32_t semid;
1564 struct sembuf operation[1] ;
1565
1566 key = ftok(MosUtilitiesSpecificNext::m_szUserFeatureFile, 1);
1567 semid = semget(key,1,0);
1568 //change semaphore
1569 operation[0].sem_op = 1;
1570 operation[0].sem_num = 0;
1571 operation[0].sem_flg = SEM_UNDO;
1572 semop(semid, operation, 1);
1573
1574 return MOS_STATUS_SUCCESS;
1575 }
1576
1577 MOS_STATUS MosUtilities::MosInitializeReg(RegBufferMap &regBufferMap)
1578 {
1579 MOS_STATUS status = MOS_STATUS_SUCCESS;
1580
1581 #if (_DEBUG || _RELEASE_INTERNAL)
1582 // Get user feature file next from config file or env, instead of default.
1583 // GFX_CONF_FILE (/etc/igfx.conf) takes priority over the environment variable,
1584 // following the pattern used by va_parseConfig() in libva.
1585 FILE* fp = nullptr;
1586 static std::string tmpFileNext = MosParseEnvFromConfig("GFX_FEATURE_FILE_NEXT");
1587
1588 if (!tmpFileNext.empty())
1589 {
1590 if ((fp = fopen(tmpFileNext.c_str(), "r")) != nullptr)
1591 {
1592 MosUtilitiesSpecificNext::m_szUserFeatureFileNext = tmpFileNext;
1593 fclose(fp);
1594 MOS_OS_NORMALMESSAGE("using %s for USER_FEATURE_FILE_NEXT", MosUtilitiesSpecificNext::m_szUserFeatureFileNext.c_str());
1595 }
1596 else
1597 {
1598 MOS_OS_ASSERTMESSAGE("Can't open %s for USER_FEATURE_FILE_NEXT!!!", tmpFileNext.c_str());
1599 }
1600 }
1601
1602 // Get user feature file report from config file or env, instead of default.
1603 static std::string tmpFileReport = MosParseEnvFromConfig("GFX_FEATURE_FILE_REPORT");
1604
1605 if (!tmpFileReport.empty())
1606 {
1607 MosUtilitiesSpecificNext::m_szUserFeatureFileReport = tmpFileReport;
1608 MOS_OS_NORMALMESSAGE("using %s for USER_FEATURE_FILE_REPORT", MosUtilitiesSpecificNext::m_szUserFeatureFileReport.c_str());
1609 }
1610 #endif
1611
1612 std::ifstream regStream;
1613 try
1614 {
1615 regStream.open(MosUtilitiesSpecificNext::m_szUserFeatureFileNext.c_str());
1616 if (regStream.good())
1617 {
1618 std::string id = "";
1619 while(!regStream.eof())
1620 {
1621 std::string line = "";
1622 std::getline(regStream, line);
1623 auto endIndex = line.find("\r");
1624 if(endIndex != std::string::npos)
1625 {
1626 line = line.substr(0, endIndex);
1627 }
1628 if (std::string::npos != line.find(USER_SETTING_CONFIG_PATH))
1629 {
1630 id = USER_SETTING_CONFIG_PATH;
1631 }
1632 else if (std::string::npos != line.find(USER_SETTING_REPORT_PATH))
1633 {
1634 id = USER_SETTING_REPORT_PATH;
1635 }
1636 else if (line.find("]") != std::string::npos)
1637 {
1638 auto mkPos = line.find_last_of("]");
1639 id = line.substr(0, mkPos+1);
1640 }
1641 else
1642 {
1643 if (id == USER_SETTING_REPORT_PATH)
1644 {
1645 continue;
1646 }
1647
1648 std::size_t pos = line.find("=");
1649 if (std::string::npos != pos && !id.empty())
1650 {
1651 std::string name = line.substr(0,pos);
1652 std::string value = line.substr(pos+1);
1653 if (name.size() > 0 && value.size() > 0)
1654 {
1655 auto &keys = regBufferMap[id];
1656 keys[name] = value;
1657 }
1658 }
1659 }
1660 }
1661
1662 }
1663 }
1664 catch(const std::exception &e)
1665 {
1666 status = MOS_STATUS_FILE_OPEN_FAILED;
1667 }
1668
1669 regStream.close();
1670
1671 return status;
1672 }
1673
1674 MOS_STATUS MosUtilities::MosUninitializeReg(RegBufferMap &regBufferMap)
1675 {
1676 MOS_STATUS status = MOS_STATUS_SUCCESS;
1677
1678 if (regBufferMap.size() == 0)
1679 {
1680 return MOS_STATUS_SUCCESS;
1681 }
1682
1683 auto iter = regBufferMap.find(USER_SETTING_REPORT_PATH);
1684 // No need to write the user setting files if no session [report].
1685 // The session [config] is read only.
1686 if(iter == regBufferMap.end() || iter->second.size() == 0)
1687 {
1688 MOS_OS_NORMALMESSAGE("no report session");
1689 return MOS_STATUS_SUCCESS;
1690 }
1691
1692 std::ofstream regStream;
1693 try
1694 {
1695 // For release version: writes to the file if it exists,
1696 // skips if it does not exist
1697 // For other version: always writes to the file
1698 #if(_RELEASE)
1699 std::ifstream regFile(MosUtilitiesSpecificNext::m_szUserFeatureFileNext.c_str());
1700 if (regFile.good())
1701 {
1702 regFile.close();
1703 regStream.open(MosUtilitiesSpecificNext::m_szUserFeatureFileReport.c_str(), std::ios::out | std::ios::trunc);
1704 }
1705 else
1706 {
1707 regFile.close();
1708 return status;
1709 }
1710 #else
1711 regStream.open(MosUtilitiesSpecificNext::m_szUserFeatureFileReport.c_str(), std::ios::out | std::ios::trunc);
1712 #endif
1713 if (regStream.good())
1714 {
1715 regStream << iter->first << "\n";
1716
1717 auto &keys = iter->second;
1718 for (auto key: keys)
1719 {
1720 auto name = key.first;
1721 regStream << key.first << "=" << key.second << "\n";
1722 }
1723
1724 keys.clear();
1725 regStream << std::endl;
1726 regBufferMap.clear();
1727 regStream.flush();
1728 }
1729 }
1730 catch(const std::exception &e)
1731 {
1732 status = MOS_STATUS_FILE_WRITE_FAILED;
1733 }
1734
1735 regStream.close();
1736 return status;
1737 }
1738
1739 MOS_STATUS MosUtilities::MosCreateRegKey(
1740 UFKEY_NEXT keyHandle,
1741 const std::string &subKey,
1742 uint32_t samDesired,
1743 PUFKEY_NEXT key,
1744 RegBufferMap &regBufferMap)
1745 {
1746 MOS_UNUSED(keyHandle);
1747 MOS_UNUSED(samDesired);
1748 MOS_OS_CHK_NULL_RETURN(key);
1749 auto ret = regBufferMap.find(subKey);
1750
1751 if (ret == regBufferMap.end())
1752 {
1753 regBufferMap[subKey] = {};
1754 }
1755
1756 *key = subKey;
1757 return MOS_STATUS_SUCCESS;
1758 }
1759
1760 MOS_STATUS MosUtilities::MosOpenRegKey(
1761 UFKEY_NEXT keyHandle,
1762 const std::string &subKey,
1763 uint32_t samDesired,
1764 PUFKEY_NEXT key,
1765 RegBufferMap &regBufferMap)
1766 {
1767 std::string tempSubKey = subKey;
1768
1769 if (subKey.find_first_of("\\") != std::string::npos)
1770 {
1771 tempSubKey = subKey.substr(1);
1772 }
1773
1774 if (tempSubKey.find_first_of("[") == std::string::npos)
1775 {
1776 tempSubKey = "[" + tempSubKey + "]";
1777 }
1778 return MosCreateRegKey(keyHandle, tempSubKey, samDesired, key, regBufferMap);
1779 }
1780
1781 MOS_STATUS MosUtilities::MosCloseRegKey(
1782 UFKEY_NEXT keyHandle)
1783 {
1784 MOS_UNUSED(keyHandle);
1785 return MOS_STATUS_SUCCESS;
1786 }
1787
1788 MOS_STATUS MosUtilities::MosReadEnvVariable(
1789 const std::string &envName,
1790 MOS_USER_FEATURE_VALUE_TYPE defaultType,
1791 MediaUserSetting::Value &data)
1792 {
1793 char *retVal = getenv(envName.c_str());
1794 if (retVal != nullptr)
1795 {
1796 std::string strData = retVal;
1797 auto status = StrToMediaUserSettingValue(strData, defaultType, data);
1798 return status;
1799 }
1800
1801 return MOS_STATUS_INVALID_PARAMETER;
1802 }
1803
1804 bool MosUtilities::MosEnvVariableEqual(
1805 const std::string envName,
1806 const std::string targetVal)
1807 {
1808 char *retVal = getenv(envName.c_str());
1809 bool res = false;
1810 if (retVal != nullptr)
1811 {
1812 res = strcmp(retVal, targetVal.c_str()) ? false : true;
1813 }
1814 return res;
1815 }
1816
1817 MOS_STATUS MosUtilities::MosGetRegValue(
1818 UFKEY_NEXT keyHandle,
1819 const std::string &valueName,
1820 MOS_USER_FEATURE_VALUE_TYPE defaultType,
1821 MediaUserSetting::Value &data,
1822 RegBufferMap &regBufferMap)
1823 {
1824 MOS_STATUS status = MOS_STATUS_SUCCESS;
1825
1826 if (regBufferMap.end() == regBufferMap.find(keyHandle))
1827 {
1828 return MOS_STATUS_USER_FEATURE_KEY_OPEN_FAILED;
1829 }
1830
1831 try
1832 {
1833 auto keys = regBufferMap[keyHandle];
1834 auto it = keys.find(valueName);
1835 if (it == keys.end())
1836 {
1837 return MOS_STATUS_USER_FEATURE_KEY_OPEN_FAILED;
1838 }
1839 status = MosUtilities::StrToMediaUserSettingValue(it->second, defaultType, data);
1840 }
1841 catch(const std::exception &e)
1842 {
1843 status = MOS_STATUS_INVALID_PARAMETER;
1844 }
1845
1846 return status;
1847 }
1848
1849 MOS_STATUS MosUtilities::MosPrintCPUAllocateMemory(int32_t event_id, int32_t level, int32_t param_id_1, int64_t value_1, int32_t param_id_2, int64_t value_2,
1850 const char *funName, const char *fileName, int32_t line)
1851 {
1852 #if (_RELEASE_INTERNAL)
1853 if (MOS_IS_MEMORY_FOOT_PRINT_ENABLED())
1854 {
1855 MosAtomicIncrement(m_mosMemAllocIndex);
1856 MT_LOG3(event_id, level, param_id_1, value_1, MT_MEMORY_INDEX, *MosUtilities::m_mosMemAllocIndex, param_id_2, value_2);
1857 }
1858
1859 #endif
1860 return MOS_STATUS_SUCCESS;
1861 }
1862
1863 MOS_STATUS MosUtilities::MosPrintCPUDestroyMemory(int32_t event_id, int32_t level, int32_t param_id_1, int64_t value_1,
1864 const char *funName, const char *fileName, int32_t line)
1865 {
1866 #if (_RELEASE_INTERNAL)
1867 if (MOS_IS_MEMORY_FOOT_PRINT_ENABLED())
1868 {
1869 MosAtomicDecrement(m_mosMemAllocIndex);
1870 MT_LOG2(event_id, level, param_id_1, value_1, MT_MEMORY_INDEX, *MosUtilities::m_mosMemAllocIndex);
1871 }
1872 #endif
1873 return MOS_STATUS_SUCCESS;
1874 }
1875
1876 MOS_STATUS MosUtilities::MosSetRegValue(
1877 UFKEY_NEXT keyHandle,
1878 const std::string &valueName,
1879 const MediaUserSetting::Value &data,
1880 RegBufferMap &regBufferMap)
1881 {
1882 if (regBufferMap.end() == regBufferMap.find(keyHandle))
1883 {
1884 return MOS_STATUS_INVALID_PARAMETER;
1885 }
1886
1887 MOS_STATUS status = MOS_STATUS_SUCCESS;
1888 try
1889 {
1890 auto &keys = regBufferMap[keyHandle];
1891
1892 keys[valueName] = data.ConstString();
1893 }
1894 catch(const std::exception &e)
1895 {
1896 status = MOS_STATUS_INVALID_PARAMETER;
1897 }
1898
1899 return status;
1900 }
1901
1902 HANDLE MosUtilities::MosCreateEventEx(
1903 void *lpEventAttributes,
1904 char *lpName,
1905 uint32_t dwFlags)
1906 {
1907 int32_t semid;
1908 key_t key;
1909 union semun
1910 {
1911 int32_t val;
1912 struct semid_ds *Buf;
1913 unsigned short *array;
1914 } semctl_arg;
1915
1916 semid = 0;
1917
1918 //Generate a unique key, U can also supply a value instead
1919 key = ftok(MosUtilitiesSpecificNext::m_szUserFeatureFile, 1);
1920 semid = semget(key, 1, 0666 | IPC_CREAT );
1921 semctl_arg.val = 0; //Setting semval to 0
1922 semctl(semid, 0, SETVAL, semctl_arg);
1923
1924 HANDLE ret = reinterpret_cast<HANDLE>(semid);
1925
1926 return ret;
1927 }
1928
1929 int32_t MosUtilities::MosUserFeatureWaitForSingleObject(
1930 PTP_WAIT* phNewWaitObject,
1931 HANDLE hObject,
1932 void *Callback,
1933 void *Context)
1934 {
1935 int32_t iRet;
1936 int32_t semid;
1937 struct sembuf operation[1];
1938 pid_t pid;
1939 MOS_UserFeatureCallback pCallback;
1940 LARGE_INTEGER largeInteger;
1941
1942 pCallback = (MOS_UserFeatureCallback)Callback;
1943
1944 iRet = 0;
1945
1946 largeInteger.QuadPart = (int64_t)hObject;
1947
1948 semid = largeInteger.u.LowPart;
1949
1950 if ((pid=fork()) == -1)
1951 {
1952 printf("error\n");
1953 }
1954 else if(pid == 0)
1955 {
1956 while(1)
1957 {
1958 operation[0].sem_op = -1;
1959 operation[0].sem_num = 0;
1960 //now waiting
1961 semop(semid, operation, 1);
1962 pCallback(Context, 0);
1963 }
1964 }
1965 else
1966 {
1967 iRet = pid;
1968 }
1969
1970 *phNewWaitObject = reinterpret_cast<PTP_WAIT>(iRet);
1971
1972 return (iRet != 0);
1973 }
1974
1975 int32_t MosUtilities::MosUnregisterWaitEx(PTP_WAIT hWaitHandle)
1976 {
1977 int32_t iPid;
1978 LARGE_INTEGER largeInteger;
1979
1980 largeInteger.QuadPart = (int64_t)hWaitHandle;
1981
1982 iPid = largeInteger.u.LowPart;
1983 kill(iPid, SIGKILL);
1984 return true;
1985 }
1986
1987 #if (_DEBUG || _RELEASE_INTERNAL)
1988 MOS_STATUS MosUtilities::MosGetApoMosEnabledUserFeatureFile()
1989 {
1990 // Get use user feature file from env, instead of default.
1991 FILE * fp = nullptr;
1992 static char *tmpFile = getenv("GFX_FEATURE_FILE");
1993
1994 if (tmpFile != nullptr)
1995 {
1996 if ((fp = fopen(tmpFile, "r")) != nullptr)
1997 {
1998 if (MosUtilitiesSpecificNext::m_szUserFeatureFile != tmpFile)
1999 MosUtilitiesSpecificNext::m_szUserFeatureFile = tmpFile;
2000 fclose(fp);
2001 MOS_OS_NORMALMESSAGE("using %s for USER_FEATURE_FILE", MosUtilitiesSpecificNext::m_szUserFeatureFile);
2002 }
2003 else
2004 {
2005 MOS_OS_ASSERTMESSAGE("Can't open %s for USER_FEATURE_FILE!!!", tmpFile);
2006 return MOS_STATUS_FILE_NOT_FOUND;
2007 }
2008 }
2009 return MOS_STATUS_SUCCESS;
2010 }
2011 #endif
2012
2013 MOS_STATUS MosUtilities::MosReadMediaSoloEnabledUserFeature(bool &mediasoloEnabled)
2014 {
2015 MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
2016
2017 #if MOS_MEDIASOLO_SUPPORTED
2018
2019 void * UFKey = nullptr;
2020 uint32_t dwUFSize = 0;
2021 uint32_t data = 0;
2022
2023 #if (_DEBUG || _RELEASE_INTERNAL)
2024 eStatus = MosGetApoMosEnabledUserFeatureFile();
2025 if (eStatus != MOS_STATUS_SUCCESS)
2026 {
2027 MOS_OS_NORMALMESSAGE("Failed to get user feature file, error status %d.", eStatus);
2028 return eStatus;
2029 }
2030 #endif
2031
2032 eStatus = MosUserFeatureOpen(
2033 MOS_USER_FEATURE_TYPE_USER,
2034 __MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
2035 KEY_READ,
2036 &UFKey,
2037 nullptr);
2038
2039 if (eStatus != MOS_STATUS_SUCCESS)
2040 {
2041 MOS_OS_NORMALMESSAGE("Failed to open user feature key , error status %d.", eStatus);
2042 return eStatus;
2043 }
2044
2045 eStatus = MosUserFeatureGetValue(
2046 UFKey,
2047 nullptr,
2048 __MEDIA_USER_FEATURE_VALUE_MEDIASOLO_ENABLE,
2049 RRF_RT_UF_DWORD,
2050 nullptr,
2051 &data,
2052 &dwUFSize);
2053
2054 if (eStatus == MOS_STATUS_SUCCESS && data > 0)
2055 {
2056 mediasoloEnabled = true;
2057 }
2058 MosUserFeatureCloseKey(UFKey);
2059
2060 #endif
2061 return eStatus;
2062 }
2063
2064 MOS_STATUS MosUtilities::MosReadApoDdiEnabledUserFeature(uint32_t &userfeatureValue, char *path, MediaUserSettingSharedPtr userSettingPtr)
2065 {
2066 MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
2067 MOS_UNUSED(path);
2068
2069 uint32_t enableApoDdi = 0;
2070 eStatus = ReadUserSetting(
2071 userSettingPtr,
2072 enableApoDdi,
2073 "ApoDdiEnable",
2074 MediaUserSetting::Group::Device);
2075
2076 if (eStatus != MOS_STATUS_SUCCESS)
2077 {
2078 // It could be there is no this use feature key.
2079 MOS_OS_NORMALMESSAGE("Failed to read ApoDdiEnable user feature key value, error status %d", eStatus);
2080 }
2081 userfeatureValue = enableApoDdi ? true : false;
2082 return eStatus;
2083 }
2084
2085 MOS_STATUS MosUtilities::MosReadApoMosEnabledUserFeature(uint32_t &userfeatureValue, char *path, MediaUserSettingSharedPtr userSettingPtr)
2086 {
2087 MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
2088 MOS_USER_FEATURE_VALUE_DATA userFeatureData = {};
2089 MOS_UNUSED(path);
2090
2091
2092 uint32_t enableApoMos = 0;
2093 eStatus = ReadUserSetting(
2094 userSettingPtr,
2095 enableApoMos,
2096 "ApoMosEnable",
2097 MediaUserSetting::Group::Device);
2098
2099 if (eStatus != MOS_STATUS_SUCCESS)
2100 {
2101 // It could be there is no this use feature key.
2102 MOS_OS_NORMALMESSAGE("Failed to read ApoMosEnable user feature key value, error status %d", eStatus);
2103 }
2104 userfeatureValue = enableApoMos ? true : false;
2105 return eStatus;
2106 }
2107
2108 MOS_STATUS MosUtilities::MosUserFeatureParsePath(
2109 PMOS_USER_FEATURE_INTERFACE pOsUserFeatureInterface,
2110 char * const pInputPath,
2111 PMOS_USER_FEATURE_TYPE pUserFeatureType,
2112 char **ppSubPath)
2113 {
2114 char *pValue;
2115 MOS_USER_FEATURE_TYPE UserFeatureType;
2116 size_t uUFKeyLen;
2117 size_t uHKeyLen;
2118 size_t uValLen;
2119 size_t uSepLen;
2120 MOS_UNUSED(pOsUserFeatureInterface);
2121
2122 //-------------------------------------------
2123 // the UserFeature interface is not currently an actual interface, just a collection
2124 // of functions, so pOsUserFeatureInterface will always be nullptr until this changes
2125 //MOS_OS_ASSERT(pOsUserFeatureInterface);
2126 MOS_OS_ASSERT(pInputPath);
2127 MOS_OS_ASSERT(strlen(pInputPath) > 0);
2128 MOS_OS_ASSERT(pUserFeatureType);
2129 MOS_OS_ASSERT(ppSubPath);
2130 //-------------------------------------------
2131
2132 pValue = nullptr;
2133
2134 pValue = strstr(pInputPath, MOS_UF_SEPARATOR);
2135
2136 if (!pValue)
2137 {
2138 MOS_OS_ASSERTMESSAGE("Invalid user feature key %s.", pInputPath);
2139 return MOS_STATUS_INVALID_PARAMETER;
2140 }
2141
2142 uUFKeyLen = strlen(pInputPath);
2143 uValLen = strlen(pValue);
2144 uSepLen = strlen(MOS_UF_SEPARATOR);
2145 uHKeyLen = uUFKeyLen - uValLen;
2146
2147 if (uHKeyLen == 0)
2148 {
2149 MOS_OS_ASSERTMESSAGE("Invalid user feature key %s. Path separator in the begining.", pInputPath);
2150 return MOS_STATUS_INVALID_PARAMETER;
2151 }
2152
2153 if (uValLen <= uSepLen)
2154 {
2155 MOS_OS_ASSERTMESSAGE("Invalid user feature key %s. No value after path separator.", pInputPath);
2156 return MOS_STATUS_INVALID_PARAMETER;
2157 }
2158
2159 if ((uHKeyLen == strlen(MOS_UFKEY_EXT)) &&
2160 (strncmp(pInputPath, MOS_UFKEY_EXT, uHKeyLen) == 0))
2161 {
2162 UserFeatureType = MOS_USER_FEATURE_TYPE_SYSTEM;
2163 }
2164 else if ((uHKeyLen == strlen(MOS_UFKEY_INT)) &&
2165 (strncmp(pInputPath, MOS_UFKEY_INT, uHKeyLen) == 0))
2166 {
2167 UserFeatureType = MOS_USER_FEATURE_TYPE_USER;
2168 }
2169 else
2170 {
2171 MOS_OS_ASSERTMESSAGE("Invalid user feature key %s. Expected %s or %s.", pInputPath, MOS_UFKEY_EXT, MOS_UFKEY_INT);
2172 return MOS_STATUS_INVALID_PARAMETER;
2173 }
2174
2175 pValue = pValue + uSepLen;
2176
2177 *pUserFeatureType = UserFeatureType;
2178 *ppSubPath = pValue;
2179
2180 return MOS_STATUS_SUCCESS;
2181 }
2182
2183 uint32_t MosUtilities::MosGetLogicalCoreNumber()
2184 {
2185 return sysconf(_SC_NPROCESSORS_CONF);
2186 }
2187
2188 MOS_THREADHANDLE MosUtilities::MosCreateThread(
2189 void *ThreadFunction,
2190 void *ThreadData)
2191 {
2192 MOS_THREADHANDLE Thread;
2193
2194 if (0 != pthread_create(&Thread, nullptr, (void *(*)(void *))ThreadFunction, ThreadData))
2195 {
2196 Thread = 0;
2197 MOS_OS_ASSERTMESSAGE("Create thread failed.");
2198 }
2199
2200 return Thread;
2201 }
2202
2203 uint32_t MosUtilities::MosGetThreadId(
2204 MOS_THREADHANDLE hThread)
2205 {
2206 MOS_UNUSED(hThread);
2207 return 0;
2208 }
2209
2210 uint32_t MosUtilities::MosGetCurrentThreadId()
2211 {
2212 return (uint32_t)pthread_self();
2213 }
2214
2215 MOS_STATUS MosUtilities::MosWaitThread(
2216 MOS_THREADHANDLE hThread)
2217 {
2218 MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
2219
2220 if (hThread == 0)
2221 {
2222 MOS_OS_ASSERTMESSAGE("MOS wait thread failed, invalid thread handle.");
2223 eStatus = MOS_STATUS_INVALID_PARAMETER;
2224 }
2225 else if (0 != pthread_join(hThread, nullptr))
2226 {
2227 MOS_OS_ASSERTMESSAGE("Failed to join thread.");
2228 eStatus = MOS_STATUS_UNKNOWN;
2229 }
2230
2231 return eStatus;
2232 }
2233
2234 PMOS_MUTEX MosUtilities::MosCreateMutex(uint32_t spinCount)
2235 {
2236 PMOS_MUTEX pMutex;
2237 MOS_UNUSED(spinCount);
2238 pMutex = (PMOS_MUTEX)MOS_AllocMemory(sizeof(*pMutex));
2239 if (pMutex != nullptr)
2240 {
2241 if (pthread_mutex_init(pMutex, nullptr))
2242 {
2243 MOS_FreeMemory(pMutex);
2244 pMutex = nullptr;
2245 }
2246 }
2247
2248 return pMutex;
2249 }
2250
2251 MOS_STATUS MosUtilities::MosDestroyMutex(PMOS_MUTEX &pMutex)
2252 {
2253 MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
2254
2255 if (pMutex)
2256 {
2257 if (pthread_mutex_destroy(pMutex))
2258 {
2259 eStatus = MOS_STATUS_UNKNOWN;
2260 }
2261 MOS_FreeMemAndSetNull(pMutex);
2262 }
2263
2264 return eStatus;
2265 }
2266
2267 MOS_STATUS MosUtilities::MosLockMutex(PMOS_MUTEX pMutex)
2268 {
2269 MOS_OS_CHK_NULL_RETURN(pMutex);
2270
2271 MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
2272
2273 if (pthread_mutex_lock(pMutex))
2274 {
2275 eStatus = MOS_STATUS_UNKNOWN;
2276 }
2277
2278 return eStatus;
2279 }
2280
2281 MOS_STATUS MosUtilities::MosUnlockMutex(PMOS_MUTEX pMutex)
2282 {
2283 MOS_OS_CHK_NULL_RETURN(pMutex);
2284
2285 MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
2286
2287 if (pthread_mutex_unlock(pMutex))
2288 {
2289 eStatus = MOS_STATUS_UNKNOWN;
2290 }
2291
2292 return eStatus;
2293 }
2294
2295 PMOS_SEMAPHORE MosUtilities::MosCreateSemaphore(
2296 uint32_t uiInitialCount,
2297 uint32_t uiMaximumCount)
2298 {
2299 PMOS_SEMAPHORE pSemaphore = nullptr;
2300 MOS_UNUSED(uiMaximumCount);
2301
2302 pSemaphore = (PMOS_SEMAPHORE)MOS_AllocMemory(sizeof(*pSemaphore));
2303 if (!pSemaphore)
2304 return nullptr;
2305 if (sem_init(pSemaphore, 0, uiInitialCount))
2306 {
2307 MOS_SafeFreeMemory(pSemaphore);
2308 pSemaphore = nullptr;
2309 }
2310
2311 return pSemaphore;
2312 }
2313
2314 MOS_STATUS MosUtilities::MosDestroySemaphore(
2315 PMOS_SEMAPHORE &pSemaphore)
2316 {
2317 MOS_FreeMemAndSetNull(pSemaphore);
2318 return MOS_STATUS_SUCCESS;
2319 }
2320
2321 MOS_STATUS MosUtilities::MosWaitSemaphore(
2322 PMOS_SEMAPHORE pSemaphore,
2323 uint32_t uiMilliseconds)
2324 {
2325 MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
2326
2327 if (uiMilliseconds == INFINITE)
2328 {
2329 if (sem_wait(pSemaphore))
2330 {
2331 eStatus = MOS_STATUS_UNKNOWN;
2332 }
2333 }
2334 else
2335 {
2336 struct timespec time = {
2337 (int32_t)uiMilliseconds / 1000000,
2338 ((int32_t)uiMilliseconds % 1000000) * 1000};
2339
2340 if (sem_timedwait(pSemaphore, &time))
2341 {
2342 eStatus = MOS_STATUS_UNKNOWN;
2343 }
2344 }
2345
2346 return eStatus;
2347 }
2348
2349 MOS_STATUS MosUtilities::MosPostSemaphore(
2350 PMOS_SEMAPHORE pSemaphore,
2351 uint32_t uiPostCount)
2352 {
2353 MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
2354
2355 if (uiPostCount > 0)
2356 {
2357 while (uiPostCount--)
2358 {
2359 if (sem_post(pSemaphore))
2360 {
2361 eStatus = MOS_STATUS_UNKNOWN;
2362 break;
2363 }
2364 }
2365 }
2366 else
2367 {
2368 eStatus = MOS_STATUS_UNKNOWN;
2369 }
2370
2371 return eStatus;
2372 }
2373
2374 uint32_t MosUtilities::MosWaitForSingleObject(
2375 void *pObject,
2376 uint32_t uiMilliseconds)
2377 {
2378 uint32_t WaitSignal = 0;
2379 MOS_UNUSED(pObject);
2380 MOS_UNUSED(uiMilliseconds);
2381
2382 return WaitSignal;
2383 }
2384
2385 uint32_t MosUtilities::MosWaitForMultipleObjects(
2386 uint32_t uiThreadCount,
2387 void **ppObjects,
2388 uint32_t bWaitAll,
2389 uint32_t uiMilliseconds)
2390 {
2391 MOS_UNUSED(uiThreadCount);
2392 MOS_UNUSED(ppObjects);
2393 MOS_UNUSED(bWaitAll);
2394 MOS_UNUSED(uiMilliseconds);
2395 return 0;
2396 }
2397
2398 int32_t MosUtilities::MosAtomicIncrement(
2399 int32_t *pValue)
2400 {
2401 if (pValue != nullptr)
2402 {
2403 return __sync_add_and_fetch(pValue, 1);
2404 }
2405 return 0;
2406 }
2407
2408 int32_t MosUtilities::MosAtomicDecrement(
2409 int32_t *pValue)
2410 {
2411 if (pValue != nullptr)
2412 {
2413 return __sync_sub_and_fetch(pValue, 1);
2414 }
2415 return 0;
2416 }
2417
2418 #ifndef WDDM_LINUX
2419 VAStatus MosUtilities::MosStatusToOsResult(
2420 MOS_STATUS eStatus)
2421 {
2422 switch (eStatus)
2423 {
2424 case MOS_STATUS_SUCCESS: return VA_STATUS_SUCCESS;
2425 case MOS_STATUS_NO_SPACE: return VA_STATUS_ERROR_ALLOCATION_FAILED;
2426 case MOS_STATUS_INVALID_PARAMETER: return VA_STATUS_ERROR_INVALID_PARAMETER;
2427 case MOS_STATUS_INVALID_HANDLE: return VA_STATUS_ERROR_INVALID_BUFFER;
2428 case MOS_STATUS_NULL_POINTER: return VA_STATUS_ERROR_INVALID_CONTEXT;
2429 default: return VA_STATUS_ERROR_OPERATION_FAILED;
2430 }
2431
2432 return VA_STATUS_ERROR_OPERATION_FAILED;
2433 }
2434
2435 MOS_STATUS MosUtilities::OsResultToMOSStatus(
2436 VAStatus eResult)
2437 {
2438 switch (eResult)
2439 {
2440 case VA_STATUS_SUCCESS: return MOS_STATUS_SUCCESS;
2441 case VA_STATUS_ERROR_ALLOCATION_FAILED: return MOS_STATUS_NO_SPACE;
2442 case VA_STATUS_ERROR_INVALID_PARAMETER: return MOS_STATUS_INVALID_PARAMETER;
2443 case VA_STATUS_ERROR_INVALID_BUFFER: return MOS_STATUS_INVALID_HANDLE;
2444 case VA_STATUS_ERROR_INVALID_CONTEXT: return MOS_STATUS_NULL_POINTER;
2445 default: return MOS_STATUS_UNKNOWN;
2446 }
2447
2448 return MOS_STATUS_UNKNOWN;
2449 }
2450 #else
2451 MOS_OSRESULT MosUtilities::MosStatusToOsResult(
2452 MOS_STATUS eStatus)
2453 {
2454 if (eStatus < MOS_STATUS_SUCCESS)
2455 {
2456 // It is in fact an HRESULT already, do nothing
2457 return (MOS_OSRESULT)eStatus;
2458 }
2459
2460 switch (eStatus)
2461 {
2462 case MOS_STATUS_SUCCESS:
2463 return MOS_OSSOK;
2464 case MOS_STATUS_NO_SPACE:
2465 return MOS_OSEOUTOFMEMORY;
2466 case MOS_STATUS_INVALID_PARAMETER:
2467 return MOS_OSEINVALIDARG;
2468 case MOS_STATUS_INVALID_HANDLE:
2469 return MOS_OSEHANDLE;
2470 case MOS_STATUS_NULL_POINTER:
2471 return MOS_OSEPOINTER;
2472 case MOS_STATUS_UNIMPLEMENTED:
2473 return MOS_OSENOTIMPL;
2474 default:
2475 return MOS_OSEFAIL;
2476 }
2477
2478 return MOS_OSEFAIL;
2479 }
2480
2481 MOS_STATUS MosUtilities::OsResultToMOSStatus(
2482 MOS_OSRESULT eResult)
2483 {
2484 switch (eResult)
2485 {
2486 case MOS_OSSOK:
2487 return MOS_STATUS_SUCCESS;
2488 case MOS_OSEOUTOFMEMORY:
2489 return MOS_STATUS_NO_SPACE;
2490 case MOS_OSEINVALIDARG:
2491 return MOS_STATUS_INVALID_PARAMETER;
2492 case MOS_OSEHANDLE:
2493 return MOS_STATUS_INVALID_HANDLE;
2494 case MOS_OSEPOINTER:
2495 return MOS_STATUS_NULL_POINTER;
2496 default:
2497 return MOS_STATUS_UNKNOWN;
2498 }
2499
2500 return MOS_STATUS_UNKNOWN;
2501 }
2502 #endif
2503 MOS_STATUS MosUtilities::MosGetLocalTime(
2504 struct tm* Tm)
2505 {
2506 MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
2507 struct tm *pTm;
2508 time_t lTime = time(nullptr);
2509 pTm = localtime(&lTime);
2510 if(pTm == nullptr)
2511 {
2512 MOS_OS_ASSERTMESSAGE("Failed to get localtime.");
2513 eStatus = MOS_STATUS_UNKNOWN;
2514 return eStatus;
2515 }
2516
2517 eStatus = MosSecureMemcpy(Tm, sizeof(struct tm), pTm, sizeof(struct tm));
2518 return eStatus;
2519 }
2520
2521 void MosUtilities::MosTraceEventInit()
2522 {
2523 std::string val = MosParseEnvFromConfig("GFX_MEDIA_TRACE");
2524 if (!val.empty())
2525 {
2526 MosUtilitiesSpecificNext::m_filterEnv = strtoll(val.c_str(), nullptr, 0);
2527 std::string valLevel = MosParseEnvFromConfig("GFX_MEDIA_TRACE_LEVEL");
2528 if (!valLevel.empty())
2529 {
2530 MosUtilitiesSpecificNext::m_levelEnv = static_cast<uint32_t>(strtoll(valLevel.c_str(), nullptr, 0));
2531 }
2532 m_mosTraceEnable = true;
2533 m_mosTraceFilter = { &MosUtilitiesSpecificNext::m_filterEnv, 1};
2534 m_mosTraceLevel = reinterpret_cast<uint8_t *>(&MosUtilitiesSpecificNext::m_levelEnv);
2535 }
2536 else
2537 {
2538 int fd = open(TRACE_SETTING_PATH, O_RDONLY);
2539 if (fd < 0)
2540 {
2541 return;
2542 }
2543 void *addr = mmap(NULL, TRACE_SETTING_SIZE, PROT_READ, MAP_SHARED, fd, 0);
2544 close(fd); // close first, map addr still valid after close
2545 if (addr == MAP_FAILED)
2546 {
2547 return;
2548 }
2549 m_mosTraceControlData = reinterpret_cast<const MtControlData *>(addr);
2550
2551 m_mosTraceEnable = &m_mosTraceControlData->enable;
2552 m_mosTraceFilter = {
2553 m_mosTraceControlData->filter,
2554 sizeof(m_mosTraceControlData->filter) / sizeof(uint64_t)};
2555 m_mosTraceLevel = &m_mosTraceControlData->level;
2556 }
2557
2558 // close first, if already opened.
2559 if (MosUtilitiesSpecificNext::m_mosTraceFd >= 0)
2560 {
2561 close(MosUtilitiesSpecificNext::m_mosTraceFd);
2562 MosUtilitiesSpecificNext::m_mosTraceFd = -1;
2563 }
2564 MosUtilitiesSpecificNext::m_mosTraceFd = open(MosUtilitiesSpecificNext::m_mosTracePath, O_WRONLY);
2565 return;
2566 }
2567
2568 void MosUtilities::MosTraceEventClose()
2569 {
2570 m_mosTraceEnable.Reset();
2571 m_mosTraceFilter.Reset();
2572 m_mosTraceLevel.Reset();
2573 if (m_mosTraceControlData)
2574 {
2575 munmap((void *)m_mosTraceControlData, TRACE_SETTING_SIZE);
2576 m_mosTraceControlData = nullptr;
2577 }
2578 if (MosUtilitiesSpecificNext::m_mosTraceFd >= 0)
2579 {
2580 close(MosUtilitiesSpecificNext::m_mosTraceFd);
2581 MosUtilitiesSpecificNext::m_mosTraceFd = -1;
2582 }
2583 MosUtilitiesSpecificNext::m_filterEnv = 0;
2584 MosUtilitiesSpecificNext::m_levelEnv = {};
2585 return;
2586 }
2587
2588 void MosUtilities::MosTraceSetupInfo(uint32_t DrvVer, uint32_t PlatFamily, uint32_t RenderFamily, uint32_t DeviceID)
2589 {
2590 // not implemented
2591 }
2592
2593 void MosUtilities::MosTraceEvent(
2594 uint16_t usId,
2595 uint8_t ucType,
2596 const void *pArg1,
2597 uint32_t dwSize1,
2598 const void *pArg2,
2599 uint32_t dwSize2)
2600 {
2601 if (!m_mosTraceEnable)
2602 {
2603 return; // skip if trace not enabled from share memory
2604 }
2605
2606 if (MosUtilitiesSpecificNext::m_mosTraceFd >= 0 &&
2607 TRACE_EVENT_MAX_SIZE > dwSize1 + dwSize2 + TRACE_EVENT_HEADER_SIZE)
2608 {
2609 uint8_t traceBuf[256];
2610 uint8_t *pTraceBuf = traceBuf;
2611
2612 // special handling for media runtime log, filter by component
2613 if (usId == EVENT_MEDIA_LOG && pArg1 != nullptr && dwSize1 >= 2*sizeof(int32_t))
2614 {
2615 int32_t comp = (*(int32_t*)pArg1) >> 24;
2616 int32_t level = *((int32_t*)pArg1 + 1);
2617
2618 if (!m_mosTraceFilter(TR_KEY_MOSMSG_ALL) || !m_mosTraceFilter(MEDIA_EVENT_FILTER_KEYID(comp + 16)))
2619 {
2620 // keyword not set for this component, skip it
2621 return;
2622 }
2623 }
2624
2625 if (dwSize1 + dwSize2 + TRACE_EVENT_HEADER_SIZE > sizeof(traceBuf))
2626 {
2627 pTraceBuf = (uint8_t *)MOS_AllocAndZeroMemory(TRACE_EVENT_MAX_SIZE);
2628 }
2629
2630 if (pTraceBuf)
2631 {
2632 // trace header
2633 uint32_t *header = (uint32_t *)pTraceBuf;
2634 uint32_t nLen = TRACE_EVENT_HEADER_SIZE;
2635
2636 header[0] = 0x494D5445; // IMTE (IntelMediaTraceEvent) as ftrace raw marker tag
2637 header[1] = (usId << 16) | (dwSize1 + dwSize2);
2638 header[2] = ucType;
2639
2640 if (pArg1 && dwSize1 > 0)
2641 {
2642 MOS_SecureMemcpy(pTraceBuf+nLen, dwSize1, pArg1, dwSize1);
2643 nLen += dwSize1;
2644 }
2645 if (pArg2 && dwSize2 > 0)
2646 {
2647 MOS_SecureMemcpy(pTraceBuf+nLen, dwSize2, pArg2, dwSize2);
2648 nLen += dwSize2;
2649 }
2650 size_t writeSize = write(MosUtilitiesSpecificNext::m_mosTraceFd, pTraceBuf, nLen);
2651 if (traceBuf != pTraceBuf)
2652 {
2653 MOS_FreeMemory(pTraceBuf);
2654 }
2655 }
2656 #if Backtrace_FOUND
2657 if (m_mosTraceFilter(TR_KEY_CALL_STACK))
2658 {
2659 // reserve space for header and stack size field.
2660 // max 32-2=30 layers call stack in 64bit driver.
2661 uint32_t nLen = 4*sizeof(uint32_t);
2662 void **stack = (void **)(traceBuf + nLen);
2663 int num = backtrace(stack, ((sizeof(traceBuf)-nLen)/sizeof(void *)));
2664 if (num > 0)
2665 {
2666 uint32_t *header = (uint32_t *)traceBuf;
2667
2668 header[0] = 0x494D5445; // IMTE (IntelMediaTraceEvent) as ftrace raw marker tag
2669 header[1] = (EVENT_CALL_STACK << 16) | (num*sizeof(void *)+sizeof(uint32_t));
2670 header[2] = 0;
2671 header[3] = (uint32_t)num;
2672 nLen += num*sizeof(void *);
2673 size_t ret = write(MosUtilitiesSpecificNext::m_mosTraceFd, traceBuf, nLen);
2674 }
2675 }
2676 #endif
2677 }
2678 return;
2679 }
2680
2681 bool MosUtilities::MosShouldTraceEventMsg(
2682 uint8_t level,
2683 uint8_t compID)
2684 {
2685 return false;
2686 }
2687
2688 void MosUtilities::MosTraceEventMsg(
2689 uint8_t level,
2690 uint8_t compID,
2691 void *message,
2692 void *functionName,
2693 uint32_t lineNum)
2694 {
2695 }
2696
2697 void MosUtilities::MosTraceDataDump(
2698 const char *pcName,
2699 uint32_t flags,
2700 const void *pBuf,
2701 uint32_t dwSize)
2702 {
2703 if (MosUtilitiesSpecificNext::m_mosTraceFd >= 0 && pBuf && pcName)
2704 {
2705 uint8_t *pTraceBuf = (uint8_t *)MOS_AllocAndZeroMemory(TRACE_EVENT_MAX_SIZE);
2706 size_t writeSize = 0;
2707
2708 if (pTraceBuf)
2709 {
2710 // trace header
2711 uint32_t *header = (uint32_t *)pTraceBuf;
2712 uint32_t nLen = strlen(pcName) & 0xff;// 255 max pcName length
2713
2714 header[0] = 0x494D5445; // IMTE (IntelMediaTraceEvent) as ftrace raw marker tag
2715 header[1] = (EVENT_DATA_DUMP << 16) | (8 + nLen + 1);
2716 header[2] = EVENT_TYPE_START;
2717 header[3] = dwSize;
2718 header[4] = flags;
2719 memcpy(&header[5], pcName, nLen);
2720 nLen += TRACE_EVENT_HEADER_SIZE + 8 + 1;
2721 writeSize = write(MosUtilitiesSpecificNext::m_mosTraceFd, pTraceBuf, nLen);
2722 // send dump data
2723 header[2] = EVENT_TYPE_INFO;
2724 const uint8_t *pData = static_cast<const uint8_t *>(pBuf);
2725 while (dwSize > 0)
2726 {
2727 uint32_t size = dwSize;
2728 if (size > TRACE_EVENT_MAX_DATA_SIZE)
2729 {
2730 size = TRACE_EVENT_MAX_DATA_SIZE;
2731 }
2732 uint16_t len = ((size + 3) & ~3) / sizeof(uint32_t);
2733 uint8_t *pDst = (uint8_t *)&header[3];
2734
2735 header[1] = (EVENT_DATA_DUMP << 16) | (size + sizeof(len));
2736 memcpy(pDst, &len, sizeof(len));
2737 memcpy(pDst+sizeof(len), pData, size);
2738 nLen = TRACE_EVENT_HEADER_SIZE + size + sizeof(len);
2739 writeSize = write(MosUtilitiesSpecificNext::m_mosTraceFd, pTraceBuf, nLen);
2740 dwSize -= size;
2741 pData += size;
2742 }
2743 // send dump end
2744 header[1] = EVENT_DATA_DUMP << 16;
2745 header[2] = EVENT_TYPE_END;
2746 writeSize = write(MosUtilitiesSpecificNext::m_mosTraceFd, pTraceBuf, TRACE_EVENT_HEADER_SIZE);
2747
2748 MOS_FreeMemory(pTraceBuf);
2749 }
2750 }
2751 }
2752
2753 void MosUtilities::MosTraceDataDictionary(
2754 const char* pcName,
2755 const void* pBuf,
2756 uint32_t dwSize)
2757 {
2758 // not implemented
2759 }
2760
2761 MOS_STATUS MosUtilities::MosGfxInfoInit()
2762 {
2763 // not implemented
2764 return MOS_STATUS_SUCCESS;
2765 }
2766
2767 void MosUtilities::MosGfxInfoClose()
2768 {
2769 // not implemented
2770 }
2771
2772 void MosUtilities::MosGfxInfoRTErrInternal(uint8_t ver,
2773 uint16_t compId,
2774 uint16_t FtrId,
2775 uint32_t ErrorCode,
2776 uint8_t num_of_triples,
2777 va_list args)
2778 {
2779 // not implemented
2780 }
2781
2782 void MosUtilities::MosGfxInfoRTErr(uint8_t ver,
2783 uint16_t compId,
2784 uint16_t FtrId,
2785 uint32_t ErrorCode,
2786 uint8_t num_of_triples,
2787 ...)
2788 {
2789 // not implemented
2790 }
2791
2792 void MosUtilities::MosGfxInfoInternal(
2793 uint8_t ver,
2794 uint16_t compId,
2795 uint32_t tmtryID,
2796 uint8_t num_of_triples,
2797 va_list args)
2798 {
2799 // not implemented
2800 }
2801
2802 bool MosUtilities::MosIsProfilerDumpEnabled()
2803 {
2804 return true;
2805 }
2806
2807 void MosUtilities::MosGfxInfo(
2808 uint8_t ver,
2809 uint16_t compId,
2810 uint32_t tmtryID,
2811 uint8_t num_of_triples,
2812 ...)
2813 {
2814 // not implemented
2815 }
2816
2817 #if (_DEBUG || _RELEASE_INTERNAL)
2818 void MosUtilities::MosMMPWriteFile(
2819 const std::string &name,
2820 const void *data,
2821 size_t size)
2822 {
2823 std::ofstream ofs(name);
2824 ofs.write(static_cast<const char *>(data), size);
2825 }
2826 #endif //(_DEBUG || _RELEASE_INTERNAL)
2827 void PerfUtility::startTick(std::string tag)
2828 {
2829 std::lock_guard<std::mutex> lock(perfMutex);
2830 Tick newTick = {};
2831 struct timespec ts = {};
2832
2833 // get start tick count
2834 clock_gettime(CLOCK_REALTIME, &ts);
2835 newTick.start = int(ts.tv_sec * 1000000) + int(ts.tv_nsec / 1000); // us
2836
2837 std::vector<Tick> *perf = nullptr;
2838 std::map<std::string, std::vector<Tick>*>::iterator it;
2839 it = records.find(tag);
2840 if (it == records.end())
2841 {
2842 perf = new std::vector<Tick>;
2843 perf->push_back(newTick);
2844 records[tag] = perf;
2845 }
2846 else
2847 {
2848 it->second->push_back(newTick);
2849 }
2850 }
2851
2852 void PerfUtility::stopTick(std::string tag)
2853 {
2854 std::lock_guard<std::mutex> lock(perfMutex);
2855 struct timespec ts = {};
2856 std::map<std::string, std::vector<Tick>*>::iterator it;
2857 it = records.find(tag);
2858 if (it == records.end())
2859 {
2860 // should not happen
2861 return;
2862 }
2863
2864 // get stop tick count
2865 clock_gettime(CLOCK_REALTIME, &ts);
2866 it->second->back().stop = int(ts.tv_sec * 1000000) + int(ts.tv_nsec / 1000); // us
2867
2868 // calculate time interval
2869 it->second->back().time = double(it->second->back().stop - it->second->back().start) / 1000.0; // ms
2870 }
2871
2872 /*----------------------------------------------------------------------------
2873 | Name : GMMDebugBreak
2874 | Purpose : Fix compiling issue for Gmmlib on debug mode
2875 | Arguments : N/A
2876 | Returns : void
2877 | Calls : N/A
2878 | Callers : Several
2879 \---------------------------------------------------------------------------*/
2880 void GMMDebugBreak(const char *file, const char *function,const int32_t line)
2881 {
2882 // Not required for media driver
2883 return;
2884 }
2885
2886 /*----------------------------------------------------------------------------
2887 | Name : GMMPrintMessage
2888 | Purpose : Fix compiling issue for Gmmlib on debug mode
2889 | Arguments : N/A
2890 | Returns : void
2891 | Calls : N/A
2892 | Callers : Several
2893 \---------------------------------------------------------------------------*/
2894 void GMMPrintMessage(int32_t debuglevel, const char *function, ...)
2895 {
2896 // Not Required for media driver
2897 return;
2898 }