pthread.c 20.2 KB
Newer Older
L
likailong 已提交
1
/*
M
mamingshuai 已提交
2 3
 * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
 * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
L
likailong 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 *    conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 *    of conditions and the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

M
mamingshuai 已提交
32
#include "pthread.h"
L
likailong 已提交
33
#include <errno.h>
34
#include <stdlib.h>
L
likailong 已提交
35 36
#include <unistd.h>
#include <securec.h>
37
#include <limits.h>
38
#include <stdbool.h>
39
#include "los_config.h"
L
likailong 已提交
40
#include "los_task.h"
41
#include "los_debug.h"
L
likailong 已提交
42

43 44
#define PTHREAD_DEFAULT_NAME     "pthread"
#define PTHREAD_DEFAULT_NAME_LEN 8
L
likailong 已提交
45
#define PTHREAD_NAMELEN 16
46 47
#define PTHREAD_KEY_UNUSED 0
#define PTHREAD_KEY_USED   1
48
#define PTHREAD_TASK_INVAILD 0
49 50 51 52 53 54 55 56 57

typedef void (*PthreadKeyDtor)(void *);
typedef struct {
    int flag;
    PthreadKeyDtor destructor;
} PthreadKey;
static unsigned int g_pthreadkeyCount = 0;
static PthreadKey   g_pthreadKeyData[PTHREAD_KEYS_MAX];
static LOS_DL_LIST  g_pthreadListHead;
L
likailong 已提交
58

59 60 61 62
typedef struct {
    void *(*startRoutine)(void *);
    void *param;
    char name[PTHREAD_NAMELEN];
63 64
    uintptr_t *key;
    LOS_DL_LIST threadList;
65 66 67
    unsigned char cancelState;
    unsigned char cancelType;
    unsigned char canceled;
68
} PthreadData;
L
likailong 已提交
69

70 71
static void PthreadExitKeyDtor(PthreadData *pthreadData);

72
static void *PthreadEntry(UINT32 param)
L
likailong 已提交
73
{
74 75 76
    PthreadData *pthreadData = (PthreadData *)(UINTPTR)param;
    void *(*startRoutine)(void *) = pthreadData->startRoutine;
    void *ret = startRoutine(pthreadData->param);
77
    pthread_exit(ret);
78

79 80
    return ret;
}
L
likailong 已提交
81

82
static inline bool IsPthread(pthread_t thread)
83
{
84 85 86 87 88 89 90 91 92
    LosTaskCB *tcb = NULL;
    if ((UINT32)thread >= LOSCFG_BASE_CORE_TSK_LIMIT) {
        return false;
    }
    tcb = OS_TCB_FROM_TID((UINT32)thread);
    if ((UINTPTR)tcb->taskEntry != (UINTPTR)PthreadEntry) {
        return false;
    }
    return true;
L
likailong 已提交
93 94
}

95 96
static int PthreadCreateAttrInit(const pthread_attr_t *attr, void *(*startRoutine)(void *), void *arg,
    TSK_INIT_PARAM_S *taskInitParam)
L
likailong 已提交
97
{
98 99 100 101 102
    const pthread_attr_t *threadAttr = attr;
    struct sched_param schedParam = { 0 };
    INT32 policy = 0;
    pthread_attr_t attrTmp;
    INT32 ret;
L
likailong 已提交
103

104 105 106
    if (!attr) {
        (VOID)pthread_attr_init(&attrTmp);
        threadAttr = &attrTmp;
L
likailong 已提交
107 108
    }

109 110 111 112 113 114 115 116 117
    if (threadAttr->stackaddr_set != 0) {
        return ENOTSUP;
    }
    if (threadAttr->stacksize < PTHREAD_STACK_MIN) {
        return EINVAL;
    }
    taskInitParam->uwStackSize = threadAttr->stacksize;
    if (threadAttr->inheritsched == PTHREAD_EXPLICIT_SCHED) {
        taskInitParam->usTaskPrio = (UINT16)threadAttr->schedparam.sched_priority;
118
    } else if (IsPthread(pthread_self())) {
119 120 121
        ret = pthread_getschedparam(pthread_self(), &policy, &schedParam);
        if (ret != 0) {
            return ret;
C
Caoruihong 已提交
122
        }
123
        taskInitParam->usTaskPrio = (UINT16)schedParam.sched_priority;
124 125
    } else {
        taskInitParam->usTaskPrio = (UINT16)threadAttr->schedparam.sched_priority;
L
likailong 已提交
126 127
    }

128
    PthreadData *pthreadData = (PthreadData *)malloc(sizeof(PthreadData));
129
    if (pthreadData == NULL) {
L
likailong 已提交
130 131 132
        return ENOMEM;
    }

133 134 135 136 137 138
    errno_t error = memcpy_s(pthreadData->name, PTHREAD_NAMELEN, PTHREAD_DEFAULT_NAME, PTHREAD_DEFAULT_NAME_LEN);
    if (error != EOK) {
        free(pthreadData);
        return error;
    }

139 140 141
    pthreadData->cancelState    = PTHREAD_CANCEL_ENABLE;
    pthreadData->cancelType     = PTHREAD_CANCEL_DEFERRED;
    pthreadData->canceled       = 0;
142 143
    pthreadData->startRoutine   = startRoutine;
    pthreadData->param          = arg;
144
    pthreadData->key            = NULL;
145 146 147
    taskInitParam->pcName       = pthreadData->name;
    taskInitParam->pfnTaskEntry = PthreadEntry;
    taskInitParam->uwArg        = (UINT32)(UINTPTR)pthreadData;
148 149 150
    if (threadAttr->detachstate != PTHREAD_CREATE_DETACHED) {
        taskInitParam->uwResved = LOS_TASK_ATTR_JOINABLE;
    }
151 152 153 154 155 156 157 158 159

    return 0;
}

static int CheckForCancel(void)
{
    UINT32 intSave;
    LosTaskCB *tcb = NULL;

160 161 162 163 164 165 166
    pthread_t thread = pthread_self();
    if (!IsPthread(thread)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
        return 0;
    }

    tcb = OS_TCB_FROM_TID((UINT32)thread);
167 168 169 170 171 172 173
    intSave = LOS_IntLock();
    PthreadData *pthreadData = (PthreadData *)(UINTPTR)tcb->arg;
    if ((pthreadData->canceled) && (pthreadData->cancelState == PTHREAD_CANCEL_ENABLE)) {
        LOS_IntRestore(intSave);
        return 1;
    }
    LOS_IntRestore(intSave);
174 175 176 177 178 179 180 181 182
    return 0;
}

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    void *(*startRoutine)(void *), void *arg)
{
    TSK_INIT_PARAM_S taskInitParam = { 0 };
    UINT32 taskID;
    UINT32 ret;
183
    UINT32 intSave;
184 185 186 187 188 189 190 191 192

    if ((thread == NULL) || (startRoutine == NULL)) {
        return EINVAL;
    }

    ret = PthreadCreateAttrInit(attr, startRoutine, arg, &taskInitParam);
    if (ret != 0) {
        return ret;
    }
L
likailong 已提交
193

C
Caoruihong 已提交
194
    if (LOS_TaskCreateOnly(&taskID, &taskInitParam) != LOS_OK) {
195
        free((VOID *)(UINTPTR)taskInitParam.uwArg);
L
likailong 已提交
196 197 198
        return EINVAL;
    }

199 200 201 202 203 204 205 206 207
    PthreadData *pthreadData = (PthreadData *)taskInitParam.uwArg;
    intSave = LOS_IntLock();
    if (g_pthreadListHead.pstNext == NULL) {
        LOS_ListInit(&g_pthreadListHead);
    }

    LOS_ListAdd(&g_pthreadListHead, &pthreadData->threadList);
    LOS_IntRestore(intSave);

C
Caoruihong 已提交
208 209
    (void)LOS_TaskResume(taskID);

L
likailong 已提交
210
    *thread = (pthread_t)taskID;
211

212
    return 0;
L
likailong 已提交
213 214 215 216
}

int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *param)
{
217 218 219 220 221
    if (!IsPthread(thread)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
        return EINVAL;
    }

222
    if ((param == NULL) || (param->sched_priority < OS_TASK_PRIORITY_HIGHEST) ||
223
        (param->sched_priority >= OS_TASK_PRIORITY_LOWEST)) {
L
likailong 已提交
224 225 226 227 228 229 230 231 232 233 234 235
        return EINVAL;
    }

    /* Only support SCHED_RR policy now */
    if (policy != SCHED_RR) {
        return ENOTSUP;
    }

    if (LOS_TaskPriSet((UINT32)thread, (UINT16)param->sched_priority) != LOS_OK) {
        return EINVAL;
    }

236
    return 0;
L
likailong 已提交
237 238
}

239 240
int pthread_setschedprio(pthread_t thread, int prio)
{
241 242 243 244 245
    if (!IsPthread(thread)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
        return EINVAL;
    }

246 247 248 249 250 251 252 253 254 255 256 257
    if (LOS_TaskPriSet((UINT32)thread, (UINT16)prio) != LOS_OK) {
        return EINVAL;
    }

    return 0;
}

int pthread_once(pthread_once_t *onceControl, void (*initRoutine)(void))
{
    UINT32 intSave;
    pthread_once_t old;

258 259 260 261 262 263
    pthread_t thread = pthread_self();
    if (!IsPthread(thread)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
        return EINVAL;
    }

264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
    if ((onceControl == NULL) || (initRoutine == NULL)) {
        return EINVAL;
    }
    intSave = LOS_IntLock();
    old = *onceControl;
    *onceControl = 1;
    LOS_IntRestore(intSave);

    if (!old) {
        initRoutine();
    }

    return 0;
}

int pthread_equal(pthread_t thread1, pthread_t thread2)
{
    return (int)(thread1 == thread2);
}

int pthread_setcancelstate(int state, int *oldState)
{
    UINT32 intSave;
    LosTaskCB *tcb = NULL;
    PthreadData *pthreadData = NULL;
289 290 291 292 293 294
    pthread_t thread = pthread_self();
    if (!IsPthread(thread)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
        return EINVAL;
    }

295 296 297 298
    if ((state != PTHREAD_CANCEL_ENABLE) && (state != PTHREAD_CANCEL_DISABLE)) {
        return EINVAL;
    }

299
    tcb = OS_TCB_FROM_TID((UINT32)thread);
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    intSave = LOS_IntLock();
    pthreadData = (PthreadData *)(UINTPTR)tcb->arg;
    if (pthreadData == NULL) {
        LOS_IntRestore(intSave);
        return EINVAL;
    }

    if (oldState != NULL) {
        *oldState = pthreadData->cancelState;
    }
    pthreadData->cancelState = (UINT8)state;
    LOS_IntRestore(intSave);

    return 0;
}

int pthread_setcanceltype(int type, int *oldType)
{
    UINT32 intSave;
    LosTaskCB *tcb = NULL;
    PthreadData *pthreadData = NULL;

322 323 324 325 326 327
    pthread_t thread = pthread_self();
    if (!IsPthread(thread)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
        return EINVAL;
    }

328 329 330 331
    if ((type != PTHREAD_CANCEL_ASYNCHRONOUS) && (type != PTHREAD_CANCEL_DEFERRED)) {
        return EINVAL;
    }

332
    tcb = OS_TCB_FROM_TID((UINT32)thread);
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
    intSave = LOS_IntLock();
    pthreadData = (PthreadData *)(UINTPTR)tcb->arg;
    if (pthreadData == NULL) {
        LOS_IntRestore(intSave);
        return EINVAL;
    }

    if (oldType != NULL) {
        *oldType = pthreadData->cancelType;
    }

    pthreadData->cancelType = (UINT8)type;
    LOS_IntRestore(intSave);

    return 0;
}

L
likailong 已提交
350 351 352 353
int pthread_getschedparam(pthread_t thread, int *policy, struct sched_param *param)
{
    UINT32 prio;

354 355 356 357 358 359
    if (!IsPthread(thread)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
        return EINVAL;
    }

    if ((policy == NULL) || (param == NULL)) {
L
likailong 已提交
360 361 362 363 364 365 366 367 368 369
        return EINVAL;
    }

    prio = LOS_TaskPriGet((UINT32)thread);
    if (prio == OS_INVALID) {
        return EINVAL;
    }

    *policy = SCHED_RR;
    param->sched_priority = prio;
370

371
    return 0;
L
likailong 已提交
372 373 374 375 376 377 378
}

pthread_t pthread_self(void)
{
    return (pthread_t)LOS_CurTaskIDGet();
}

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
STATIC UINT32 DoPthreadCancel(LosTaskCB *task)
{
    UINT32 ret = LOS_OK;
    PthreadData *pthreadData = NULL;

    LOS_TaskLock();
    pthreadData = (PthreadData *)(UINTPTR)task->arg;
    pthreadData->canceled = 0;
    if ((task->taskStatus == PTHREAD_TASK_INVAILD) || (LOS_TaskSuspend(task->taskID) != LOS_OK)) {
        ret = LOS_NOK;
        goto OUT;
    }
    free((VOID *)(UINTPTR)task->arg);
    task->arg = (UINT32)(UINTPTR)NULL;
    (void)LOS_TaskDelete(task->taskID);

OUT:
    LOS_TaskUnlock();
    return ret;
}

L
likailong 已提交
400 401
int pthread_cancel(pthread_t thread)
{
402 403 404
    UINT32 intSave;
    LosTaskCB *tcb = NULL;
    PthreadData *pthreadData = NULL;
405
    if (!IsPthread(thread)) {
406
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
407 408
        return EINVAL;
    }
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    intSave = LOS_IntLock();
    tcb = OS_TCB_FROM_TID((UINT32)thread);
    pthreadData = (PthreadData *)(UINTPTR)tcb->arg;
    pthreadData->canceled = 1;
    if ((pthreadData->cancelState == PTHREAD_CANCEL_ENABLE) &&
        (pthreadData->cancelType == PTHREAD_CANCEL_ASYNCHRONOUS)) {
        /*
         * If the thread has cancellation enabled, and it is in
         * asynchronous mode, suspend it and set corresponding thread's status.
         * We also release the thread out of any current wait to make it wake up.
         */
        if (DoPthreadCancel(tcb) == LOS_NOK) {
            LOS_IntRestore(intSave);
            return ESRCH;
        }
    }
    LOS_IntRestore(intSave);

    return 0;
}
L
likailong 已提交
429

430 431 432 433 434 435 436 437 438 439 440
void pthread_testcancel(void)
{
    if (CheckForCancel()) {
        /*
         * If we have cancellation enabled, and there is a cancellation
         * pending, then go ahead and do the deed.
         * Exit now with special retVal. pthread_exit() calls the
         * cancellation handlers implicitly.
         */
        pthread_exit((void *)PTHREAD_CANCELED);
    }
L
likailong 已提交
441 442 443 444
}

int pthread_join(pthread_t thread, void **retval)
{
445
    UINTPTR result;
446 447 448 449 450
    UINT32 ret;
    if (!IsPthread(thread)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
        return EINVAL;
    }
451

452
    ret = LOS_TaskJoin((UINT32)thread, &result);
453
    if (ret == LOS_ERRNO_TSK_NOT_JOIN_SELF) {
L
likailong 已提交
454
        return EDEADLK;
455 456 457 458 459
    } else if ((ret == LOS_ERRNO_TSK_NOT_CREATED) ||
               (ret == LOS_ERRNO_TSK_OPERATE_IDLE) ||
               (ret == LOS_ERRNO_TSK_ID_INVALID) ||
               (ret == LOS_ERRNO_TSK_SUSPEND_SWTMR_NOT_ALLOWED)) {
        return ESRCH;
460 461
    } else if (ret != LOS_OK) {
        return EINVAL;
L
likailong 已提交
462 463
    }

464 465
    if (retval != NULL) {
        *retval = (VOID *)result;
L
likailong 已提交
466
    }
467

L
likailong 已提交
468 469 470 471 472
    return 0;
}

int pthread_detach(pthread_t thread)
{
473 474 475 476 477 478 479
    UINT32 ret;
    if (!IsPthread(thread)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
        return EINVAL;
    }

    ret = LOS_TaskDetach((UINT32)thread);
480 481 482
    if (ret == LOS_ERRNO_TSK_NOT_JOIN) {
        return ESRCH;
    } else if (ret != LOS_OK) {
483 484 485
        return EINVAL;
    }

486
    return 0;
L
likailong 已提交
487 488 489 490
}

void pthread_exit(void *retVal)
{
491 492
    UINT32 intSave;

493 494 495 496 497 498 499
    pthread_t thread = pthread_self();
    if (!IsPthread(thread)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
        goto EXIT;
    }

    LosTaskCB *tcb = OS_TCB_FROM_TID((UINT32)thread);
500
    tcb->joinRetval = (UINTPTR)retVal;
501
    PthreadData *pthreadData = (PthreadData *)(UINTPTR)tcb->arg;
502 503 504
    if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) {
        PRINT_ERR("%s: %d failed\n", __FUNCTION__, __LINE__);
    }
505

506 507 508 509 510 511
    if (pthreadData->key != NULL) {
        PthreadExitKeyDtor(pthreadData);
    }

    intSave = LOS_IntLock();
    LOS_ListDelete(&pthreadData->threadList);
512
    tcb->taskName = PTHREAD_DEFAULT_NAME;
513 514
    LOS_IntRestore(intSave);
    free(pthreadData);
515
    (void)LOS_TaskDelete(tcb->taskID);
516
EXIT:
517 518
    while (1) {
    }
L
likailong 已提交
519 520 521 522
}

int pthread_setname_np(pthread_t thread, const char *name)
{
523 524
    UINT32 intSave;
    LosTaskCB *taskCB = NULL;
525 526 527 528 529 530 531 532 533
    char *taskName = NULL;

    if (!IsPthread(thread)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
        return EINVAL;
    }

    taskName = LOS_TaskNameGet((UINT32)thread);
    if (taskName == NULL) {
L
likailong 已提交
534 535
        return EINVAL;
    }
536

L
likailong 已提交
537 538 539
    if (strnlen(name, PTHREAD_NAMELEN) >= PTHREAD_NAMELEN) {
        return ERANGE;
    }
540 541 542

    taskCB = OS_TCB_FROM_TID((UINT32)thread);
    intSave = LOS_IntLock();
543 544 545 546 547
    if (taskCB->taskStatus & OS_TASK_STATUS_EXIT) {
        LOS_IntRestore(intSave);
        return EINVAL;
    }

548 549 550 551 552 553 554
    if (taskCB->taskEntry == PthreadEntry) {
        (void)strcpy_s(taskName, PTHREAD_NAMELEN, name);
    } else {
        LOS_IntRestore(intSave);
        return EINVAL;
    }
    LOS_IntRestore(intSave);
555

L
likailong 已提交
556 557 558 559 560 561
    return 0;
}

int pthread_getname_np(pthread_t thread, char *buf, size_t buflen)
{
    int ret;
562
    const char *name = NULL;
L
likailong 已提交
563

564 565 566 567 568 569 570
    if (!IsPthread(thread)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
        return EINVAL;
    }

    name = LOS_TaskNameGet((UINT32)thread);
    if (name == NULL) {
L
likailong 已提交
571 572 573 574 575 576 577 578
        return EINVAL;
    }
    if (buflen > strlen(name)) {
        ret = strcpy_s(buf, buflen, name);
        if (ret == 0) {
            return 0;
        }
    }
579

L
likailong 已提交
580 581
    return ERANGE;
}
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613

static void PthreadExitKeyDtor(PthreadData *pthreadData)
{
    PthreadKey *keys = NULL;
    unsigned int intSave;

    intSave = LOS_IntLock();
    for (unsigned int count = 0; count < PTHREAD_KEYS_MAX; count++) {
        keys = &g_pthreadKeyData[count];
        if (keys->flag == PTHREAD_KEY_UNUSED) {
            continue;
        }
        PthreadKeyDtor dtor = keys->destructor;
        LOS_IntRestore(intSave);

        if ((dtor != NULL) && (pthreadData->key[count] != 0)) {
            dtor((void *)pthreadData->key[count]);
        }

        intSave = LOS_IntLock();
    }
    LOS_IntRestore(intSave);

    free((void *)pthreadData->key);
}

int pthread_key_create(pthread_key_t *k, void (*dtor)(void *))
{
    unsigned int intSave;
    unsigned int count = 0;
    PthreadKey *keys = NULL;

614 615 616 617 618 619
    pthread_t thread = pthread_self();
    if (!IsPthread(thread)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
        return EINVAL;
    }

620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
    if (k == NULL) {
        return EINVAL;
    }

    intSave = LOS_IntLock();
    if (g_pthreadkeyCount >= PTHREAD_KEYS_MAX) {
        LOS_IntRestore(intSave);
        return EAGAIN;
    }

    do {
        keys = &g_pthreadKeyData[count];
        if (keys->flag == PTHREAD_KEY_UNUSED) {
            break;
        }
        count++;
    } while (count < PTHREAD_KEYS_MAX);

    keys->destructor = dtor;
    keys->flag = PTHREAD_KEY_USED;
    g_pthreadkeyCount++;
    LOS_IntRestore(intSave);

    *k = count;
644

645 646 647 648 649 650 651
    return 0;
}

int pthread_key_delete(pthread_key_t k)
{
    unsigned int intSave;

652 653 654 655 656 657
    pthread_t thread = pthread_self();
    if (!IsPthread(thread)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, thread);
        return EINVAL;
    }

658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
    if (k >= PTHREAD_KEYS_MAX) {
        return EINVAL;
    }

    intSave = LOS_IntLock();
    if ((g_pthreadkeyCount == 0) || (g_pthreadKeyData[k].flag == PTHREAD_KEY_UNUSED)) {
        LOS_IntRestore(intSave);
        return EAGAIN;
    }

    LOS_DL_LIST *list = g_pthreadListHead.pstNext;
    while (list != &g_pthreadListHead) {
        PthreadData *pthreadData = (PthreadData *)LOS_DL_LIST_ENTRY(list, PthreadData, threadList);
        if (pthreadData->key != NULL) {
            if ((g_pthreadKeyData[k].destructor != NULL) && (pthreadData->key[k] != 0)) {
                g_pthreadKeyData[k].destructor((void *)pthreadData->key[k]);
            }
            pthreadData->key[k] = 0;
        }
        list = list->pstNext;
    }

    g_pthreadKeyData[k].destructor = NULL;
    g_pthreadKeyData[k].flag = PTHREAD_KEY_UNUSED;
    g_pthreadkeyCount--;
    LOS_IntRestore(intSave);
684

685 686 687 688 689 690 691 692
    return 0;
}

int pthread_setspecific(pthread_key_t k, const void *x)
{
    unsigned int intSave;
    uintptr_t *key = NULL;

693 694 695
    pthread_t self = pthread_self();
    if (!IsPthread(self)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, self);
696 697 698
        return EINVAL;
    }

699
    if (k >= PTHREAD_KEYS_MAX) {
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
        return EINVAL;
    }

    LosTaskCB *taskCB = OS_TCB_FROM_TID((UINT32)self);
    PthreadData *pthreadData = (PthreadData *)taskCB->arg;
    if (pthreadData->key == NULL) {
        key = (uintptr_t *)malloc(sizeof(uintptr_t) * PTHREAD_KEYS_MAX);
        if (key == NULL) {
            return ENOMEM;
        }
        (void)memset_s(key, sizeof(uintptr_t) * PTHREAD_KEYS_MAX, 0, sizeof(uintptr_t) * PTHREAD_KEYS_MAX);
    }

    intSave = LOS_IntLock();
    if (g_pthreadKeyData[k].flag == PTHREAD_KEY_UNUSED) {
        LOS_IntRestore(intSave);
        free(key);
        return EAGAIN;
    }

    if (pthreadData->key == NULL) {
        pthreadData->key = key;
    }

    pthreadData->key[k] = (uintptr_t)x;
    LOS_IntRestore(intSave);
726

727 728 729 730 731 732 733 734
    return 0;
}

void *pthread_getspecific(pthread_key_t k)
{
    unsigned int intSave;
    void *key = NULL;
    pthread_t self = pthread_self();
735 736
    if (!IsPthread(self)) {
        PRINT_ERR("[%s:%d] This task %d is not a posix thread!!!\n", __FUNCTION__, __LINE__, self);
737 738 739
        return NULL;
    }

740
    if (k >= PTHREAD_KEYS_MAX) {
741 742 743 744 745 746 747 748 749 750 751 752 753
        return NULL;
    }

    LosTaskCB *taskCB = OS_TCB_FROM_TID((UINT32)self);
    PthreadData *pthreadData = (PthreadData *)taskCB->arg;
    intSave = LOS_IntLock();
    if ((g_pthreadKeyData[k].flag == PTHREAD_KEY_UNUSED) || (pthreadData->key == NULL)) {
        LOS_IntRestore(intSave);
        return NULL;
    }

    key = (void *)pthreadData->key[k];
    LOS_IntRestore(intSave);
754

755 756 757
    return key;
}