los_sched.c 36.4 KB
Newer Older
W
wenjun 已提交
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.
W
wenjun 已提交
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 "los_sched_pri.h"
W
wenjun 已提交
33
#include "los_hw_pri.h"
M
mamingshuai 已提交
34
#include "los_task_pri.h"
W
wenjun 已提交
35
#include "los_process_pri.h"
M
mamingshuai 已提交
36
#include "los_arch_mmu.h"
L
LiteOS2021 已提交
37
#include "los_hook.h"
W
wenjun 已提交
38 39 40
#ifdef LOSCFG_KERNEL_CPUP
#include "los_cpup_pri.h"
#endif
M
mamingshuai 已提交
41 42
#include "los_hw_tick_pri.h"
#include "los_tick_pri.h"
43
#ifdef LOSCFG_BASE_CORE_TSK_MONITOR
M
mamingshuai 已提交
44 45 46 47 48 49
#include "los_stackinfo_pri.h"
#endif
#include "los_mp.h"
#ifdef LOSCFG_SCHED_DEBUG
#include "los_stat_pri.h"
#endif
W
wenjun 已提交
50

M
mamingshuai 已提交
51 52 53 54 55 56 57 58
#define OS_32BIT_MAX               0xFFFFFFFFUL
#define OS_SCHED_FIFO_TIMEOUT      0x7FFFFFFF
#define OS_PRIORITY_QUEUE_NUM      32
#define PRIQUEUE_PRIOR0_BIT        0x80000000U
#define OS_SCHED_TIME_SLICES_MIN   ((5000 * OS_SYS_NS_PER_US) / OS_NS_PER_CYCLE)  /* 5ms */
#define OS_SCHED_TIME_SLICES_MAX   ((LOSCFG_BASE_CORE_TIMESLICE_TIMEOUT * OS_SYS_NS_PER_US) / OS_NS_PER_CYCLE)
#define OS_SCHED_TIME_SLICES_DIFF  (OS_SCHED_TIME_SLICES_MAX - OS_SCHED_TIME_SLICES_MIN)
#define OS_SCHED_READY_MAX         30
星e雨's avatar
星e雨 已提交
59
#define OS_TIME_SLICE_MIN          (INT32)((50 * OS_SYS_NS_PER_US) / OS_NS_PER_CYCLE) /* 50us */
M
mamingshuai 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75

typedef struct {
    LOS_DL_LIST priQueueList[OS_PRIORITY_QUEUE_NUM];
    UINT32      readyTasks[OS_PRIORITY_QUEUE_NUM];
    UINT32      queueBitmap;
} SchedQueue;

typedef struct {
    SchedQueue queueList[OS_PRIORITY_QUEUE_NUM];
    UINT32     queueBitmap;
    SchedScan  taskScan;
    SchedScan  swtmrScan;
} Sched;

STATIC Sched *g_sched = NULL;
STATIC UINT64 g_schedTickMaxResponseTime;
76
UINT64 g_sysSchedStartTime = OS_64BIT_MAX;
M
mamingshuai 已提交
77 78 79 80 81 82 83 84 85 86 87 88

#ifdef LOSCFG_SCHED_TICK_DEBUG
#define OS_SCHED_DEBUG_DATA_NUM  1000
typedef struct {
    UINT32 tickResporeTime[OS_SCHED_DEBUG_DATA_NUM];
    UINT32 index;
    UINT32 setTickCount;
    UINT64 oldResporeTime;
} SchedTickDebug;
STATIC SchedTickDebug *g_schedTickDebug = NULL;

STATIC UINT32 OsSchedDebugInit(VOID)
W
wenjun 已提交
89
{
M
mamingshuai 已提交
90 91 92 93
    UINT32 size = sizeof(SchedTickDebug) * LOSCFG_KERNEL_CORE_NUM;
    g_schedTickDebug = (SchedTickDebug *)LOS_MemAlloc(m_aucSysMem0, size);
    if (g_schedTickDebug == NULL) {
        return LOS_ERRNO_TSK_NO_MEMORY;
W
wenjun 已提交
94 95
    }

M
mamingshuai 已提交
96 97 98
    (VOID)memset_s(g_schedTickDebug, size, 0, size);
    return LOS_OK;
}
W
wenjun 已提交
99

M
mamingshuai 已提交
100 101 102 103
VOID OsSchedDebugRecordData(VOID)
{
    SchedTickDebug *schedDebug = &g_schedTickDebug[ArchCurrCpuid()];
    if (schedDebug->index < OS_SCHED_DEBUG_DATA_NUM) {
104
        UINT64 currTime = OsGetCurrSchedTimeCycle();
M
mamingshuai 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
        schedDebug->tickResporeTime[schedDebug->index] = currTime - schedDebug->oldResporeTime;
        schedDebug->oldResporeTime = currTime;
        schedDebug->index++;
    }
}

SchedTickDebug *OsSchedDebugGet(VOID)
{
    return g_schedTickDebug;
}

UINT32 OsShellShowTickRespo(VOID)
{
    UINT32 intSave;
    UINT16 cpu;
120
    UINT64 allTime;
M
mamingshuai 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

    UINT32 tickSize = sizeof(SchedTickDebug) * LOSCFG_KERNEL_CORE_NUM;
    SchedTickDebug *schedDebug = (SchedTickDebug *)LOS_MemAlloc(m_aucSysMem1, tickSize);
    if (schedDebug == NULL) {
        return LOS_NOK;
    }

    UINT32 sortLinkNum[LOSCFG_KERNEL_CORE_NUM];
    SCHEDULER_LOCK(intSave);
    (VOID)memcpy_s((CHAR *)schedDebug, tickSize, (CHAR *)OsSchedDebugGet(), tickSize);
    (VOID)memset_s((CHAR *)OsSchedDebugGet(), tickSize, 0, tickSize);
    for (cpu = 0; cpu < LOSCFG_KERNEL_CORE_NUM; cpu++) {
        sortLinkNum[cpu] = OsPercpuGetByID(cpu)->taskSortLink.nodeNum + OsPercpuGetByID(cpu)->swtmrSortLink.nodeNum;
    }
    SCHEDULER_UNLOCK(intSave);

    for (cpu = 0; cpu < LOSCFG_KERNEL_CORE_NUM; cpu++) {
        SchedTickDebug *schedData = &schedDebug[cpu];
        PRINTK("cpu : %u sched data num : %u set time count : %u SortMax : %u\n",
               cpu, schedData->index, schedData->setTickCount, sortLinkNum[cpu]);
        UINT32 *data = schedData->tickResporeTime;
142 143 144
        allTime = 0;
        for (UINT32 i = 1; i < schedData->index; i++) {
            allTime += data[i];
M
mamingshuai 已提交
145 146
            UINT32 timeUs = (data[i] * OS_NS_PER_CYCLE) / OS_SYS_NS_PER_US;
            PRINTK("     %u(%u)", timeUs, timeUs / OS_US_PER_TICK);
147
            if ((i != 0) && ((i % 5) == 0)) { /* A row of 5 data */
M
mamingshuai 已提交
148 149 150 151
                PRINTK("\n");
            }
        }

152 153
        allTime = (allTime * OS_NS_PER_CYCLE) / OS_SYS_NS_PER_US;
        PRINTK("\nTick Indicates the average response period: %llu(us)\n", allTime / (schedData->index - 1));
M
mamingshuai 已提交
154 155 156 157 158 159 160 161 162 163 164 165
    }

    (VOID)LOS_MemFree(m_aucSysMem1, schedDebug);
    return LOS_OK;
}

#else

UINT32 OsShellShowTickRespo(VOID)
{
    return LOS_NOK;
}
W
wenjun 已提交
166
#endif
M
mamingshuai 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

#ifdef LOSCFG_SCHED_DEBUG
UINT32 OsShellShowSchedParam(VOID)
{
    UINT64 averRunTime;
    UINT64 averTimeSlice;
    UINT64 averSchedWait;
    UINT64 averPendTime;
    UINT32 intSave;
    UINT32 size = g_taskMaxNum * sizeof(LosTaskCB);
    LosTaskCB *taskCBArray = LOS_MemAlloc(m_aucSysMem1, size);
    if (taskCBArray == NULL) {
        return LOS_NOK;
    }

    SCHEDULER_LOCK(intSave);
    (VOID)memcpy_s(taskCBArray, size, g_taskCBArray, size);
    SCHEDULER_UNLOCK(intSave);
    PRINTK("  Tid    AverRunTime(us)    SwitchCount  AverTimeSlice(us)    TimeSliceCount  AverReadyWait(us)  "
           "AverPendTime(us)  TaskName \n");
    for (UINT32 tid = 0; tid < g_taskMaxNum; tid++) {
        LosTaskCB *taskCB = taskCBArray + tid;
        if (OsTaskIsUnused(taskCB)) {
            continue;
W
wenjun 已提交
191
        }
M
mamingshuai 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221

        averRunTime = 0;
        averTimeSlice = 0;
        averPendTime = 0;
        averSchedWait = 0;

        if (taskCB->schedStat.switchCount >= 1) {
            averRunTime = taskCB->schedStat.runTime / taskCB->schedStat.switchCount;
            averRunTime = (averRunTime * OS_NS_PER_CYCLE) / OS_SYS_NS_PER_US;
        }

        if (taskCB->schedStat.timeSliceCount > 1) {
            averTimeSlice = taskCB->schedStat.timeSliceTime / (taskCB->schedStat.timeSliceCount - 1);
            averTimeSlice = (averTimeSlice * OS_NS_PER_CYCLE) / OS_SYS_NS_PER_US;
        }

        if (taskCB->schedStat.pendCount > 1) {
            averPendTime = taskCB->schedStat.pendTime / taskCB->schedStat.pendCount;
            averPendTime = (averPendTime * OS_NS_PER_CYCLE) / OS_SYS_NS_PER_US;
        }

        if (taskCB->schedStat.waitSchedCount > 0) {
            averSchedWait = taskCB->schedStat.waitSchedTime / taskCB->schedStat.waitSchedCount;
            averSchedWait = (averSchedWait * OS_NS_PER_CYCLE) / OS_SYS_NS_PER_US;
        }

        PRINTK("%5u%19llu%15llu%19llu%18llu%19llu%18llu  %-32s\n", taskCB->taskID,
               averRunTime, taskCB->schedStat.switchCount,
               averTimeSlice, taskCB->schedStat.timeSliceCount - 1,
               averSchedWait, averPendTime, taskCB->taskName);
W
wenjun 已提交
222
    }
M
mamingshuai 已提交
223 224 225 226 227 228 229 230 231 232 233 234

    (VOID)LOS_MemFree(m_aucSysMem1, taskCBArray);

    return LOS_OK;
}

#else

UINT32 OsShellShowSchedParam(VOID)
{
    return LOS_NOK;
}
W
wenjun 已提交
235 236
#endif

M
mamingshuai 已提交
237 238 239 240 241 242 243 244 245 246 247 248
UINT32 OsSchedSetTickTimerType(UINT32 timerType)
{
    switch (timerType) {
        case 32: /* 32 bit timer */
            g_schedTickMaxResponseTime = OS_32BIT_MAX;
            break;
        case 64: /* 64 bit timer */
            g_schedTickMaxResponseTime = OS_64BIT_MAX;
            break;
        default:
            PRINT_ERR("Unsupported Tick Timer type, The system only supports 32 and 64 bit tick timers\n");
            return LOS_NOK;
W
wenjun 已提交
249 250
    }

M
mamingshuai 已提交
251 252
    return LOS_OK;
}
W
wenjun 已提交
253

M
mamingshuai 已提交
254 255
STATIC VOID OsSchedSetStartTime(UINT64 currCycle)
{
256
    if (g_sysSchedStartTime == OS_64BIT_MAX) {
M
mamingshuai 已提交
257 258 259 260 261 262 263 264 265 266 267
        g_sysSchedStartTime = currCycle;
    }
}

STATIC INLINE VOID OsTimeSliceUpdate(LosTaskCB *taskCB, UINT64 currTime)
{
    LOS_ASSERT(currTime >= taskCB->startTime);

    INT32 incTime = (currTime - taskCB->startTime - taskCB->irqUsedTime);

    LOS_ASSERT(incTime >= 0);
W
wenjun 已提交
268

M
mamingshuai 已提交
269 270 271 272 273
    if (taskCB->policy == LOS_SCHED_RR) {
        taskCB->timeSlice -= incTime;
#ifdef LOSCFG_SCHED_DEBUG
        taskCB->schedStat.timeSliceRealTime += incTime;
#endif
W
wenjun 已提交
274
    }
M
mamingshuai 已提交
275 276 277 278 279 280
    taskCB->irqUsedTime = 0;
    taskCB->startTime = currTime;

#ifdef LOSCFG_SCHED_DEBUG
    taskCB->schedStat.allRuntime += incTime;
#endif
W
wenjun 已提交
281 282
}

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
STATIC INLINE VOID OsSchedTickReload(Percpu *currCpu, UINT64 nextResponseTime, UINT32 responseID, BOOL isTimeSlice)
{
    UINT64 currTime, nextExpireTime;
    UINT32 usedTime;

    currTime = OsGetCurrSchedTimeCycle();
    if (currCpu->tickStartTime != 0) {
        usedTime = currTime - currCpu->tickStartTime;
        currCpu->tickStartTime = 0;
    } else {
        usedTime = 0;
    }

    if ((nextResponseTime > usedTime) && ((nextResponseTime - usedTime) > OS_TICK_RESPONSE_PRECISION)) {
        nextResponseTime -= usedTime;
    } else {
        nextResponseTime = OS_TICK_RESPONSE_PRECISION;
    }

    nextExpireTime = currTime + nextResponseTime;
    if (nextExpireTime >= currCpu->responseTime) {
        return;
    }

    if (isTimeSlice) {
        /* The expiration time of the current system is the thread's slice expiration time */
        currCpu->responseID = responseID;
    } else {
        currCpu->responseID = OS_INVALID_VALUE;
    }
    currCpu->responseTime = nextExpireTime;
    HalClockTickTimerReload(nextResponseTime);

#ifdef LOSCFG_SCHED_TICK_DEBUG
    SchedTickDebug *schedDebug = &g_schedTickDebug[ArchCurrCpuid()];
    if (schedDebug->index < OS_SCHED_DEBUG_DATA_NUM) {
        schedDebug->setTickCount++;
    }
#endif
}

M
mamingshuai 已提交
324 325
STATIC INLINE VOID OsSchedSetNextExpireTime(UINT64 startTime, UINT32 responseID,
                                            UINT64 taskEndTime, UINT32 oldResponseID)
W
wenjun 已提交
326
{
M
mamingshuai 已提交
327 328 329 330
    UINT64 nextExpireTime = OsGetNextExpireTime(startTime);
    Percpu *currCpu = OsPercpuGet();
    UINT64 nextResponseTime;
    BOOL isTimeSlice = FALSE;
W
wenjun 已提交
331

332
    currCpu->schedFlag &= ~INT_PEND_TICK;
M
mamingshuai 已提交
333 334 335 336 337 338 339 340
    if (currCpu->responseID == oldResponseID) {
        /* This time has expired, and the next time the theory has expired is infinite */
        currCpu->responseTime = OS_SCHED_MAX_RESPONSE_TIME;
    }

    /* The current thread's time slice has been consumed, but the current system lock task cannot
     * trigger the schedule to release the CPU
     */
341
    if ((nextExpireTime > taskEndTime) && ((nextExpireTime - taskEndTime) > OS_SCHED_MINI_PERIOD)) {
M
mamingshuai 已提交
342 343 344
        nextExpireTime = taskEndTime;
        isTimeSlice = TRUE;
    }
W
wenjun 已提交
345

346 347
    if ((currCpu->responseTime > nextExpireTime) &&
        ((currCpu->responseTime - nextExpireTime) >= OS_TICK_RESPONSE_PRECISION)) {
M
mamingshuai 已提交
348
        nextResponseTime = nextExpireTime - startTime;
349
        if (nextResponseTime > g_schedTickMaxResponseTime) {
M
mamingshuai 已提交
350 351 352 353
            nextResponseTime = g_schedTickMaxResponseTime;
        }
    } else {
        /* There is no point earlier than the current expiration date */
354
        currCpu->tickStartTime = 0;
W
wenjun 已提交
355 356 357
        return;
    }

358
    OsSchedTickReload(currCpu, nextResponseTime, responseID, isTimeSlice);
M
mamingshuai 已提交
359 360 361 362 363
}

VOID OsSchedUpdateExpireTime(UINT64 startTime)
{
    UINT64 endTime;
364
    Percpu *cpu = OsPercpuGet();
M
mamingshuai 已提交
365 366
    LosTaskCB *runTask = OsCurrTaskGet();

367 368 369 370 371
    if (!OS_SCHEDULER_ACTIVE || OS_INT_ACTIVE) {
        cpu->schedFlag |= INT_PEND_TICK;
        return;
    }

M
mamingshuai 已提交
372 373 374 375 376 377
    if (runTask->policy == LOS_SCHED_RR) {
        LOS_SpinLock(&g_taskSpin);
        INT32 timeSlice = (runTask->timeSlice <= OS_TIME_SLICE_MIN) ? runTask->initTimeSlice : runTask->timeSlice;
        LOS_SpinUnlock(&g_taskSpin);
        endTime = startTime + timeSlice;
    } else {
378
        endTime = OS_SCHED_MAX_RESPONSE_TIME - OS_TICK_RESPONSE_PRECISION;
M
mamingshuai 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    }

    OsSchedSetNextExpireTime(startTime, runTask->taskID, endTime, runTask->taskID);
}

STATIC INLINE UINT32 OsSchedCalculateTimeSlice(UINT16 proPriority, UINT16 priority)
{
    UINT32 ratTime, readTasks;

    SchedQueue *queueList = &g_sched->queueList[proPriority];
    readTasks = queueList->readyTasks[priority];
    if (readTasks > OS_SCHED_READY_MAX) {
        return OS_SCHED_TIME_SLICES_MIN;
    }
    ratTime = ((OS_SCHED_READY_MAX - readTasks) * OS_SCHED_TIME_SLICES_DIFF) / OS_SCHED_READY_MAX;
    return (ratTime + OS_SCHED_TIME_SLICES_MIN);
}

STATIC INLINE VOID OsSchedPriQueueEnHead(UINT32 proPriority, LOS_DL_LIST *priqueueItem, UINT32 priority)
{
    SchedQueue *queueList = &g_sched->queueList[proPriority];
    LOS_DL_LIST *priQueueList = &queueList->priQueueList[0];
    UINT32 *bitMap = &queueList->queueBitmap;

    /*
     * Task control blocks are inited as zero. And when task is deleted,
     * and at the same time would be deleted from priority queue or
     * other lists, task pend node will restored as zero.
     */
    LOS_ASSERT(priqueueItem->pstNext == NULL);

    if (*bitMap == 0) {
        g_sched->queueBitmap |= PRIQUEUE_PRIOR0_BIT >> proPriority;
    }

    if (LOS_ListEmpty(&priQueueList[priority])) {
        *bitMap |= PRIQUEUE_PRIOR0_BIT >> priority;
    }

    LOS_ListHeadInsert(&priQueueList[priority], priqueueItem);
    queueList->readyTasks[priority]++;
}

STATIC INLINE VOID OsSchedPriQueueEnTail(UINT32 proPriority, LOS_DL_LIST *priqueueItem, UINT32 priority)
{
    SchedQueue *queueList = &g_sched->queueList[proPriority];
    LOS_DL_LIST *priQueueList = &queueList->priQueueList[0];
    UINT32 *bitMap = &queueList->queueBitmap;

    /*
     * Task control blocks are inited as zero. And when task is deleted,
     * and at the same time would be deleted from priority queue or
     * other lists, task pend node will restored as zero.
     */
    LOS_ASSERT(priqueueItem->pstNext == NULL);

    if (*bitMap == 0) {
        g_sched->queueBitmap |= PRIQUEUE_PRIOR0_BIT >> proPriority;
    }

    if (LOS_ListEmpty(&priQueueList[priority])) {
        *bitMap |= PRIQUEUE_PRIOR0_BIT >> priority;
    }

    LOS_ListTailInsert(&priQueueList[priority], priqueueItem);
    queueList->readyTasks[priority]++;
}

STATIC INLINE VOID OsSchedPriQueueDelete(UINT32 proPriority, LOS_DL_LIST *priqueueItem, UINT32 priority)
{
    SchedQueue *queueList = &g_sched->queueList[proPriority];
    LOS_DL_LIST *priQueueList = &queueList->priQueueList[0];
    UINT32 *bitMap = &queueList->queueBitmap;

    LOS_ListDelete(priqueueItem);
    queueList->readyTasks[priority]--;
    if (LOS_ListEmpty(&priQueueList[priority])) {
        *bitMap &= ~(PRIQUEUE_PRIOR0_BIT >> priority);
    }

    if (*bitMap == 0) {
        g_sched->queueBitmap &= ~(PRIQUEUE_PRIOR0_BIT >> proPriority);
    }
}

STATIC INLINE VOID OsSchedWakePendTimeTask(UINT64 currTime, LosTaskCB *taskCB, BOOL *needSchedule)
{
#ifndef LOSCFG_SCHED_DEBUG
    (VOID)currTime;
#endif

    LOS_SpinLock(&g_taskSpin);
    UINT16 tempStatus = taskCB->taskStatus;
    if (tempStatus & (OS_TASK_STATUS_PENDING | OS_TASK_STATUS_DELAY)) {
        taskCB->taskStatus &= ~(OS_TASK_STATUS_PENDING | OS_TASK_STATUS_PEND_TIME | OS_TASK_STATUS_DELAY);
        if (tempStatus & OS_TASK_STATUS_PENDING) {
475
#ifdef LOSCFG_KERNEL_LITEIPC
M
mamingshuai 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
            taskCB->ipcStatus &= ~IPC_THREAD_STATUS_PEND;
#endif
            taskCB->taskStatus |= OS_TASK_STATUS_TIMEOUT;
            LOS_ListDelete(&taskCB->pendList);
            taskCB->taskMux = NULL;
            OsTaskWakeClearPendMask(taskCB);
        }

        if (!(tempStatus & OS_TASK_STATUS_SUSPENDED)) {
#ifdef LOSCFG_SCHED_DEBUG
            taskCB->schedStat.pendTime += currTime - taskCB->startTime;
            taskCB->schedStat.pendCount++;
#endif
            OsSchedTaskEnQueue(taskCB);
            *needSchedule = TRUE;
        }
    }

    LOS_SpinUnlock(&g_taskSpin);
}

STATIC INLINE BOOL OsSchedScanTimerList(VOID)
{
    Percpu *cpu = OsPercpuGet();
    BOOL needSchedule = FALSE;
    SortLinkAttribute *taskSortLink = &OsPercpuGet()->taskSortLink;
    LOS_DL_LIST *listObject = &taskSortLink->sortLink;
    /*
     * When task is pended with timeout, the task block is on the timeout sortlink
     * (per cpu) and ipc(mutex,sem and etc.)'s block at the same time, it can be waken
     * up by either timeout or corresponding ipc it's waiting.
     *
     * Now synchronize sortlink preocedure is used, therefore the whole task scan needs
     * to be protected, preventing another core from doing sortlink deletion at same time.
     */
    LOS_SpinLock(&cpu->taskSortLinkSpin);

    if (LOS_ListEmpty(listObject)) {
        LOS_SpinUnlock(&cpu->taskSortLinkSpin);
        return needSchedule;
    }

    SortLinkList *sortList = LOS_DL_LIST_ENTRY(listObject->pstNext, SortLinkList, sortLinkNode);
519
    UINT64 currTime = OsGetCurrSchedTimeCycle();
M
mamingshuai 已提交
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 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
    while (sortList->responseTime <= currTime) {
        LosTaskCB *taskCB = LOS_DL_LIST_ENTRY(sortList, LosTaskCB, sortList);
        OsDeleteNodeSortLink(taskSortLink, &taskCB->sortList);
        LOS_SpinUnlock(&cpu->taskSortLinkSpin);

        OsSchedWakePendTimeTask(currTime, taskCB, &needSchedule);

        LOS_SpinLock(&cpu->taskSortLinkSpin);
        if (LOS_ListEmpty(listObject)) {
            break;
        }

        sortList = LOS_DL_LIST_ENTRY(listObject->pstNext, SortLinkList, sortLinkNode);
    }

    LOS_SpinUnlock(&cpu->taskSortLinkSpin);

    return needSchedule;
}

STATIC INLINE VOID OsSchedEnTaskQueue(LosTaskCB *taskCB, LosProcessCB *processCB)
{
    LOS_ASSERT(!(taskCB->taskStatus & OS_TASK_STATUS_READY));

    switch (taskCB->policy) {
        case LOS_SCHED_RR: {
            if (taskCB->timeSlice > OS_TIME_SLICE_MIN) {
                OsSchedPriQueueEnHead(processCB->priority, &taskCB->pendList, taskCB->priority);
            } else {
                taskCB->initTimeSlice = OsSchedCalculateTimeSlice(processCB->priority, taskCB->priority);
                taskCB->timeSlice = taskCB->initTimeSlice;
                OsSchedPriQueueEnTail(processCB->priority, &taskCB->pendList, taskCB->priority);
#ifdef LOSCFG_SCHED_DEBUG
                taskCB->schedStat.timeSliceTime = taskCB->schedStat.timeSliceRealTime;
                taskCB->schedStat.timeSliceCount++;
#endif
            }
            break;
        }
        case LOS_SCHED_FIFO: {
            /* The time slice of FIFO is always greater than 0 unless the yield is called */
            if ((taskCB->timeSlice > OS_TIME_SLICE_MIN) && (taskCB->taskStatus & OS_TASK_STATUS_RUNNING)) {
                OsSchedPriQueueEnHead(processCB->priority, &taskCB->pendList, taskCB->priority);
            } else {
                taskCB->initTimeSlice = OS_SCHED_FIFO_TIMEOUT;
                taskCB->timeSlice = taskCB->initTimeSlice;
                OsSchedPriQueueEnTail(processCB->priority, &taskCB->pendList, taskCB->priority);
            }
            break;
        }
        case LOS_SCHED_IDLE:
#ifdef LOSCFG_SCHED_DEBUG
            taskCB->schedStat.timeSliceCount = 1;
#endif
            break;
        default:
            LOS_ASSERT(0);
            break;
    }

    taskCB->taskStatus &= ~OS_TASK_STATUS_BLOCKED;
    taskCB->taskStatus |= OS_TASK_STATUS_READY;

    processCB->processStatus &= ~(OS_PROCESS_STATUS_INIT | OS_PROCESS_STATUS_PENDING);
    processCB->processStatus |= OS_PROCESS_STATUS_READY;
    processCB->readyTaskNum++;
}

STATIC INLINE VOID OsSchedDeTaskQueue(LosTaskCB *taskCB, LosProcessCB *processCB)
{
    if (taskCB->policy != LOS_SCHED_IDLE) {
        OsSchedPriQueueDelete(processCB->priority, &taskCB->pendList, taskCB->priority);
    }
    taskCB->taskStatus &= ~OS_TASK_STATUS_READY;

    processCB->readyTaskNum--;
    if (processCB->readyTaskNum == 0) {
        processCB->processStatus &= ~OS_PROCESS_STATUS_READY;
    }
}

VOID OsSchedTaskDeQueue(LosTaskCB *taskCB)
{
    LosProcessCB *processCB = OS_PCB_FROM_PID(taskCB->processID);

    if (taskCB->taskStatus & OS_TASK_STATUS_READY) {
        OsSchedDeTaskQueue(taskCB, processCB);
    }

    if (processCB->processStatus & OS_PROCESS_STATUS_READY) {
W
wenjun 已提交
610 611 612
        return;
    }

M
mamingshuai 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625
    /* If the current process has only the current thread running,
     * the process becomes blocked after the thread leaves the scheduling queue
     */
    if (OS_PROCESS_GET_RUNTASK_COUNT(processCB->processStatus) == 1) {
        processCB->processStatus |= OS_PROCESS_STATUS_PENDING;
    }
}

VOID OsSchedTaskEnQueue(LosTaskCB *taskCB)
{
    LosProcessCB *processCB = OS_PCB_FROM_PID(taskCB->processID);
#ifdef LOSCFG_SCHED_DEBUG
    if (!(taskCB->taskStatus & OS_TASK_STATUS_RUNNING)) {
626
        taskCB->startTime = OsGetCurrSchedTimeCycle();
M
mamingshuai 已提交
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
    }
#endif
    OsSchedEnTaskQueue(taskCB, processCB);
}

VOID OsSchedTaskExit(LosTaskCB *taskCB)
{
    LosProcessCB *processCB = OS_PCB_FROM_PID(taskCB->processID);

    if (taskCB->taskStatus & OS_TASK_STATUS_READY) {
        OsSchedTaskDeQueue(taskCB);
        processCB->processStatus &= ~OS_PROCESS_STATUS_PENDING;
    } else if (taskCB->taskStatus & OS_TASK_STATUS_PENDING) {
        LOS_ListDelete(&taskCB->pendList);
        taskCB->taskStatus &= ~OS_TASK_STATUS_PENDING;
    }

    if (taskCB->taskStatus & (OS_TASK_STATUS_DELAY | OS_TASK_STATUS_PEND_TIME)) {
        OsDeleteSortLink(&taskCB->sortList, OS_SORT_LINK_TASK);
        taskCB->taskStatus &= ~(OS_TASK_STATUS_DELAY | OS_TASK_STATUS_PEND_TIME);
    }
}

VOID OsSchedYield(VOID)
{
    LosTaskCB *runTask = OsCurrTaskGet();

    runTask->timeSlice = 0;

656
    runTask->startTime = OsGetCurrSchedTimeCycle();
M
mamingshuai 已提交
657 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 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
    OsSchedTaskEnQueue(runTask);
    OsSchedResched();
}

VOID OsSchedDelay(LosTaskCB *runTask, UINT32 tick)
{
    OsSchedTaskDeQueue(runTask);
    runTask->taskStatus |= OS_TASK_STATUS_DELAY;
    runTask->waitTimes = tick;

    OsSchedResched();
}

UINT32 OsSchedTaskWait(LOS_DL_LIST *list, UINT32 ticks, BOOL needSched)
{
    LosTaskCB *runTask = OsCurrTaskGet();
    OsSchedTaskDeQueue(runTask);

    runTask->taskStatus |= OS_TASK_STATUS_PENDING;
    LOS_ListTailInsert(list, &runTask->pendList);

    if (ticks != LOS_WAIT_FOREVER) {
        runTask->taskStatus |= OS_TASK_STATUS_PEND_TIME;
        runTask->waitTimes = ticks;
    }

    if (needSched == TRUE) {
        OsSchedResched();
        if (runTask->taskStatus & OS_TASK_STATUS_TIMEOUT) {
            runTask->taskStatus &= ~OS_TASK_STATUS_TIMEOUT;
            return LOS_ERRNO_TSK_TIMEOUT;
        }
    }

    return LOS_OK;
}

VOID OsSchedTaskWake(LosTaskCB *resumedTask)
{
    LOS_ListDelete(&resumedTask->pendList);
    resumedTask->taskStatus &= ~OS_TASK_STATUS_PENDING;

    if (resumedTask->taskStatus & OS_TASK_STATUS_PEND_TIME) {
        OsDeleteSortLink(&resumedTask->sortList, OS_SORT_LINK_TASK);
        resumedTask->taskStatus &= ~OS_TASK_STATUS_PEND_TIME;
    }

    if (!(resumedTask->taskStatus & OS_TASK_STATUS_SUSPENDED)) {
#ifdef LOSCFG_SCHED_DEBUG
706
        resumedTask->schedStat.pendTime += OsGetCurrSchedTimeCycle() - resumedTask->startTime;
M
mamingshuai 已提交
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
        resumedTask->schedStat.pendCount++;
#endif
        OsSchedTaskEnQueue(resumedTask);
    }
}

BOOL OsSchedModifyTaskSchedParam(LosTaskCB *taskCB, UINT16 policy, UINT16 priority)
{
    if (taskCB->policy != policy) {
        taskCB->policy = policy;
        taskCB->timeSlice = 0;
    }

    if (taskCB->taskStatus & OS_TASK_STATUS_READY) {
        OsSchedTaskDeQueue(taskCB);
        taskCB->priority = priority;
        OsSchedTaskEnQueue(taskCB);
        return TRUE;
    }

    taskCB->priority = priority;
L
LiteOS2021 已提交
728
    OsHookCall(LOS_HOOK_TYPE_TASK_PRIMODIFY, taskCB, taskCB->priority); 
M
mamingshuai 已提交
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
    if (taskCB->taskStatus & OS_TASK_STATUS_INIT) {
        OsSchedTaskEnQueue(taskCB);
        return TRUE;
    }

    if (taskCB->taskStatus & OS_TASK_STATUS_RUNNING) {
        return TRUE;
    }

    return FALSE;
}

BOOL OsSchedModifyProcessSchedParam(LosProcessCB *processCB, UINT16 policy, UINT16 priority)
{
    LosTaskCB *taskCB = NULL;
    BOOL needSched = FALSE;
    (VOID)policy;

    if (processCB->processStatus & OS_PROCESS_STATUS_READY) {
        LOS_DL_LIST_FOR_EACH_ENTRY(taskCB, &processCB->threadSiblingList, LosTaskCB, threadList) {
            if (taskCB->taskStatus & OS_TASK_STATUS_READY) {
                OsSchedPriQueueDelete(processCB->priority, &taskCB->pendList, taskCB->priority);
                OsSchedPriQueueEnTail(priority, &taskCB->pendList, taskCB->priority);
                needSched = TRUE;
            }
        }
    }

    processCB->priority = priority;
    if (processCB->processStatus & OS_PROCESS_STATUS_RUNNING) {
        needSched = TRUE;
    }

    return needSched;
}

VOID OsSchedTick(VOID)
{
    Sched *sched = g_sched;
    Percpu *currCpu = OsPercpuGet();
    BOOL needSched = FALSE;
770
    LosTaskCB *runTask = OsCurrTaskGet();
M
mamingshuai 已提交
771

772
    currCpu->tickStartTime = runTask->irqStartTime;
M
mamingshuai 已提交
773 774 775 776 777 778 779 780 781
    if (currCpu->responseID == OS_INVALID_VALUE) {
        if (sched->swtmrScan != NULL) {
            (VOID)sched->swtmrScan();
        }

        needSched = sched->taskScan();

        if (needSched) {
            LOS_MpSchedule(OS_MP_CPU_ALL);
782
            currCpu->schedFlag |= INT_PEND_RESCH;
M
mamingshuai 已提交
783 784
        }
    }
785 786
    currCpu->schedFlag |= INT_PEND_TICK;
    currCpu->responseTime = OS_SCHED_MAX_RESPONSE_TIME;
M
mamingshuai 已提交
787 788
}

789
VOID OsSchedSetIdleTaskSchedParam(LosTaskCB *idleTask)
M
mamingshuai 已提交
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
{
    idleTask->policy = LOS_SCHED_IDLE;
    idleTask->initTimeSlice = OS_SCHED_FIFO_TIMEOUT;
    idleTask->timeSlice = idleTask->initTimeSlice;
    OsSchedTaskEnQueue(idleTask);
}

UINT32 OsSchedSwtmrScanRegister(SchedScan func)
{
    if (func == NULL) {
        return LOS_NOK;
    }

    g_sched->swtmrScan = func;
    return LOS_OK;
}

UINT32 OsSchedInit(VOID)
{
    UINT16 index, pri;
    UINT32 ret;

    g_sched = (Sched *)LOS_MemAlloc(m_aucSysMem0, sizeof(Sched));
    if (g_sched == NULL) {
        return LOS_ERRNO_TSK_NO_MEMORY;
    }

    (VOID)memset_s(g_sched, sizeof(Sched), 0, sizeof(Sched));

    for (index = 0; index < OS_PRIORITY_QUEUE_NUM; index++) {
        SchedQueue *queueList = &g_sched->queueList[index];
        LOS_DL_LIST *priList = &queueList->priQueueList[0];
        for (pri = 0; pri < OS_PRIORITY_QUEUE_NUM; pri++) {
            LOS_ListInit(&priList[pri]);
        }
    }

    for (index = 0; index < LOSCFG_KERNEL_CORE_NUM; index++) {
        Percpu *cpu = OsPercpuGetByID(index);
        ret = OsSortLinkInit(&cpu->taskSortLink);
        if (ret != LOS_OK) {
            return LOS_ERRNO_TSK_NO_MEMORY;
        }
        cpu->responseTime = OS_SCHED_MAX_RESPONSE_TIME;
        LOS_SpinInit(&cpu->taskSortLinkSpin);
        LOS_SpinInit(&cpu->swtmrSortLinkSpin);
    }

    g_sched->taskScan = OsSchedScanTimerList;

#ifdef LOSCFG_SCHED_TICK_DEBUG
    ret = OsSchedDebugInit();
    if (ret != LOS_OK) {
        return ret;
    }
#endif
    return LOS_OK;
}

STATIC LosTaskCB *OsGetTopTask(VOID)
{
    UINT32 priority, processPriority;
    UINT32 bitmap;
    LosTaskCB *newTask = NULL;
    UINT32 processBitmap = g_sched->queueBitmap;
855
#ifdef LOSCFG_KERNEL_SMP
M
mamingshuai 已提交
856 857 858 859 860 861 862 863 864 865
    UINT32 cpuid = ArchCurrCpuid();
#endif

    while (processBitmap) {
        processPriority = CLZ(processBitmap);
        SchedQueue *queueList = &g_sched->queueList[processPriority];
        bitmap = queueList->queueBitmap;
            while (bitmap) {
                priority = CLZ(bitmap);
                LOS_DL_LIST_FOR_EACH_ENTRY(newTask, &queueList->priQueueList[priority], LosTaskCB, pendList) {
866
#ifdef LOSCFG_KERNEL_SMP
M
mamingshuai 已提交
867 868 869
                    if (newTask->cpuAffiMask & (1U << cpuid)) {
#endif
                        goto FIND_TASK;
870
#ifdef LOSCFG_KERNEL_SMP
M
mamingshuai 已提交
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
                    }
#endif
                }
            bitmap &= ~(1U << (OS_PRIORITY_QUEUE_NUM - priority - 1));
        }
        processBitmap &= ~(1U << (OS_PRIORITY_QUEUE_NUM - processPriority - 1));
    }

    newTask = OS_TCB_FROM_TID(OsPercpuGet()->idleTaskID);

FIND_TASK:
    OsSchedDeTaskQueue(newTask, OS_PCB_FROM_PID(newTask->processID));
    return newTask;
}

VOID OsSchedStart(VOID)
{
    UINT32 cpuid = ArchCurrCpuid();
    UINT32 intSave;

    SCHEDULER_LOCK(intSave);

893 894 895
    if (cpuid == 0) {
        OsTickStart();
    }
M
mamingshuai 已提交
896 897 898 899

    LosTaskCB *newTask = OsGetTopTask();
    LosProcessCB *newProcess = OS_PCB_FROM_PID(newTask->processID);

W
wenjun 已提交
900
    newTask->taskStatus |= OS_TASK_STATUS_RUNNING;
M
mamingshuai 已提交
901 902
    newProcess->processStatus |= OS_PROCESS_STATUS_RUNNING;
    newProcess->processStatus = OS_PROCESS_RUNTASK_COUNT_ADD(newProcess->processStatus);
W
wenjun 已提交
903

M
mamingshuai 已提交
904
    OsSchedSetStartTime(HalClockGetCycles());
905
    newTask->startTime = OsGetCurrSchedTimeCycle();
W
wenjun 已提交
906

907
#ifdef LOSCFG_KERNEL_SMP
M
mamingshuai 已提交
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
    /*
     * attention: current cpu needs to be set, in case first task deletion
     * may fail because this flag mismatch with the real current cpu.
     */
    newTask->currCpu = cpuid;
#endif

    OsCurrTaskSet((VOID *)newTask);

    /* System start schedule */
    OS_SCHEDULER_SET(cpuid);

    OsPercpuGet()->responseID = OS_INVALID;
    OsSchedSetNextExpireTime(newTask->startTime, newTask->taskID, newTask->startTime + newTask->timeSlice, OS_INVALID);

    PRINTK("cpu %d entering scheduler\n", cpuid);
    OsTaskContextLoad(newTask);
}
W
wenjun 已提交
926

927
#ifdef LOSCFG_KERNEL_SMP
M
mamingshuai 已提交
928 929 930 931 932 933 934 935
VOID OsSchedToUserReleaseLock(VOID)
{
    /* The scheduling lock needs to be released before returning to user mode */
    LOCKDEP_CHECK_OUT(&g_taskSpin);
    ArchSpinUnlock(&g_taskSpin.rawLock);

    OsPercpuGet()->taskLockCnt--;
}
W
wenjun 已提交
936 937
#endif

938
#ifdef LOSCFG_BASE_CORE_TSK_MONITOR
M
mamingshuai 已提交
939 940 941 942 943
STATIC VOID OsTaskStackCheck(LosTaskCB *runTask, LosTaskCB *newTask)
{
    if (!OS_STACK_MAGIC_CHECK(runTask->topOfStack)) {
        LOS_Panic("CURRENT task ID: %s:%d stack overflow!\n", runTask->taskName, runTask->taskID);
    }
W
wenjun 已提交
944

M
mamingshuai 已提交
945 946 947 948 949 950
    if (((UINTPTR)(newTask->stackPointer) <= newTask->topOfStack) ||
        ((UINTPTR)(newTask->stackPointer) > (newTask->topOfStack + newTask->stackSize))) {
        LOS_Panic("HIGHEST task ID: %s:%u SP error! StackPointer: %p TopOfStack: %p\n",
                  newTask->taskName, newTask->taskID, newTask->stackPointer, newTask->topOfStack);
    }
}
W
wenjun 已提交
951 952
#endif

M
mamingshuai 已提交
953 954
STATIC INLINE VOID OsSchedSwitchCheck(LosTaskCB *runTask, LosTaskCB *newTask)
{
955
#ifdef LOSCFG_BASE_CORE_TSK_MONITOR
M
mamingshuai 已提交
956
    OsTaskStackCheck(runTask, newTask);
957
#endif /* LOSCFG_BASE_CORE_TSK_MONITOR */
L
LiteOS2021 已提交
958
    OsHookCall(LOS_HOOK_TYPE_TASK_SWITCHEDIN, newTask, runTask);
M
mamingshuai 已提交
959 960 961 962 963 964 965 966 967 968
}

STATIC INLINE VOID OsSchedSwitchProcess(LosProcessCB *runProcess, LosProcessCB *newProcess)
{
    runProcess->processStatus = OS_PROCESS_RUNTASK_COUNT_DEC(runProcess->processStatus);
    newProcess->processStatus = OS_PROCESS_RUNTASK_COUNT_ADD(newProcess->processStatus);

    LOS_ASSERT(!(OS_PROCESS_GET_RUNTASK_COUNT(newProcess->processStatus) > LOSCFG_KERNEL_CORE_NUM));
    if (OS_PROCESS_GET_RUNTASK_COUNT(runProcess->processStatus) == 0) {
        runProcess->processStatus &= ~OS_PROCESS_STATUS_RUNNING;
W
wenjun 已提交
969 970
    }

M
mamingshuai 已提交
971 972 973
    LOS_ASSERT(!(newProcess->processStatus & OS_PROCESS_STATUS_PENDING));
    newProcess->processStatus |= OS_PROCESS_STATUS_RUNNING;

Y
YOUR_NAME 已提交
974
#ifdef LOSCFG_KERNEL_VM
M
mamingshuai 已提交
975 976 977
    if (OsProcessIsUserMode(newProcess)) {
        LOS_ArchMmuContextSwitch(&newProcess->vmSpace->archMmu);
    }
Y
YOUR_NAME 已提交
978
#endif
M
mamingshuai 已提交
979 980 981 982 983 984 985 986 987 988 989 990 991

    OsCurrProcessSet(newProcess);
}

STATIC VOID OsSchedTaskSwicth(LosTaskCB *runTask, LosTaskCB *newTask)
{
    UINT64 endTime;

    OsSchedSwitchCheck(runTask, newTask);

    runTask->taskStatus &= ~OS_TASK_STATUS_RUNNING;
    newTask->taskStatus |= OS_TASK_STATUS_RUNNING;

992
#ifdef LOSCFG_KERNEL_SMP
M
mamingshuai 已提交
993 994 995 996 997 998 999 1000 1001 1002 1003
    /* mask new running task's owner processor */
    runTask->currCpu = OS_TASK_INVALID_CPUID;
    newTask->currCpu = ArchCurrCpuid();
#endif

    OsCurrTaskSet((VOID *)newTask);
    LosProcessCB *newProcess = OS_PCB_FROM_PID(newTask->processID);
    LosProcessCB *runProcess = OS_PCB_FROM_PID(runTask->processID);
    if (runProcess != newProcess) {
        OsSchedSwitchProcess(runProcess, newProcess);
    }
W
wenjun 已提交
1004 1005 1006 1007 1008

    if (OsProcessIsUserMode(newProcess)) {
        OsCurrUserTaskSet(newTask->userArea);
    }

M
mamingshuai 已提交
1009 1010 1011
#ifdef LOSCFG_KERNEL_CPUP
    OsCpupCycleEndStart(runTask->taskID, newTask->taskID);
#endif
W
wenjun 已提交
1012

M
mamingshuai 已提交
1013 1014 1015 1016 1017 1018 1019 1020
#ifdef LOSCFG_SCHED_DEBUG
    UINT64 waitStartTime = newTask->startTime;
#endif
    if (runTask->taskStatus & OS_TASK_STATUS_READY) {
        /* When a thread enters the ready queue, its slice of time is updated */
        newTask->startTime = runTask->startTime;
    } else {
        /* The currently running task is blocked */
1021
        newTask->startTime = OsGetCurrSchedTimeCycle();
M
mamingshuai 已提交
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
        /* The task is in a blocking state and needs to update its time slice before pend */
        OsTimeSliceUpdate(runTask, newTask->startTime);

        if (runTask->taskStatus & (OS_TASK_STATUS_PEND_TIME | OS_TASK_STATUS_DELAY)) {
            OsAdd2SortLink(&runTask->sortList, runTask->startTime, runTask->waitTimes, OS_SORT_LINK_TASK);
        }
    }

    if (newTask->policy == LOS_SCHED_RR) {
        endTime = newTask->startTime + newTask->timeSlice;
    } else {
1033
        endTime = OS_SCHED_MAX_RESPONSE_TIME - OS_TICK_RESPONSE_PRECISION;
M
mamingshuai 已提交
1034 1035 1036 1037 1038 1039 1040 1041 1042
    }
    OsSchedSetNextExpireTime(newTask->startTime, newTask->taskID, endTime, runTask->taskID);

#ifdef LOSCFG_SCHED_DEBUG
    newTask->schedStat.waitSchedTime += newTask->startTime - waitStartTime;
    newTask->schedStat.waitSchedCount++;
    runTask->schedStat.runTime = runTask->schedStat.allRuntime;
    runTask->schedStat.switchCount++;
#endif
W
wenjun 已提交
1043 1044 1045 1046
    /* do the task context switch */
    OsTaskSchedule(newTask, runTask);
}

M
mamingshuai 已提交
1047 1048 1049 1050 1051
VOID OsSchedIrqEndCheckNeedSched(VOID)
{
    Percpu *percpu = OsPercpuGet();
    LosTaskCB *runTask = OsCurrTaskGet();

1052
    OsTimeSliceUpdate(runTask, OsGetCurrSchedTimeCycle());
M
mamingshuai 已提交
1053
    if (runTask->timeSlice <= OS_TIME_SLICE_MIN) {
1054
        percpu->schedFlag |= INT_PEND_RESCH;
M
mamingshuai 已提交
1055 1056
    }

1057 1058
    if (OsPreemptable() && (percpu->schedFlag & INT_PEND_RESCH)) {
        percpu->schedFlag &= ~INT_PEND_RESCH;
M
mamingshuai 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073

        LOS_SpinLock(&g_taskSpin);

        OsSchedTaskEnQueue(runTask);

        LosTaskCB *newTask = OsGetTopTask();
        if (runTask != newTask) {
            OsSchedTaskSwicth(runTask, newTask);
            LOS_SpinUnlock(&g_taskSpin);
            return;
        }

        LOS_SpinUnlock(&g_taskSpin);
    }

1074 1075 1076
    if (percpu->schedFlag & INT_PEND_TICK) {
        OsSchedUpdateExpireTime(runTask->startTime);
    }
M
mamingshuai 已提交
1077 1078 1079 1080 1081
}

VOID OsSchedResched(VOID)
{
    LOS_ASSERT(LOS_SpinHeld(&g_taskSpin));
1082
#ifdef LOSCFG_KERNEL_SMP
M
mamingshuai 已提交
1083 1084 1085 1086 1087
    LOS_ASSERT(OsPercpuGet()->taskLockCnt == 1);
#else
    LOS_ASSERT(OsPercpuGet()->taskLockCnt == 0);
#endif

1088
    OsPercpuGet()->schedFlag &= ~INT_PEND_RESCH;
M
mamingshuai 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
    LosTaskCB *runTask = OsCurrTaskGet();
    LosTaskCB *newTask = OsGetTopTask();
    if (runTask == newTask) {
        return;
    }

    OsSchedTaskSwicth(runTask, newTask);
}

VOID LOS_Schedule(VOID)
W
wenjun 已提交
1099 1100
{
    UINT32 intSave;
M
mamingshuai 已提交
1101 1102 1103
    LosTaskCB *runTask = OsCurrTaskGet();

    if (OS_INT_ACTIVE) {
1104
        OsPercpuGet()->schedFlag |= INT_PEND_RESCH;
M
mamingshuai 已提交
1105 1106
        return;
    }
W
wenjun 已提交
1107 1108 1109 1110 1111

    if (!OsPreemptable()) {
        return;
    }

M
mamingshuai 已提交
1112 1113 1114 1115 1116
    /*
     * trigger schedule in task will also do the slice check
     * if neccessary, it will give up the timeslice more in time.
     * otherwhise, there's no other side effects.
     */
W
wenjun 已提交
1117 1118
    SCHEDULER_LOCK(intSave);

1119
    OsTimeSliceUpdate(runTask, OsGetCurrSchedTimeCycle());
M
mamingshuai 已提交
1120

W
wenjun 已提交
1121
    /* add run task back to ready queue */
M
mamingshuai 已提交
1122
    OsSchedTaskEnQueue(runTask);
W
wenjun 已提交
1123 1124 1125 1126 1127 1128 1129

    /* reschedule to new thread */
    OsSchedResched();

    SCHEDULER_UNLOCK(intSave);
}

M
mamingshuai 已提交
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
STATIC INLINE LOS_DL_LIST *OsSchedLockPendFindPosSub(const LosTaskCB *runTask, const LOS_DL_LIST *lockList)
{
    LosTaskCB *pendedTask = NULL;
    LOS_DL_LIST *node = NULL;

    LOS_DL_LIST_FOR_EACH_ENTRY(pendedTask, lockList, LosTaskCB, pendList) {
        if (pendedTask->priority < runTask->priority) {
            continue;
        } else if (pendedTask->priority > runTask->priority) {
            node = &pendedTask->pendList;
            break;
        } else {
            node = pendedTask->pendList.pstNext;
            break;
        }
    }

    return node;
}

LOS_DL_LIST *OsSchedLockPendFindPos(const LosTaskCB *runTask, LOS_DL_LIST *lockList)
{
    LOS_DL_LIST *node = NULL;

    if (LOS_ListEmpty(lockList)) {
        node = lockList;
    } else {
        LosTaskCB *pendedTask1 = OS_TCB_FROM_PENDLIST(LOS_DL_LIST_FIRST(lockList));
        LosTaskCB *pendedTask2 = OS_TCB_FROM_PENDLIST(LOS_DL_LIST_LAST(lockList));
        if (pendedTask1->priority > runTask->priority) {
            node = lockList->pstNext;
        } else if (pendedTask2->priority <= runTask->priority) {
            node = lockList;
        } else {
            node = OsSchedLockPendFindPosSub(runTask, lockList);
        }
    }

    return node;
}