los_sched.c 33.7 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"
35
#include "los_swtmr_pri.h"
W
wenjun 已提交
36
#include "los_process_pri.h"
M
mamingshuai 已提交
37
#include "los_arch_mmu.h"
L
LiteOS2021 已提交
38
#include "los_hook.h"
W
wenjun 已提交
39 40 41
#ifdef LOSCFG_KERNEL_CPUP
#include "los_cpup_pri.h"
#endif
M
mamingshuai 已提交
42 43
#include "los_hw_tick_pri.h"
#include "los_tick_pri.h"
44
#ifdef LOSCFG_BASE_CORE_TSK_MONITOR
M
mamingshuai 已提交
45 46 47 48 49 50
#include "los_stackinfo_pri.h"
#endif
#include "los_mp.h"
#ifdef LOSCFG_SCHED_DEBUG
#include "los_stat_pri.h"
#endif
Z
zhushengle 已提交
51
#include "los_pm_pri.h"
W
wenjun 已提交
52

M
mamingshuai 已提交
53 54 55 56 57 58 59 60
#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雨 已提交
61
#define OS_TIME_SLICE_MIN          (INT32)((50 * OS_SYS_NS_PER_US) / OS_NS_PER_CYCLE) /* 50us */
62 63
#define OS_TASK_STATUS_BLOCKED     (OS_TASK_STATUS_INIT | OS_TASK_STATUS_PENDING | \
                                    OS_TASK_STATUS_DELAY | OS_TASK_STATUS_PEND_TIME)
Z
zhushengle 已提交
64

M
mamingshuai 已提交
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;
} Sched;

76 77
SchedRunQue g_schedRunQue[LOSCFG_KERNEL_CORE_NUM];
STATIC Sched g_sched;
M
mamingshuai 已提交
78 79 80 81 82 83 84 85 86 87 88 89

#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 已提交
90
{
M
mamingshuai 已提交
91 92 93 94
    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 已提交
95 96
    }

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

M
mamingshuai 已提交
101 102 103 104
VOID OsSchedDebugRecordData(VOID)
{
    SchedTickDebug *schedDebug = &g_schedTickDebug[ArchCurrCpuid()];
    if (schedDebug->index < OS_SCHED_DEBUG_DATA_NUM) {
105
        UINT64 currTime = OsGetCurrSchedTimeCycle();
M
mamingshuai 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
        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;
121
    UINT64 allTime;
M
mamingshuai 已提交
122 123 124 125 126 127 128 129 130 131 132 133

    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++) {
134
        SchedRunQue *rq = OsSchedRunQueByID(cpu);
135
        sortLinkNum[cpu] = OsGetSortLinkNodeNum(&rq->taskSortLink);
M
mamingshuai 已提交
136 137 138 139 140 141 142 143
    }
    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;
144 145 146
        allTime = 0;
        for (UINT32 i = 1; i < schedData->index; i++) {
            allTime += data[i];
M
mamingshuai 已提交
147 148
            UINT32 timeUs = (data[i] * OS_NS_PER_CYCLE) / OS_SYS_NS_PER_US;
            PRINTK("     %u(%u)", timeUs, timeUs / OS_US_PER_TICK);
149
            if ((i != 0) && ((i % 5) == 0)) { /* A row of 5 data */
M
mamingshuai 已提交
150 151 152 153
                PRINTK("\n");
            }
        }

154 155
        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 已提交
156 157 158 159 160
    }

    (VOID)LOS_MemFree(m_aucSysMem1, schedDebug);
    return LOS_OK;
}
W
wenjun 已提交
161
#endif
M
mamingshuai 已提交
162 163

#ifdef LOSCFG_SCHED_DEBUG
Z
zhushengle 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
STATIC VOID SchedDataGet(LosTaskCB *taskCB, UINT64 *runTime, UINT64 *timeSlice, UINT64 *pendTime, UINT64 *schedWait)
{
    if (taskCB->schedStat.switchCount >= 1) {
        UINT64 averRunTime = taskCB->schedStat.runTime / taskCB->schedStat.switchCount;
        *runTime = (averRunTime * OS_NS_PER_CYCLE) / OS_SYS_NS_PER_US;
    }

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

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

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

M
mamingshuai 已提交
187 188 189 190 191 192
UINT32 OsShellShowSchedParam(VOID)
{
    UINT64 averRunTime;
    UINT64 averTimeSlice;
    UINT64 averSchedWait;
    UINT64 averPendTime;
193
    UINT32 taskLinkNum[LOSCFG_KERNEL_CORE_NUM];
M
mamingshuai 已提交
194 195 196 197 198 199 200 201 202
    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);
203 204 205 206
    for (UINT16 cpu = 0; cpu < LOSCFG_KERNEL_CORE_NUM; cpu++) {
        SchedRunQue *rq = OsSchedRunQueByID(cpu);
        taskLinkNum[cpu] = OsGetSortLinkNodeNum(&rq->taskSortLink);
    }
M
mamingshuai 已提交
207
    SCHEDULER_UNLOCK(intSave);
208 209 210 211 212

    for (UINT16 cpu = 0; cpu < LOSCFG_KERNEL_CORE_NUM; cpu++) {
        PRINTK("cpu: %u Task SortMax: %u\n", cpu, taskLinkNum[cpu]);
    }

M
mamingshuai 已提交
213 214 215 216 217 218
    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 已提交
219
        }
M
mamingshuai 已提交
220 221 222 223 224 225

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

Z
zhushengle 已提交
226
        SchedDataGet(taskCB, &averRunTime, &averTimeSlice, &averPendTime, &averSchedWait);
M
mamingshuai 已提交
227 228 229 230 231

        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 已提交
232
    }
M
mamingshuai 已提交
233 234 235 236 237

    (VOID)LOS_MemFree(m_aucSysMem1, taskCBArray);

    return LOS_OK;
}
W
wenjun 已提交
238 239
#endif

240
STATIC INLINE VOID TimeSliceUpdate(LosTaskCB *taskCB, UINT64 currTime)
M
mamingshuai 已提交
241 242 243 244 245 246
{
    LOS_ASSERT(currTime >= taskCB->startTime);

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

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

M
mamingshuai 已提交
248 249 250 251 252
    if (taskCB->policy == LOS_SCHED_RR) {
        taskCB->timeSlice -= incTime;
#ifdef LOSCFG_SCHED_DEBUG
        taskCB->schedStat.timeSliceRealTime += incTime;
#endif
W
wenjun 已提交
253
    }
M
mamingshuai 已提交
254 255 256 257 258 259
    taskCB->irqUsedTime = 0;
    taskCB->startTime = currTime;

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

262
STATIC INLINE VOID SchedSetNextExpireTime(UINT32 responseID, UINT64 taskEndTime, UINT32 oldResponseID)
W
wenjun 已提交
263
{
264
    SchedRunQue *rq = OsSchedRunQue();
M
mamingshuai 已提交
265
    BOOL isTimeSlice = FALSE;
266
    UINT64 currTime = OsGetCurrSchedTimeCycle();
267
    UINT64 nextExpireTime = OsGetSortLinkNextExpireTime(&rq->taskSortLink, currTime, OS_TICK_RESPONSE_PRECISION);
W
wenjun 已提交
268

269 270
    rq->schedFlag &= ~INT_PEND_TICK;
    if (rq->responseID == oldResponseID) {
M
mamingshuai 已提交
271
        /* This time has expired, and the next time the theory has expired is infinite */
272
        rq->responseTime = OS_SCHED_MAX_RESPONSE_TIME;
M
mamingshuai 已提交
273 274 275 276 277
    }

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

283 284
    if ((rq->responseTime <= nextExpireTime) ||
        ((rq->responseTime - nextExpireTime) < OS_TICK_RESPONSE_PRECISION)) {
W
wenjun 已提交
285 286 287
        return;
    }

288 289
    if (isTimeSlice) {
        /* The expiration time of the current system is the thread's slice expiration time */
290
        rq->responseID = responseID;
291
    } else {
292
        rq->responseID = OS_INVALID_VALUE;
293 294
    }

295 296
    UINT64 nextResponseTime = nextExpireTime - currTime;
    rq->responseTime = currTime + HalClockTickTimerReload(nextResponseTime);
297 298 299 300 301 302 303

#ifdef LOSCFG_SCHED_TICK_DEBUG
    SchedTickDebug *schedDebug = &g_schedTickDebug[ArchCurrCpuid()];
    if (schedDebug->index < OS_SCHED_DEBUG_DATA_NUM) {
        schedDebug->setTickCount++;
    }
#endif
M
mamingshuai 已提交
304 305
}

306
VOID OsSchedUpdateExpireTime(VOID)
M
mamingshuai 已提交
307 308 309 310
{
    UINT64 endTime;
    LosTaskCB *runTask = OsCurrTaskGet();

311
    if (!OS_SCHEDULER_ACTIVE || OS_INT_ACTIVE) {
312
        OsSchedRunQuePendingSet();
313 314 315
        return;
    }

M
mamingshuai 已提交
316 317 318
    if (runTask->policy == LOS_SCHED_RR) {
        LOS_SpinLock(&g_taskSpin);
        INT32 timeSlice = (runTask->timeSlice <= OS_TIME_SLICE_MIN) ? runTask->initTimeSlice : runTask->timeSlice;
319
        endTime = runTask->startTime + timeSlice;
M
mamingshuai 已提交
320 321
        LOS_SpinUnlock(&g_taskSpin);
    } else {
322
        endTime = OS_SCHED_MAX_RESPONSE_TIME - OS_TICK_RESPONSE_PRECISION;
M
mamingshuai 已提交
323 324
    }

325
    SchedSetNextExpireTime(runTask->taskID, endTime, runTask->taskID);
M
mamingshuai 已提交
326 327
}

328
STATIC INLINE UINT32 SchedCalculateTimeSlice(UINT16 proPriority, UINT16 priority)
M
mamingshuai 已提交
329
{
330 331
    UINT32 retTime;
    UINT32 readyTasks;
M
mamingshuai 已提交
332

333
    SchedQueue *queueList = &g_sched.queueList[proPriority];
334 335
    readyTasks = queueList->readyTasks[priority];
    if (readyTasks > OS_SCHED_READY_MAX) {
M
mamingshuai 已提交
336 337
        return OS_SCHED_TIME_SLICES_MIN;
    }
338 339
    retTime = ((OS_SCHED_READY_MAX - readyTasks) * OS_SCHED_TIME_SLICES_DIFF) / OS_SCHED_READY_MAX;
    return (retTime + OS_SCHED_TIME_SLICES_MIN);
M
mamingshuai 已提交
340 341
}

342
STATIC INLINE VOID SchedPriQueueEnHead(UINT32 proPriority, LOS_DL_LIST *priqueueItem, UINT32 priority)
M
mamingshuai 已提交
343
{
344
    SchedQueue *queueList = &g_sched.queueList[proPriority];
M
mamingshuai 已提交
345 346 347 348 349 350 351 352 353 354 355
    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) {
356
        g_sched.queueBitmap |= PRIQUEUE_PRIOR0_BIT >> proPriority;
M
mamingshuai 已提交
357 358 359 360 361 362 363 364 365 366
    }

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

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

367
STATIC INLINE VOID SchedPriQueueEnTail(UINT32 proPriority, LOS_DL_LIST *priqueueItem, UINT32 priority)
M
mamingshuai 已提交
368
{
369
    SchedQueue *queueList = &g_sched.queueList[proPriority];
M
mamingshuai 已提交
370 371 372 373 374 375 376 377 378 379 380
    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) {
381
        g_sched.queueBitmap |= PRIQUEUE_PRIOR0_BIT >> proPriority;
M
mamingshuai 已提交
382 383 384 385 386 387 388 389 390 391
    }

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

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

392
STATIC INLINE VOID SchedPriQueueDelete(UINT32 proPriority, LOS_DL_LIST *priqueueItem, UINT32 priority)
M
mamingshuai 已提交
393
{
394
    SchedQueue *queueList = &g_sched.queueList[proPriority];
M
mamingshuai 已提交
395 396 397 398 399 400 401 402 403 404
    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) {
405
        g_sched.queueBitmap &= ~(PRIQUEUE_PRIOR0_BIT >> proPriority);
M
mamingshuai 已提交
406 407 408
    }
}

409
STATIC INLINE VOID SchedEnTaskQueue(LosTaskCB *taskCB)
M
mamingshuai 已提交
410 411 412 413 414 415
{
    LOS_ASSERT(!(taskCB->taskStatus & OS_TASK_STATUS_READY));

    switch (taskCB->policy) {
        case LOS_SCHED_RR: {
            if (taskCB->timeSlice > OS_TIME_SLICE_MIN) {
416
                SchedPriQueueEnHead(taskCB->basePrio, &taskCB->pendList, taskCB->priority);
M
mamingshuai 已提交
417
            } else {
418
                taskCB->initTimeSlice = SchedCalculateTimeSlice(taskCB->basePrio, taskCB->priority);
M
mamingshuai 已提交
419
                taskCB->timeSlice = taskCB->initTimeSlice;
420
                SchedPriQueueEnTail(taskCB->basePrio, &taskCB->pendList, taskCB->priority);
M
mamingshuai 已提交
421 422 423 424 425 426 427 428 429 430
#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)) {
431
                SchedPriQueueEnHead(taskCB->basePrio, &taskCB->pendList, taskCB->priority);
M
mamingshuai 已提交
432 433 434
            } else {
                taskCB->initTimeSlice = OS_SCHED_FIFO_TIMEOUT;
                taskCB->timeSlice = taskCB->initTimeSlice;
435
                SchedPriQueueEnTail(taskCB->basePrio, &taskCB->pendList, taskCB->priority);
M
mamingshuai 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
            }
            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;
}

VOID OsSchedTaskDeQueue(LosTaskCB *taskCB)
{
    if (taskCB->taskStatus & OS_TASK_STATUS_READY) {
456 457 458 459
        if (taskCB->policy != LOS_SCHED_IDLE) {
            SchedPriQueueDelete(taskCB->basePrio, &taskCB->pendList, taskCB->priority);
        }
        taskCB->taskStatus &= ~OS_TASK_STATUS_READY;
M
mamingshuai 已提交
460 461 462 463 464 465 466
    }
}

VOID OsSchedTaskEnQueue(LosTaskCB *taskCB)
{
#ifdef LOSCFG_SCHED_DEBUG
    if (!(taskCB->taskStatus & OS_TASK_STATUS_RUNNING)) {
467
        taskCB->startTime = OsGetCurrSchedTimeCycle();
M
mamingshuai 已提交
468 469
    }
#endif
470
    SchedEnTaskQueue(taskCB);
M
mamingshuai 已提交
471 472 473 474 475 476 477 478 479 480 481 482
}

VOID OsSchedTaskExit(LosTaskCB *taskCB)
{
    if (taskCB->taskStatus & OS_TASK_STATUS_READY) {
        OsSchedTaskDeQueue(taskCB);
    } 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)) {
483
        OsSchedDeTaskFromTimeList(taskCB);
M
mamingshuai 已提交
484 485 486 487 488 489 490 491 492 493
        taskCB->taskStatus &= ~(OS_TASK_STATUS_DELAY | OS_TASK_STATUS_PEND_TIME);
    }
}

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

    runTask->timeSlice = 0;

494
    runTask->startTime = OsGetCurrSchedTimeCycle();
M
mamingshuai 已提交
495 496 497 498
    OsSchedTaskEnQueue(runTask);
    OsSchedResched();
}

499
VOID OsSchedDelay(LosTaskCB *runTask, UINT64 waitTime)
M
mamingshuai 已提交
500 501
{
    runTask->taskStatus |= OS_TASK_STATUS_DELAY;
502
    runTask->waitTime = waitTime;
M
mamingshuai 已提交
503 504 505 506 507 508 509 510 511 512 513 514 515

    OsSchedResched();
}

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

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

    if (ticks != LOS_WAIT_FOREVER) {
        runTask->taskStatus |= OS_TASK_STATUS_PEND_TIME;
516
        runTask->waitTime = OS_SCHED_TICK_TO_CYCLE(ticks);
M
mamingshuai 已提交
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
    }

    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) {
536
        OsSchedDeTaskFromTimeList(resumedTask);
M
mamingshuai 已提交
537 538 539 540 541
        resumedTask->taskStatus &= ~OS_TASK_STATUS_PEND_TIME;
    }

    if (!(resumedTask->taskStatus & OS_TASK_STATUS_SUSPENDED)) {
#ifdef LOSCFG_SCHED_DEBUG
542
        resumedTask->schedStat.pendTime += OsGetCurrSchedTimeCycle() - resumedTask->startTime;
M
mamingshuai 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
        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;
W
wangchen 已提交
564
    OsHookCall(LOS_HOOK_TYPE_TASK_PRIMODIFY, taskCB, taskCB->priority);
M
mamingshuai 已提交
565 566 567 568 569 570 571 572 573 574 575 576
    if (taskCB->taskStatus & OS_TASK_STATUS_INIT) {
        OsSchedTaskEnQueue(taskCB);
        return TRUE;
    }

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

    return FALSE;
}

577
BOOL OsSchedModifyProcessSchedParam(UINT32 pid, UINT16 policy, UINT16 priority)
M
mamingshuai 已提交
578
{
579
    LosProcessCB *processCB = OS_PCB_FROM_PID(pid);
M
mamingshuai 已提交
580 581 582 583
    LosTaskCB *taskCB = NULL;
    BOOL needSched = FALSE;
    (VOID)policy;

584 585 586 587 588 589 590
    LOS_DL_LIST_FOR_EACH_ENTRY(taskCB, &processCB->threadSiblingList, LosTaskCB, threadList) {
        if (taskCB->taskStatus & OS_TASK_STATUS_READY) {
            SchedPriQueueDelete(taskCB->basePrio, &taskCB->pendList, taskCB->priority);
            SchedPriQueueEnTail(priority, &taskCB->pendList, taskCB->priority);
            needSched = TRUE;
        } else if (taskCB->taskStatus & OS_TASK_STATUS_RUNNING) {
            needSched = TRUE;
M
mamingshuai 已提交
591
        }
592
        taskCB->basePrio = priority;
M
mamingshuai 已提交
593 594 595 596 597
    }

    return needSched;
}

598
STATIC VOID SchedFreezeTask(LosTaskCB *taskCB)
Z
zhushengle 已提交
599 600 601 602 603 604 605 606 607 608 609 610
{
    UINT64 responseTime;

    if (!OsIsPmMode()) {
        return;
    }

    if (!(taskCB->taskStatus & (OS_TASK_STATUS_PEND_TIME | OS_TASK_STATUS_DELAY))) {
        return;
    }

    responseTime = GET_SORTLIST_VALUE(&taskCB->sortList);
611
    OsSchedDeTaskFromTimeList(taskCB);
Z
zhushengle 已提交
612 613 614 615 616
    SET_SORTLIST_VALUE(&taskCB->sortList, responseTime);
    taskCB->taskStatus |= OS_TASK_FLAG_FREEZE;
    return;
}

617
STATIC VOID SchedUnfreezeTask(LosTaskCB *taskCB)
Z
zhushengle 已提交
618 619 620 621 622 623 624 625 626 627 628
{
    UINT64 currTime, responseTime;

    if (!(taskCB->taskStatus & OS_TASK_FLAG_FREEZE)) {
        return;
    }

    taskCB->taskStatus &= ~OS_TASK_FLAG_FREEZE;
    currTime = OsGetCurrSchedTimeCycle();
    responseTime = GET_SORTLIST_VALUE(&taskCB->sortList);
    if (responseTime > currTime) {
629
        OsSchedAddTask2TimeList(taskCB, responseTime);
Z
zhushengle 已提交
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
        return;
    }

    SET_SORTLIST_VALUE(&taskCB->sortList, OS_SORT_LINK_INVALID_TIME);
    if (taskCB->taskStatus & OS_TASK_STATUS_PENDING) {
        LOS_ListDelete(&taskCB->pendList);
    }
    taskCB->taskStatus &= ~(OS_TASK_STATUS_DELAY | OS_TASK_STATUS_PEND_TIME | OS_TASK_STATUS_PENDING);
    return;
}

VOID OsSchedSuspend(LosTaskCB *taskCB)
{
    if (taskCB->taskStatus & OS_TASK_STATUS_READY) {
        OsSchedTaskDeQueue(taskCB);
    }

647
    SchedFreezeTask(taskCB);
Z
zhushengle 已提交
648 649 650 651 652 653 654 655 656 657 658 659

    taskCB->taskStatus |= OS_TASK_STATUS_SUSPENDED;
    OsHookCall(LOS_HOOK_TYPE_MOVEDTASKTOSUSPENDEDLIST, taskCB);
    if (taskCB == OsCurrTaskGet()) {
        OsSchedResched();
    }
}

BOOL OsSchedResume(LosTaskCB *taskCB)
{
    BOOL needSched = FALSE;

660
    SchedUnfreezeTask(taskCB);
Z
zhushengle 已提交
661 662

    taskCB->taskStatus &= ~OS_TASK_STATUS_SUSPENDED;
663
    if (!OsTaskIsBlocked(taskCB)) {
Z
zhushengle 已提交
664 665 666 667 668 669 670
        OsSchedTaskEnQueue(taskCB);
        needSched = TRUE;
    }

    return needSched;
}

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 706 707 708 709 710 711 712 713 714
STATIC INLINE VOID SchedWakePendTimeTask(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) {
            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 SchedScanTaskTimeList(SchedRunQue *rq)
{
    BOOL needSchedule = FALSE;
    SortLinkAttribute *taskSortLink = &rq->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 procedure is used, therefore the whole task scan needs
     * to be protected, preventing another core from doing sortlink deletion at same time.
     */
    LOS_SpinLock(&taskSortLink->spinLock);
M
mamingshuai 已提交
715

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
    if (LOS_ListEmpty(listObject)) {
        LOS_SpinUnlock(&taskSortLink->spinLock);
        return needSchedule;
    }

    SortLinkList *sortList = LOS_DL_LIST_ENTRY(listObject->pstNext, SortLinkList, sortLinkNode);
    UINT64 currTime = OsGetCurrSchedTimeCycle();
    while (sortList->responseTime <= currTime) {
        LosTaskCB *taskCB = LOS_DL_LIST_ENTRY(sortList, LosTaskCB, sortList);
        OsDeleteNodeSortLink(taskSortLink, &taskCB->sortList);
        LOS_SpinUnlock(&taskSortLink->spinLock);

        SchedWakePendTimeTask(currTime, taskCB, &needSchedule);

        LOS_SpinLock(&taskSortLink->spinLock);
        if (LOS_ListEmpty(listObject)) {
            break;
M
mamingshuai 已提交
733 734
        }

735 736 737 738 739 740 741 742 743 744 745 746 747
        sortList = LOS_DL_LIST_ENTRY(listObject->pstNext, SortLinkList, sortLinkNode);
    }

    LOS_SpinUnlock(&taskSortLink->spinLock);

    return needSchedule;
}

VOID OsSchedTick(VOID)
{
    SchedRunQue *rq = OsSchedRunQue();

    if (rq->responseID == OS_INVALID_VALUE) {
748
        if (SchedScanTaskTimeList(rq)) {
M
mamingshuai 已提交
749
            LOS_MpSchedule(OS_MP_CPU_ALL);
750
            rq->schedFlag |= INT_PEND_RESCH;
M
mamingshuai 已提交
751 752
        }
    }
753 754
    rq->schedFlag |= INT_PEND_TICK;
    rq->responseTime = OS_SCHED_MAX_RESPONSE_TIME;
M
mamingshuai 已提交
755 756
}

757
VOID OsSchedSetIdleTaskSchedParam(LosTaskCB *idleTask)
M
mamingshuai 已提交
758
{
759
    idleTask->basePrio = OS_TASK_PRIORITY_LOWEST;
M
mamingshuai 已提交
760 761 762 763 764 765
    idleTask->policy = LOS_SCHED_IDLE;
    idleTask->initTimeSlice = OS_SCHED_FIFO_TIMEOUT;
    idleTask->timeSlice = idleTask->initTimeSlice;
    OsSchedTaskEnQueue(idleTask);
}

Z
zhushengle 已提交
766 767
VOID OsSchedResetSchedResponseTime(UINT64 responseTime)
{
768
    OsSchedRunQue()->responseTime = responseTime;
Z
zhushengle 已提交
769 770
}

771
VOID OsSchedRunQueInit(VOID)
M
mamingshuai 已提交
772
{
773 774
    if (ArchCurrCpuid() != 0) {
        return;
M
mamingshuai 已提交
775 776
    }

777 778 779 780 781
    for (UINT16 index = 0; index < LOSCFG_KERNEL_CORE_NUM; index++) {
        SchedRunQue *rq = OsSchedRunQueByID(index);
        OsSortLinkInit(&rq->taskSortLink);
        rq->responseTime = OS_SCHED_MAX_RESPONSE_TIME;
    }
M
mamingshuai 已提交
782 783
}

784 785 786 787 788
VOID OsSchedRunQueIdleInit(UINT32 idleTaskID)
{
    SchedRunQue *rq = OsSchedRunQue();
    rq->idleTaskID = idleTaskID;
}
M
mamingshuai 已提交
789

790 791 792 793
UINT32 OsSchedInit(VOID)
{
    for (UINT16 index = 0; index < OS_PRIORITY_QUEUE_NUM; index++) {
        SchedQueue *queueList = &g_sched.queueList[index];
M
mamingshuai 已提交
794
        LOS_DL_LIST *priList = &queueList->priQueueList[0];
795
        for (UINT16 pri = 0; pri < OS_PRIORITY_QUEUE_NUM; pri++) {
M
mamingshuai 已提交
796 797 798 799 800
            LOS_ListInit(&priList[pri]);
        }
    }

#ifdef LOSCFG_SCHED_TICK_DEBUG
801
    UINT32 ret = OsSchedDebugInit();
M
mamingshuai 已提交
802 803 804 805 806 807 808
    if (ret != LOS_OK) {
        return ret;
    }
#endif
    return LOS_OK;
}

809
STATIC LosTaskCB *GetTopTask(SchedRunQue *rq)
M
mamingshuai 已提交
810 811 812 813
{
    UINT32 priority, processPriority;
    UINT32 bitmap;
    LosTaskCB *newTask = NULL;
814
    UINT32 processBitmap = g_sched.queueBitmap;
815
#ifdef LOSCFG_KERNEL_SMP
M
mamingshuai 已提交
816 817 818 819 820
    UINT32 cpuid = ArchCurrCpuid();
#endif

    while (processBitmap) {
        processPriority = CLZ(processBitmap);
821
        SchedQueue *queueList = &g_sched.queueList[processPriority];
M
mamingshuai 已提交
822 823 824 825
        bitmap = queueList->queueBitmap;
            while (bitmap) {
                priority = CLZ(bitmap);
                LOS_DL_LIST_FOR_EACH_ENTRY(newTask, &queueList->priQueueList[priority], LosTaskCB, pendList) {
826
#ifdef LOSCFG_KERNEL_SMP
M
mamingshuai 已提交
827 828 829
                    if (newTask->cpuAffiMask & (1U << cpuid)) {
#endif
                        goto FIND_TASK;
830
#ifdef LOSCFG_KERNEL_SMP
M
mamingshuai 已提交
831 832 833 834 835 836 837 838
                    }
#endif
                }
            bitmap &= ~(1U << (OS_PRIORITY_QUEUE_NUM - priority - 1));
        }
        processBitmap &= ~(1U << (OS_PRIORITY_QUEUE_NUM - processPriority - 1));
    }

839
    newTask = OS_TCB_FROM_TID(rq->idleTaskID);
M
mamingshuai 已提交
840 841

FIND_TASK:
842
    OsSchedTaskDeQueue(newTask);
M
mamingshuai 已提交
843 844 845 846 847 848 849 850
    return newTask;
}

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

851 852
    PRINTK("cpu %d entering scheduler\n", cpuid);

M
mamingshuai 已提交
853 854
    SCHEDULER_LOCK(intSave);

855
    OsTickStart();
M
mamingshuai 已提交
856

857 858
    SchedRunQue *rq = OsSchedRunQue();
    LosTaskCB *newTask = GetTopTask(rq);
W
wenjun 已提交
859 860
    newTask->taskStatus |= OS_TASK_STATUS_RUNNING;

861
#ifdef LOSCFG_KERNEL_SMP
M
mamingshuai 已提交
862 863 864 865 866 867 868 869 870
    /*
     * 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);

871 872
    newTask->startTime = OsGetCurrSchedTimeCycle();

873
    OsSwtmrResponseTimeReset(newTask->startTime);
874

M
mamingshuai 已提交
875 876 877
    /* System start schedule */
    OS_SCHEDULER_SET(cpuid);

878 879
    rq->responseID = OS_INVALID;
    SchedSetNextExpireTime(newTask->taskID, newTask->startTime + newTask->timeSlice, OS_INVALID);
M
mamingshuai 已提交
880 881
    OsTaskContextLoad(newTask);
}
W
wenjun 已提交
882

883
#ifdef LOSCFG_KERNEL_SMP
M
mamingshuai 已提交
884 885 886 887 888 889
VOID OsSchedToUserReleaseLock(VOID)
{
    /* The scheduling lock needs to be released before returning to user mode */
    LOCKDEP_CHECK_OUT(&g_taskSpin);
    ArchSpinUnlock(&g_taskSpin.rawLock);

890
    OsSchedUnlock();
M
mamingshuai 已提交
891
}
W
wenjun 已提交
892 893
#endif

894
#ifdef LOSCFG_BASE_CORE_TSK_MONITOR
895
STATIC VOID TaskStackCheck(LosTaskCB *runTask, LosTaskCB *newTask)
M
mamingshuai 已提交
896 897 898 899
{
    if (!OS_STACK_MAGIC_CHECK(runTask->topOfStack)) {
        LOS_Panic("CURRENT task ID: %s:%d stack overflow!\n", runTask->taskName, runTask->taskID);
    }
W
wenjun 已提交
900

M
mamingshuai 已提交
901 902 903 904 905 906
    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 已提交
907 908
#endif

909
STATIC INLINE VOID SchedSwitchCheck(LosTaskCB *runTask, LosTaskCB *newTask)
M
mamingshuai 已提交
910
{
911
#ifdef LOSCFG_BASE_CORE_TSK_MONITOR
912
    TaskStackCheck(runTask, newTask);
913
#endif /* LOSCFG_BASE_CORE_TSK_MONITOR */
L
LiteOS2021 已提交
914
    OsHookCall(LOS_HOOK_TYPE_TASK_SWITCHEDIN, newTask, runTask);
M
mamingshuai 已提交
915 916
}

917
STATIC VOID SchedTaskSwitch(LosTaskCB *runTask, LosTaskCB *newTask)
M
mamingshuai 已提交
918 919 920
{
    UINT64 endTime;

921
    SchedSwitchCheck(runTask, newTask);
M
mamingshuai 已提交
922 923 924 925

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

926
#ifdef LOSCFG_KERNEL_SMP
M
mamingshuai 已提交
927 928 929 930 931 932
    /* mask new running task's owner processor */
    runTask->currCpu = OS_TASK_INVALID_CPUID;
    newTask->currCpu = ArchCurrCpuid();
#endif

    OsCurrTaskSet((VOID *)newTask);
933 934 935
#ifdef LOSCFG_KERNEL_VM
    if (newTask->archMmu != runTask->archMmu) {
        LOS_ArchMmuContextSwitch((LosArchMmu *)newTask->archMmu);
W
wenjun 已提交
936
    }
937
#endif
W
wenjun 已提交
938

M
mamingshuai 已提交
939 940 941
#ifdef LOSCFG_KERNEL_CPUP
    OsCpupCycleEndStart(runTask->taskID, newTask->taskID);
#endif
W
wenjun 已提交
942

M
mamingshuai 已提交
943 944 945 946 947 948 949 950
#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 */
951
        newTask->startTime = OsGetCurrSchedTimeCycle();
M
mamingshuai 已提交
952
        /* The task is in a blocking state and needs to update its time slice before pend */
953
        TimeSliceUpdate(runTask, newTask->startTime);
M
mamingshuai 已提交
954 955

        if (runTask->taskStatus & (OS_TASK_STATUS_PEND_TIME | OS_TASK_STATUS_DELAY)) {
956
            OsSchedAddTask2TimeList(runTask, runTask->startTime + runTask->waitTime);
M
mamingshuai 已提交
957 958 959 960 961 962
        }
    }

    if (newTask->policy == LOS_SCHED_RR) {
        endTime = newTask->startTime + newTask->timeSlice;
    } else {
963
        endTime = OS_SCHED_MAX_RESPONSE_TIME - OS_TICK_RESPONSE_PRECISION;
M
mamingshuai 已提交
964
    }
965
    SchedSetNextExpireTime(newTask->taskID, endTime, runTask->taskID);
M
mamingshuai 已提交
966 967 968 969 970 971 972

#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 已提交
973 974 975 976
    /* do the task context switch */
    OsTaskSchedule(newTask, runTask);
}

M
mamingshuai 已提交
977 978
VOID OsSchedIrqEndCheckNeedSched(VOID)
{
979
    SchedRunQue *rq = OsSchedRunQue();
M
mamingshuai 已提交
980 981
    LosTaskCB *runTask = OsCurrTaskGet();

982
    TimeSliceUpdate(runTask, OsGetCurrSchedTimeCycle());
M
mamingshuai 已提交
983
    if (runTask->timeSlice <= OS_TIME_SLICE_MIN) {
984
        rq->schedFlag |= INT_PEND_RESCH;
M
mamingshuai 已提交
985 986
    }

987 988
    if (OsPreemptable() && (rq->schedFlag & INT_PEND_RESCH)) {
        rq->schedFlag &= ~INT_PEND_RESCH;
M
mamingshuai 已提交
989 990 991 992 993

        LOS_SpinLock(&g_taskSpin);

        OsSchedTaskEnQueue(runTask);

994
        LosTaskCB *newTask = GetTopTask(rq);
M
mamingshuai 已提交
995
        if (runTask != newTask) {
996
            SchedTaskSwitch(runTask, newTask);
M
mamingshuai 已提交
997 998 999 1000 1001 1002 1003
            LOS_SpinUnlock(&g_taskSpin);
            return;
        }

        LOS_SpinUnlock(&g_taskSpin);
    }

1004 1005
    if (rq->schedFlag & INT_PEND_TICK) {
        OsSchedUpdateExpireTime();
1006
    }
M
mamingshuai 已提交
1007 1008 1009 1010 1011
}

VOID OsSchedResched(VOID)
{
    LOS_ASSERT(LOS_SpinHeld(&g_taskSpin));
1012
    SchedRunQue *rq = OsSchedRunQue();
1013
#ifdef LOSCFG_KERNEL_SMP
1014
    LOS_ASSERT(rq->taskLockCnt == 1);
M
mamingshuai 已提交
1015
#else
1016
    LOS_ASSERT(rq->taskLockCnt == 0);
M
mamingshuai 已提交
1017 1018
#endif

1019
    rq->schedFlag &= ~INT_PEND_RESCH;
M
mamingshuai 已提交
1020
    LosTaskCB *runTask = OsCurrTaskGet();
1021
    LosTaskCB *newTask = GetTopTask(rq);
M
mamingshuai 已提交
1022 1023 1024 1025
    if (runTask == newTask) {
        return;
    }

1026
    SchedTaskSwitch(runTask, newTask);
M
mamingshuai 已提交
1027 1028 1029
}

VOID LOS_Schedule(VOID)
W
wenjun 已提交
1030 1031
{
    UINT32 intSave;
M
mamingshuai 已提交
1032 1033 1034
    LosTaskCB *runTask = OsCurrTaskGet();

    if (OS_INT_ACTIVE) {
1035
        OsSchedRunQuePendingSet();
M
mamingshuai 已提交
1036 1037
        return;
    }
W
wenjun 已提交
1038 1039 1040 1041 1042

    if (!OsPreemptable()) {
        return;
    }

M
mamingshuai 已提交
1043 1044
    /*
     * trigger schedule in task will also do the slice check
1045 1046
     * if necessary, it will give up the timeslice more in time.
     * otherwise, there's no other side effects.
M
mamingshuai 已提交
1047
     */
W
wenjun 已提交
1048 1049
    SCHEDULER_LOCK(intSave);

1050
    TimeSliceUpdate(runTask, OsGetCurrSchedTimeCycle());
M
mamingshuai 已提交
1051

W
wenjun 已提交
1052
    /* add run task back to ready queue */
M
mamingshuai 已提交
1053
    OsSchedTaskEnQueue(runTask);
W
wenjun 已提交
1054 1055 1056 1057 1058 1059 1060

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

    SCHEDULER_UNLOCK(intSave);
}

M
mamingshuai 已提交
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
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;
}