hm_liteipc.c 50.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*!
 * @file    hm_liteipc.c
 * @brief 轻量级进程间通信
 * @link LiteIPC http://weharmonyos.com/openharmony/zh-cn/device-dev/kernel/kernel-small-bundles-ipc.html @endlink
   @verbatim
   基本概念
	   LiteIPC是OpenHarmony LiteOS-A内核提供的一种新型IPC(Inter-Process Communication,即进程间通信)机制,
	   不同于传统的System V IPC机制,LiteIPC主要是为RPC(Remote Procedure Call,即远程过程调用)而设计的,
	   而且是通过设备文件的方式对上层提供接口的,而非传统的API函数方式。
	   
	   LiteIPC中有两个主要概念,一个是ServiceManager,另一个是Service。整个系统只能有一个ServiceManager,
	   而Service可以有多个。ServiceManager有两个主要功能:一是负责Service的注册和注销,二是负责管理Service的
	   访问权限(只有有权限的任务(Task)可以向对应的Service发送IPC消息)。
   
   运行机制
	   首先将需要接收IPC消息的任务通过ServiceManager注册成为一个Service,然后通过ServiceManager为该Service
	   任务配置访问权限,即指定哪些任务可以向该Service任务发送IPC消息。LiteIPC的核心思想就是在内核态为
	   每个Service任务维护一个IPC消息队列,该消息队列通过LiteIPC设备文件向上层用户态程序分别提供代表收取
	   IPC消息的读操作和代表发送IPC消息的写操作。
   @endverbatim
 * @version 
 * @author  weharmonyos.com | 鸿蒙研究站 | 每天死磕一点点
 * @date    2021-11-22
 */
25
/*
26 27
 * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
 * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
 *
 * 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.
 */

#include "hm_liteipc.h"
#include "linux/kernel.h"
58 59
#include "fs/file.h"
#include "fs/driver.h"
60
#include "los_init.h"
61 62 63
#include "los_mp.h"
#include "los_mux.h"
#include "los_process_pri.h"
64
#include "los_sched_pri.h"
65 66
#include "los_spinlock.h"
#include "los_task_pri.h"
67
#include "los_vm_lock.h"
68 69
#include "los_vm_map.h"
#include "los_vm_page.h"
70
#include "los_vm_phys.h"
71
#include "los_hook.h"
72

73 74
#define USE_TASKID_AS_HANDLE 1 	///< 使用任务ID作为句柄
#define USE_MMAP 1				///< 使用映射( 用户空间 <--> 物理地址 <--> 内核空间 ) ==> 用户空间 <-映射-> 内核空间 
75
#define IPC_IO_DATA_MAX 8192UL	///< 最大的消息内容 8K ,posix最大消息内容 64个字节
76 77
#define IPC_MSG_DATA_SZ_MAX (IPC_IO_DATA_MAX * sizeof(SpecialObj) / (sizeof(SpecialObj) + sizeof(size_t))) ///< 消息内容上限
#define IPC_MSG_OBJECT_NUM_MAX (IPC_MSG_DATA_SZ_MAX / sizeof(SpecialObj)) ///< 消息条数上限
78

79
#define LITE_IPC_POOL_NAME "liteipc"	///< ipc池名称
80 81
#define LITE_IPC_POOL_PAGE_MAX_NUM 64 	/* 256KB | IPC池最大物理页数 */
#define LITE_IPC_POOL_PAGE_DEFAULT_NUM 16 /* 64KB | IPC池默认物理页数  */
82 83
#define LITE_IPC_POOL_MAX_SIZE (LITE_IPC_POOL_PAGE_MAX_NUM << PAGE_SHIFT)	///< 最大IPC池 256K
#define LITE_IPC_POOL_DEFAULT_SIZE (LITE_IPC_POOL_PAGE_DEFAULT_NUM << PAGE_SHIFT)///< 默认IPC池 64K
84
#define LITE_IPC_POOL_UVADDR 0x10000000 ///< IPC默认在用户空间地址
85 86
#define INVAILD_ID (-1)

87 88
#define LITEIPC_TIMEOUT_MS 5000UL			///< 超时时间单位毫秒
#define LITEIPC_TIMEOUT_NS 5000000000ULL	///< 超时时间单位纳秒
89

90 91 92
typedef struct {
    LOS_DL_LIST list;	///< 通过它挂到对应g_ipcUsedNodelist[processID]上
    VOID *ptr;			///< 指向ipc节点内容
93 94
} IpcUsedNode;

95
STATIC LosMux g_serviceHandleMapMux; 
96
#if (USE_TASKID_AS_HANDLE == 1) // @note_why 前缀cms是何意思? 难道是Content Management System(内容管理系统) :(
97
STATIC HandleInfo g_cmsTask;	///< 应该是Service管理器的意思,因借助任务ID参与管理,所以名称中存在 task ?
98
#else
99
STATIC HandleInfo g_serviceHandleMap[MAX_SERVICE_NUM]; ///< 整个系统只能有一个 ServiceManager 用于管理 service
100
#endif
101
STATIC LOS_DL_LIST g_ipcPendlist;	///< 挂起/待办链表,上面挂等待读/写消息的任务LosTaskCB
102 103 104 105 106 107

/* ipc lock */
SPIN_LOCK_INIT(g_ipcSpin);//初始化IPC自旋锁
#define IPC_LOCK(state)       LOS_SpinLockSave(&g_ipcSpin, &(state))
#define IPC_UNLOCK(state)     LOS_SpinUnlockRestore(&g_ipcSpin, state)

108 109 110 111
STATIC int LiteIpcOpen(struct file *filep);
STATIC int LiteIpcClose(struct file *filep);
STATIC int LiteIpcIoctl(struct file *filep, int cmd, unsigned long arg);
STATIC int LiteIpcMmap(struct file* filep, LosVmMapRegion *region);
112 113 114
STATIC UINT32 LiteIpcWrite(IpcContent *content);
STATIC UINT32 GetTid(UINT32 serviceHandle, UINT32 *taskID);
STATIC UINT32 HandleSpecialObjects(UINT32 dstTid, IpcListNode *node, BOOL isRollback);
115
STATIC ProcIpcInfo *LiteIpcPoolCreate(VOID);
116

117
STATIC const struct file_operations_vfs g_liteIpcFops = {
118 119 120
    .open = LiteIpcOpen,   /* open */
    .close = LiteIpcClose,  /* close */
    .ioctl = LiteIpcIoctl,  /* ioctl */
121
    .mmap = LiteIpcMmap,   /* mmap | ipc机制的关键函数*/
122 123
};

124 125 126 127 128 129 130
/*!
 * @brief OsLiteIpcInit	初始化LiteIPC模块
 *
 * @return	
 *
 * @see
 */
131
LITE_OS_SEC_TEXT_INIT UINT32 OsLiteIpcInit(VOID)
132
{
133
    UINT32 ret;
134
#if (USE_TASKID_AS_HANDLE == 1) //两种管理方式,一种是 任务ID == service ID 
135
    g_cmsTask.status = HANDLE_NOT_USED;//默认未使用
136
#else
137
    memset_s(g_serviceHandleMap, sizeof(g_serviceHandleMap), 0, sizeof(g_serviceHandleMap));//默认未使用
138 139 140 141 142
#endif
    ret = LOS_MuxInit(&g_serviceHandleMapMux, NULL);
    if (ret != LOS_OK) {
        return ret;
    }
143
    ret = (UINT32)register_driver(LITEIPC_DRIVER, &g_liteIpcFops, LITEIPC_DRIVER_MODE, NULL);
144 145 146
    if (ret != LOS_OK) {
        PRINT_ERR("register lite_ipc driver failed:%d\n", ret);
    }
147
    LOS_ListInit(&(g_ipcPendlist));
148

149 150
    return ret;
}
151

152
LOS_MODULE_INIT(OsLiteIpcInit, LOS_INIT_LEVEL_KMOD_EXTENDED);//内核IPC模块的初始化
153

154 155 156 157 158 159 160 161
/*!
 * @brief LiteIpcOpen
 * 以VFS方式为当前进程创建IPC消息池 
 * @param filep	
 * @return	
 *
 * @see
 */
162
LITE_OS_SEC_TEXT STATIC int LiteIpcOpen(struct file *filep)
163
{
164 165 166 167 168 169 170 171 172 173
    LosProcessCB *pcb = OsCurrProcessGet();
    if (pcb->ipcInfo != NULL) {
        return 0;
    }

    pcb->ipcInfo = LiteIpcPoolCreate();
    if (pcb->ipcInfo == NULL) {
        return -ENOMEM;
    }

174 175
    return 0;
}
176 177

LITE_OS_SEC_TEXT STATIC int LiteIpcClose(struct file *filep)
178 179 180
{
    return 0;
}
181
/// 池是否已经映射
182
LITE_OS_SEC_TEXT STATIC BOOL IsPoolMapped(ProcIpcInfo *ipcInfo)
183
{
184 185
    return (ipcInfo->pool.uvaddr != NULL) && (ipcInfo->pool.kvaddr != NULL) &&
        (ipcInfo->pool.poolSize != 0);
186
}
187

188 189 190 191 192 193 194 195 196
/*!
 * @brief DoIpcMmap	
 * 做IPC层映射,将内核空间虚拟地址映射到用户空间,这样的好处是用户态下操作读写的背后是在读写内核态空间
 * @param pcb	
 * @param region	
 * @return	
 *
 * @see
 */
197 198 199 200 201 202 203
LITE_OS_SEC_TEXT STATIC INT32 DoIpcMmap(LosProcessCB *pcb, LosVmMapRegion *region)
{
    UINT32 i;
    INT32 ret = 0;
    PADDR_T pa;
    UINT32 uflags = VM_MAP_REGION_FLAG_PERM_READ | VM_MAP_REGION_FLAG_PERM_USER;
    LosVmPage *vmPage = NULL;
204 205
    VADDR_T uva = (VADDR_T)(UINTPTR)pcb->ipcInfo->pool.uvaddr;//用户空间地址
    VADDR_T kva = (VADDR_T)(UINTPTR)pcb->ipcInfo->pool.kvaddr;//内核空间地址
206 207 208

    (VOID)LOS_MuxAcquire(&pcb->vmSpace->regionMux);

209 210
    for (i = 0; i < (region->range.size >> PAGE_SHIFT); i++) {//获取线性区页数
        pa = LOS_PaddrQuery((VOID *)(UINTPTR)(kva + (i << PAGE_SHIFT)));//通过内核空间查找物理地址
211 212 213 214 215
        if (pa == 0) {
            PRINT_ERR("%s, %d\n", __FUNCTION__, __LINE__);
            ret = -EINVAL;
            break;
        }
216 217
        vmPage = LOS_VmPageGet(pa);//获取物理页框
        if (vmPage == NULL) {//目的是检查物理页是否存在
218 219 220 221
            PRINT_ERR("%s, %d\n", __FUNCTION__, __LINE__);
            ret = -EINVAL;
            break;
        }
222
        STATUS_T err = LOS_ArchMmuMap(&pcb->vmSpace->archMmu, uva + (i << PAGE_SHIFT), pa, 1, uflags);//将物理页映射到用户空间
223 224 225 226 227 228
        if (err < 0) {
            ret = err;
            PRINT_ERR("%s, %d\n", __FUNCTION__, __LINE__);
            break;
        }
    }
229
    /* if any failure happened, rollback | 如果发生失败,则回滚*/
230 231
    if (i != (region->range.size >> PAGE_SHIFT)) {
        while (i--) {
232 233 234 235
            pa = LOS_PaddrQuery((VOID *)(UINTPTR)(kva + (i << PAGE_SHIFT)));//查询物理地址
            vmPage = LOS_VmPageGet(pa);//获取物理页框
            (VOID)LOS_ArchMmuUnmap(&pcb->vmSpace->archMmu, uva + (i << PAGE_SHIFT), 1);//取消与用户空间的映射
            LOS_PhysPageFree(vmPage);//释放物理页
236 237 238 239 240 241
        }
    }

    (VOID)LOS_MuxRelease(&pcb->vmSpace->regionMux);
    return ret;
}
242
///将参数线性区设为IPC专用区
243
LITE_OS_SEC_TEXT STATIC int LiteIpcMmap(struct file *filep, LosVmMapRegion *region)
244 245 246 247
{
    int ret = 0;
    LosVmMapRegion *regionTemp = NULL;
    LosProcessCB *pcb = OsCurrProcessGet();
248 249 250 251
    ProcIpcInfo *ipcInfo = pcb->ipcInfo;

    if ((ipcInfo == NULL) || (region == NULL) || (region->range.size > LITE_IPC_POOL_MAX_SIZE) ||
        (!LOS_IsRegionPermUserReadOnly(region)) || (!LOS_IsRegionFlagPrivateOnly(region))) {
252 253 254
        ret = -EINVAL;
        goto ERROR_REGION_OUT;
    }
255
    if (IsPoolMapped(ipcInfo)) {//已经用户空间和内核空间之间存在映射关系了
256 257
        return -EEXIST;
    }
258 259
    if (ipcInfo->pool.uvaddr != NULL) {//ipc池已在进程空间有地址
        regionTemp = LOS_RegionFind(pcb->vmSpace, (VADDR_T)(UINTPTR)ipcInfo->pool.uvaddr);//找到所在线性区
260
        if (regionTemp != NULL) {
261
            (VOID)LOS_RegionFree(pcb->vmSpace, regionTemp);//先释放线性区
262 263
        }
    }
264 265
    ipcInfo->pool.uvaddr = (VOID *)(UINTPTR)region->range.base;//将指定的线性区和ipc池虚拟地址绑定
    if (ipcInfo->pool.kvaddr != NULL) {//如果
266 267
        LOS_VFree(ipcInfo->pool.kvaddr);
        ipcInfo->pool.kvaddr = NULL;
268 269
    }
    /* use vmalloc to alloc phy mem */
270
    ipcInfo->pool.kvaddr = LOS_VMalloc(region->range.size);//分配物理内存
271
    if (ipcInfo->pool.kvaddr == NULL) {
272 273 274 275
        ret = -ENOMEM;
        goto ERROR_REGION_OUT;
    }
    /* do mmap */
276
    ret = DoIpcMmap(pcb, region);//对uvaddr和kvaddr做好映射关系,如此用户态下通过操作uvaddr达到操作kvaddr的目的
277 278 279 280
    if (ret) {
        goto ERROR_MAP_OUT;
    }
    /* ipc pool init */
281
    if (LOS_MemInit(ipcInfo->pool.kvaddr, region->range.size) != LOS_OK) {//初始化ipc池
282 283 284
        ret = -EINVAL;
        goto ERROR_MAP_OUT;
    }
285
    ipcInfo->pool.poolSize = region->range.size;//ipc池大小为线性区大小
286 287
    return 0;
ERROR_MAP_OUT:
288
    LOS_VFree(ipcInfo->pool.kvaddr);
289
ERROR_REGION_OUT:
290 291 292 293
    if (ipcInfo != NULL) {
        ipcInfo->pool.uvaddr = NULL;
        ipcInfo->pool.kvaddr = NULL;
    }
294 295
    return ret;
}
296
///初始化进程的IPC消息内存池
297
LITE_OS_SEC_TEXT_INIT STATIC UINT32 LiteIpcPoolInit(ProcIpcInfo *ipcInfo)
298
{
299 300
    ipcInfo->pool.uvaddr = NULL;//无用户空间地址
    ipcInfo->pool.kvaddr = NULL;//无内核空间地址
301 302
    ipcInfo->pool.poolSize = 0;
    ipcInfo->ipcTaskID = INVAILD_ID;
303
    LOS_ListInit(&ipcInfo->ipcUsedNodelist);//上面将挂已被读取的节点
304 305
    return LOS_OK;
}
306
///创建IPC消息内存池
307
LITE_OS_SEC_TEXT_INIT STATIC ProcIpcInfo *LiteIpcPoolCreate(VOID)
308
{
309
    ProcIpcInfo *ipcInfo = LOS_MemAlloc(m_aucSysMem1, sizeof(ProcIpcInfo));//从内核堆内存中申请
310 311 312 313 314 315 316 317 318
    if (ipcInfo == NULL) {
        return NULL;
    }

    (VOID)memset_s(ipcInfo, sizeof(ProcIpcInfo), 0, sizeof(ProcIpcInfo));

    (VOID)LiteIpcPoolInit(ipcInfo);
    return ipcInfo;
}
319 320 321 322 323 324 325 326 327

/*!
 * @brief LiteIpcPoolReInit	重新初始化进程的IPC消息内存池
 *
 * @param parent	
 * @return	
 *
 * @see
 */
328 329 330 331 332 333 334
LITE_OS_SEC_TEXT ProcIpcInfo *LiteIpcPoolReInit(const ProcIpcInfo *parent)
{
    ProcIpcInfo *ipcInfo = LiteIpcPoolCreate();
    if (ipcInfo == NULL) {
        return NULL;
    }

335
    ipcInfo->pool.uvaddr = parent->pool.uvaddr;//用户空间地址继续沿用
336 337 338 339
    ipcInfo->pool.kvaddr = NULL;
    ipcInfo->pool.poolSize = 0;
    ipcInfo->ipcTaskID = INVAILD_ID;
    return ipcInfo;
340
}
341
/// 释放进程的IPC消息内存池
342
STATIC VOID LiteIpcPoolDelete(ProcIpcInfo *ipcInfo, UINT32 processID)
343 344 345 346 347 348 349
{
    UINT32 intSave;
    IpcUsedNode *node = NULL;
    if (ipcInfo->pool.kvaddr != NULL) {
        LOS_VFree(ipcInfo->pool.kvaddr);
        ipcInfo->pool.kvaddr = NULL;
        IPC_LOCK(intSave);
350 351 352 353
        while (!LOS_ListEmpty(&ipcInfo->ipcUsedNodelist)) {//对进程的IPC已被读取的链表遍历
            node = LOS_DL_LIST_ENTRY(ipcInfo->ipcUsedNodelist.pstNext, IpcUsedNode, list);//挨个读取
            LOS_ListDelete(&node->list);//将自己从链表上摘出去
            free(node);//释放向内核堆内存申请的 sizeof(IpcUsedNode) 空间
354 355 356
        }
        IPC_UNLOCK(intSave);
    }
357 358 359 360 361 362
    /* remove process access to service | 删除进程对服务的访问,这里的服务指的就是任务*/
    for (UINT32 i = 0; i < MAX_SERVICE_NUM; i++) {//双方断交
        if (ipcInfo->access[i] == TRUE) {//允许访问
            ipcInfo->access[i] = FALSE; //设为不允许访问
            if (OS_TCB_FROM_TID(i)->ipcTaskInfo != NULL) {//任务有IPC时
                OS_TCB_FROM_TID(i)->ipcTaskInfo->accessMap[processID] = FALSE;//同样设置任务也不允许访问进程
363
            }
364 365 366
        }
    }
}
367
/// 销毁指定进程的IPC
368 369 370 371 372 373 374 375 376 377 378 379 380
LITE_OS_SEC_TEXT UINT32 LiteIpcPoolDestroy(UINT32 processID)
{
    LosProcessCB *pcb = OS_PCB_FROM_PID(processID);

    if (pcb->ipcInfo == NULL) {
        return LOS_NOK;
    }

    LiteIpcPoolDelete(pcb->ipcInfo, pcb->processID);
    LOS_MemFree(m_aucSysMem1, pcb->ipcInfo);
    pcb->ipcInfo = NULL;
    return LOS_OK;
}
381
/// 申请并初始化一个任务IPC
382 383 384 385 386 387 388 389 390 391 392
LITE_OS_SEC_TEXT_INIT STATIC IpcTaskInfo *LiteIpcTaskInit(VOID)
{
    IpcTaskInfo *taskInfo = LOS_MemAlloc((VOID *)m_aucSysMem1, sizeof(IpcTaskInfo));
    if (taskInfo == NULL) {
        return NULL;
    }

    (VOID)memset_s(taskInfo, sizeof(IpcTaskInfo), 0, sizeof(IpcTaskInfo));
    LOS_ListInit(&taskInfo->msgListHead);
    return taskInfo;
}
393 394 395 396

/* Only when kernel no longer access ipc node content, can user free the ipc node 
| 只有当内核不再访问ipc节点内容时,用户才能释放ipc节点*/
LITE_OS_SEC_TEXT STATIC VOID EnableIpcNodeFreeByUser(UINT32 processID, VOID *buf)
397 398
{
    UINT32 intSave;
399
    ProcIpcInfo *ipcInfo = OS_PCB_FROM_PID(processID)->ipcInfo;
400
    IpcUsedNode *node = (IpcUsedNode *)malloc(sizeof(IpcUsedNode));//申请一个已使用的节点,怎么定义已使用呢,就是被LiteIpcRead
401
    if (node != NULL) {
402
        node->ptr = buf;//指向参数缓存
403
        IPC_LOCK(intSave);
404
        LOS_ListAdd(&ipcInfo->ipcUsedNodelist, &node->list);//挂到已被读取的链表上
405 406 407
        IPC_UNLOCK(intSave);
    }
}
408
///从内核对内存中分配一个IPC节点
409
LITE_OS_SEC_TEXT STATIC VOID *LiteIpcNodeAlloc(UINT32 processID, UINT32 size)
410
{
411
    VOID *ptr = LOS_MemAlloc(OS_PCB_FROM_PID(processID)->ipcInfo->pool.kvaddr, size);
412
    PRINT_INFO("LiteIpcNodeAlloc pid:%d, pool:%x buf:%x size:%d\n",
413
               processID, OS_PCB_FROM_PID(processID)->ipcInfo->pool.kvaddr, ptr, size);
414 415
    return ptr;
}
416
///释放一个IPC节点
417 418 419
LITE_OS_SEC_TEXT STATIC UINT32 LiteIpcNodeFree(UINT32 processID, VOID *buf)
{
    PRINT_INFO("LiteIpcNodeFree pid:%d, pool:%x buf:%x\n",
420 421
               processID, OS_PCB_FROM_PID(processID)->ipcInfo->pool.kvaddr, buf);
    return LOS_MemFree(OS_PCB_FROM_PID(processID)->ipcInfo->pool.kvaddr, buf);
422
}
423
///是否是IPC节点
424 425 426 427
LITE_OS_SEC_TEXT STATIC BOOL IsIpcNode(UINT32 processID, const VOID *buf)
{
    IpcUsedNode *node = NULL;
    UINT32 intSave;
428
    ProcIpcInfo *ipcInfo = OS_PCB_FROM_PID(processID)->ipcInfo;
429
    IPC_LOCK(intSave);
430
    LOS_DL_LIST_FOR_EACH_ENTRY(node, &ipcInfo->ipcUsedNodelist, IpcUsedNode, list) {
431 432 433 434 435 436 437 438 439 440
        if (node->ptr == buf) {
            LOS_ListDelete(&node->list);
            IPC_UNLOCK(intSave);
            free(node);
            return TRUE;
        }
    }
    IPC_UNLOCK(intSave);
    return FALSE;
}
441
///获得IPC用户空间地址
442 443
LITE_OS_SEC_TEXT STATIC INTPTR GetIpcUserAddr(UINT32 processID, INTPTR kernelAddr)
{
444
    IpcPool pool = OS_PCB_FROM_PID(processID)->ipcInfo->pool;
445 446 447
    INTPTR offset = (INTPTR)(pool.uvaddr) - (INTPTR)(pool.kvaddr);
    return kernelAddr + offset;
}
448
///获得IPC内核空间地址
449 450
LITE_OS_SEC_TEXT STATIC INTPTR GetIpcKernelAddr(UINT32 processID, INTPTR userAddr)
{
451
    IpcPool pool = OS_PCB_FROM_PID(processID)->ipcInfo->pool;
452 453 454 455 456 457 458 459
    INTPTR offset = (INTPTR)(pool.uvaddr) - (INTPTR)(pool.kvaddr);
    return userAddr - offset;
}

LITE_OS_SEC_TEXT STATIC UINT32 CheckUsedBuffer(const VOID *node, IpcListNode **outPtr)
{
    VOID *ptr = NULL;
    LosProcessCB *pcb = OsCurrProcessGet();
460
    IpcPool pool = pcb->ipcInfo->pool;
461 462 463 464 465 466 467 468 469 470 471
    if ((node == NULL) || ((INTPTR)node < (INTPTR)(pool.uvaddr)) ||
        ((INTPTR)node > (INTPTR)(pool.uvaddr) + pool.poolSize)) {
        return -EINVAL;
    }
    ptr = (VOID *)GetIpcKernelAddr(pcb->processID, (INTPTR)(node));
    if (IsIpcNode(pcb->processID, ptr) != TRUE) {
        return -EFAULT;
    }
    *outPtr = (IpcListNode *)ptr;
    return LOS_OK;
}
472
/// 获取任务ID
473 474 475 476 477
LITE_OS_SEC_TEXT STATIC UINT32 GetTid(UINT32 serviceHandle, UINT32 *taskID)
{
    if (serviceHandle >= MAX_SERVICE_NUM) {
        return -EINVAL;
    }
478
    (VOID)LOS_MuxLock(&g_serviceHandleMapMux, LOS_WAIT_FOREVER);
479
#if (USE_TASKID_AS_HANDLE == 1)
480
    *taskID = serviceHandle ? serviceHandle : g_cmsTask.taskID;
481
    (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
482 483
    return LOS_OK;
#else
484 485
    if (g_serviceHandleMap[serviceHandle].status == HANDLE_REGISTED) {//必须得是已注册
        *taskID = g_serviceHandleMap[serviceHandle].taskID;//获取已注册服务的任务ID
486
        (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
487 488
        return LOS_OK;
    }
489
    (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
490 491 492 493 494 495
    return -EINVAL;
#endif
}

LITE_OS_SEC_TEXT STATIC UINT32 GenerateServiceHandle(UINT32 taskID, HandleStatus status, UINT32 *serviceHandle)
{
496
    (VOID)LOS_MuxLock(&g_serviceHandleMapMux, LOS_WAIT_FOREVER);
497
#if (USE_TASKID_AS_HANDLE == 1)
498
    *serviceHandle = taskID ? taskID : LOS_CurTaskIDGet(); /* if taskID is 0, return curTaskID */
499 500 501
    if (*serviceHandle != g_cmsTask.taskID) {
        (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
        return LOS_OK;
502 503
    }
#else
504
    for (UINT32 i = 1; i < MAX_SERVICE_NUM; i++) {
505 506 507 508
        if (g_serviceHandleMap[i].status == HANDLE_NOT_USED) {
            g_serviceHandleMap[i].taskID = taskID;
            g_serviceHandleMap[i].status = status;
            *serviceHandle = i;
509
            (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
510 511 512
            return LOS_OK;
        }
    }
513
#endif
514 515 516 517 518 519
    (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
    return -EINVAL;
}

LITE_OS_SEC_TEXT STATIC VOID RefreshServiceHandle(UINT32 serviceHandle, UINT32 result)
{
520
#if (USE_TASKID_AS_HANDLE == 0)
521 522 523 524 525 526 527 528 529 530
    (VOID)LOS_MuxLock(&g_serviceHandleMapMux, LOS_WAIT_FOREVER);
    if ((result == LOS_OK) && (g_serviceHandleMap[serviceHandle].status == HANDLE_REGISTING)) {
        g_serviceHandleMap[serviceHandle].status = HANDLE_REGISTED;
    } else {
        g_serviceHandleMap[serviceHandle].status = HANDLE_NOT_USED;
    }
    (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
#endif
}

531 532 533 534 535 536 537 538 539
/*!
 * @brief AddServiceAccess	配置访问权限
 *
 * @param serviceHandle	
 * @param taskID	
 * @return	
 *
 * @see
 */
540 541 542
LITE_OS_SEC_TEXT STATIC UINT32 AddServiceAccess(UINT32 taskID, UINT32 serviceHandle)
{
    UINT32 serviceTid = 0;
543
    UINT32 ret = GetTid(serviceHandle, &serviceTid);//通过服务获取所在任务
544
    if (ret != LOS_OK) {
545
        PRINT_ERR("Liteipc AddServiceAccess GetTid failed\n");
546 547
        return ret;
    }
548
    LosTaskCB *tcb = OS_TCB_FROM_TID(serviceTid);
549
    UINT32 processID = OS_TCB_FROM_TID(taskID)->processID;
550 551 552 553 554
    LosProcessCB *pcb = OS_PCB_FROM_PID(processID);
    if ((tcb->ipcTaskInfo == NULL) || (pcb->ipcInfo == NULL)) {
        PRINT_ERR("Liteipc AddServiceAccess ipc not create! pid %u tid %u\n", processID, tcb->taskID);
        return -EINVAL;
    }
555 556
    tcb->ipcTaskInfo->accessMap[processID] = TRUE;//允许任务给进程发送IPC消息,此处为任务所在的进程
    pcb->ipcInfo->access[serviceTid] = TRUE;//允许进程访问任务
557 558
    return LOS_OK;
}
559
/// 参数服务是否有访问当前进程的权限,实际中会有 A进程的任务去给B进程发送IPC信息,所以需要鉴权 
560 561 562
LITE_OS_SEC_TEXT STATIC BOOL HasServiceAccess(UINT32 serviceHandle)
{
    UINT32 serviceTid = 0;
563
    UINT32 curProcessID = LOS_GetCurrProcessID();//获取当前进程ID
564 565 566 567 568 569 570
    UINT32 ret;
    if (serviceHandle >= MAX_SERVICE_NUM) {
        return FALSE;
    }
    if (serviceHandle == 0) {
        return TRUE;
    }
571
    ret = GetTid(serviceHandle, &serviceTid);//获取参数服务所属任务ID
572
    if (ret != LOS_OK) {
573
        PRINT_ERR("Liteipc HasServiceAccess GetTid failed\n");
574 575
        return FALSE;
    }
576
    if (OS_TCB_FROM_TID(serviceTid)->processID == curProcessID) {//如果任务所在进程就是当前进程,直接返回OK
577 578
        return TRUE;
    }
579 580 581 582 583 584

    if (OS_TCB_FROM_TID(serviceTid)->ipcTaskInfo == NULL) {
        return FALSE;
    }

    return OS_TCB_FROM_TID(serviceTid)->ipcTaskInfo->accessMap[curProcessID];
585
}
586
///设置ipc任务ID
587 588
LITE_OS_SEC_TEXT STATIC UINT32 SetIpcTask(VOID)
{
589 590
    if (OsCurrProcessGet()->ipcInfo->ipcTaskID == INVAILD_ID) { //未设置时
        OsCurrProcessGet()->ipcInfo->ipcTaskID = LOS_CurTaskIDGet();//当前任务
591
        return OsCurrProcessGet()->ipcInfo->ipcTaskID;
592
    }
593
    PRINT_ERR("Liteipc curprocess %d IpcTask already set!\n", OsCurrProcessGet()->processID);
594 595
    return -EINVAL;
}
596
///是否设置ipc任务ID
597 598
LITE_OS_SEC_TEXT BOOL IsIpcTaskSet(VOID)
{
599
    if (OsCurrProcessGet()->ipcInfo->ipcTaskID == INVAILD_ID) {
600 601 602 603
        return FALSE;
    }
    return TRUE;
}
604
/// 获取IPC任务ID
605 606
LITE_OS_SEC_TEXT STATIC UINT32 GetIpcTaskID(UINT32 processID, UINT32 *ipcTaskID)
{
607
    if (OS_PCB_FROM_PID(processID)->ipcInfo->ipcTaskID == INVAILD_ID) {
608 609
        return LOS_NOK;
    }
610
    *ipcTaskID = OS_PCB_FROM_PID(processID)->ipcInfo->ipcTaskID;
611 612
    return LOS_OK;
}
613
/// 发送死亡消息
614 615 616 617 618 619
LITE_OS_SEC_TEXT STATIC UINT32 SendDeathMsg(UINT32 processID, UINT32 serviceHandle)
{
    UINT32 ipcTaskID;
    UINT32 ret;
    IpcContent content;
    IpcMsg msg;
620
    LosProcessCB *pcb = OS_PCB_FROM_PID(processID);
621

622 623 624 625 626
    if (pcb->ipcInfo == NULL) {
        return -EINVAL;
    }

    pcb->ipcInfo->access[serviceHandle] = FALSE;
627 628 629 630 631 632 633 634 635 636 637 638 639 640

    ret = GetIpcTaskID(processID, &ipcTaskID);
    if (ret != LOS_OK) {
        return -EINVAL;
    }
    content.flag = SEND;
    content.outMsg = &msg;
    memset_s(content.outMsg, sizeof(IpcMsg), 0, sizeof(IpcMsg));
    content.outMsg->type = MT_DEATH_NOTIFY;
    content.outMsg->target.handle = ipcTaskID;
    content.outMsg->target.token = serviceHandle;
    content.outMsg->code = 0;
    return LiteIpcWrite(&content);
}
641
/// 删除指定的Service
642
LITE_OS_SEC_TEXT VOID LiteIpcRemoveServiceHandle(UINT32 taskID)
643 644
{
    UINT32 j;
645 646 647 648 649 650
    LosTaskCB *taskCB = OS_TCB_FROM_TID(taskID);
    IpcTaskInfo *ipcTaskInfo = taskCB->ipcTaskInfo;
    if (ipcTaskInfo == NULL) {
        return;
    }

651
#if (USE_TASKID_AS_HANDLE == 1)
652 653 654 655 656 657 658

    UINT32 intSave;
    LOS_DL_LIST *listHead = NULL;
    LOS_DL_LIST *listNode = NULL;
    IpcListNode *node = NULL;
    UINT32 processID = taskCB->processID;

659
    listHead = &(ipcTaskInfo->msgListHead);
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
    do {
        SCHEDULER_LOCK(intSave);
        if (LOS_ListEmpty(listHead)) {
            SCHEDULER_UNLOCK(intSave);
            break;
        } else {
            listNode = LOS_DL_LIST_FIRST(listHead);
            LOS_ListDelete(listNode);
            node = LOS_DL_LIST_ENTRY(listNode, IpcListNode, listNode);
            SCHEDULER_UNLOCK(intSave);
            (VOID)HandleSpecialObjects(taskCB->taskID, node, TRUE);
            (VOID)LiteIpcNodeFree(processID, (VOID *)node);
        }
    } while (1);

675
    ipcTaskInfo->accessMap[processID] = FALSE;
676
    for (j = 0; j < MAX_SERVICE_NUM; j++) {
677 678
        if (ipcTaskInfo->accessMap[j] == TRUE) {
            ipcTaskInfo->accessMap[j] = FALSE;
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
            (VOID)SendDeathMsg(j, taskCB->taskID);
        }
    }
#else
    (VOID)LOS_MuxLock(&g_serviceHandleMapMux, LOS_WAIT_FOREVER);
    for (UINT32 i = 1; i < MAX_SERVICE_NUM; i++) {
        if ((g_serviceHandleMap[i].status != HANDLE_NOT_USED) && (g_serviceHandleMap[i].taskID == taskCB->taskID)) {
            g_serviceHandleMap[i].status = HANDLE_NOT_USED;
            g_serviceHandleMap[i].taskID = INVAILD_ID;
            break;
        }
    }
    (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
    /* run deathHandler */
    if (i < MAX_SERVICE_NUM) {
        for (j = 0; j < MAX_SERVICE_NUM; j++) {
695
            if (ipcTaskInfo->accessMap[j] == TRUE) {
696 697 698 699 700
                (VOID)SendDeathMsg(j, i);
            }
        }
    }
#endif
701 702 703

    (VOID)LOS_MemFree(m_aucSysMem1, ipcTaskInfo);
    taskCB->ipcTaskInfo = NULL;
704 705 706 707 708 709 710 711
}

LITE_OS_SEC_TEXT STATIC UINT32 SetCms(UINTPTR maxMsgSize)
{
    if (maxMsgSize < sizeof(IpcMsg)) {
        return -EINVAL;
    }
    (VOID)LOS_MuxLock(&g_serviceHandleMapMux, LOS_WAIT_FOREVER);
712
#if (USE_TASKID_AS_HANDLE == 1)
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    if (g_cmsTask.status == HANDLE_NOT_USED) {
        g_cmsTask.status = HANDLE_REGISTED;
        g_cmsTask.taskID = LOS_CurTaskIDGet();
        g_cmsTask.maxMsgSize = maxMsgSize;
        (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
        return LOS_OK;
    }
#else
    if (g_serviceHandleMap[0].status == HANDLE_NOT_USED) {
        g_serviceHandleMap[0].status = HANDLE_REGISTED;
        g_serviceHandleMap[0].taskID = LOS_CurTaskIDGet();
        (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
        return LOS_OK;
    }
#endif
    (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
    return -EEXIST;
}
731
///是否注册了CMS服务
732 733
LITE_OS_SEC_TEXT STATIC BOOL IsCmsSet(VOID)
{
734 735
    BOOL ret;
    (VOID)LOS_MuxLock(&g_serviceHandleMapMux, LOS_WAIT_FOREVER);
736
#if (USE_TASKID_AS_HANDLE == 1)
737
    ret = g_cmsTask.status == HANDLE_REGISTED;
738
#else
739
    ret = g_serviceHandleMap[0].status == HANDLE_REGISTED;
740
#endif
741 742
    (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
    return ret;
743 744 745 746
}

LITE_OS_SEC_TEXT STATIC BOOL IsCmsTask(UINT32 taskID)
{
747 748
    BOOL ret;
    (VOID)LOS_MuxLock(&g_serviceHandleMapMux, LOS_WAIT_FOREVER);
749
#if (USE_TASKID_AS_HANDLE == 1)
750
    ret = IsCmsSet() ? (OS_TCB_FROM_TID(taskID)->processID == OS_TCB_FROM_TID(g_cmsTask.taskID)->processID) : FALSE;
751
#else
752
    ret = IsCmsSet() ? (OS_TCB_FROM_TID(taskID)->processID ==
753 754
        OS_TCB_FROM_TID(g_serviceHandleMap[0].taskID)->processID) : FALSE;
#endif
755 756
    (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
    return ret;
757
}
758
/// 任务是否活跃
759 760 761
LITE_OS_SEC_TEXT STATIC BOOL IsTaskAlive(UINT32 taskID)
{
    LosTaskCB *tcb = NULL;
762
    if (OS_TID_CHECK_INVALID(taskID)) { //检查是否存在
763 764
        return FALSE;
    }
765 766
    tcb = OS_TCB_FROM_TID(taskID); //获取任务控制块
    if (!OsProcessIsUserMode(OS_PCB_FROM_PID(tcb->processID))) {//判断是否为用户进程
767 768
        return FALSE;
    }
769
    if (OsTaskIsInactive(tcb)) {//任务是否活跃
770 771 772 773
        return FALSE;
    }
    return TRUE;
}
774
/// 按句柄方式处理, 参数 processID 往往不是当前进程
775
LITE_OS_SEC_TEXT STATIC UINT32 HandleFd(UINT32 processID, SpecialObj *obj, BOOL isRollback)
776
{
777
    int ret;
778 779 780
    if (isRollback == FALSE) { // 不回滚
        ret = CopyFdToProc(obj->content.fd, processID);//两个不同进程fd都指向同一个系统fd
        if (ret < 0) {//返回 processID 的 新 fd
781 782
            return ret;
        }
783 784
        obj->content.fd = ret; // 记录 processID 的新FD, 可用于回滚
    } else {// 回滚时关闭进程FD
785 786 787 788 789 790
        ret = CloseProcFd(obj->content.fd, processID);
        if (ret < 0) {
            return ret;
        }
    }

791 792
    return LOS_OK;
}
793
/// 按指针方式处理
794 795 796 797 798 799 800 801
LITE_OS_SEC_TEXT STATIC UINT32 HandlePtr(UINT32 processID, SpecialObj *obj, BOOL isRollback)
{
    VOID *buf = NULL;
    UINT32 ret;
    if ((obj->content.ptr.buff == NULL) || (obj->content.ptr.buffSz == 0)) {
        return -EINVAL;
    }
    if (isRollback == FALSE) {
802 803
        if (LOS_IsUserAddress((vaddr_t)(UINTPTR)(obj->content.ptr.buff)) == FALSE) { // 判断是否为用户空间地址
            PRINT_ERR("Liteipc Bad ptr address\n"); //不在用户空间时
804 805
            return -EINVAL;
        }
806
        buf = LiteIpcNodeAlloc(processID, obj->content.ptr.buffSz);//在内核空间分配内存
807
        if (buf == NULL) {
808
            PRINT_ERR("Liteipc DealPtr alloc mem failed\n");
809 810
            return -EINVAL;
        }
811
        ret = copy_from_user(buf, obj->content.ptr.buff, obj->content.ptr.buffSz);//从用户空间拷贝数据到内核空间
812 813 814 815
        if (ret != LOS_OK) {
            LiteIpcNodeFree(processID, buf);
            return ret;
        }
816 817
        obj->content.ptr.buff = (VOID *)GetIpcUserAddr(processID, (INTPTR)buf);//获取进程 processID 的用户空间地址
        EnableIpcNodeFreeByUser(processID, (VOID *)buf);//创建一个IPC节点,挂到已读取链表上
818
    } else {
819
        (VOID)LiteIpcNodeFree(processID, (VOID *)GetIpcKernelAddr(processID, (INTPTR)obj->content.ptr.buff));//在内核空间释放IPC节点
820 821 822
    }
    return LOS_OK;
}
823
/// 按服务的方式处理
824 825 826 827 828
LITE_OS_SEC_TEXT STATIC UINT32 HandleSvc(UINT32 dstTid, const SpecialObj *obj, BOOL isRollback)
{
    UINT32 taskID = 0;
    if (isRollback == FALSE) {
        if (IsTaskAlive(obj->content.svc.handle) == FALSE) {
829
            PRINT_ERR("Liteipc HandleSvc wrong svctid\n");
830 831 832
            return -EINVAL;
        }
        if (HasServiceAccess(obj->content.svc.handle) == FALSE) {
833
            PRINT_ERR("Liteipc %s, %d\n", __FUNCTION__, __LINE__);
834 835 836
            return -EACCES;
        }
        if (GetTid(obj->content.svc.handle, &taskID) == 0) {
837
            if (taskID == OS_PCB_FROM_PID(OS_TCB_FROM_TID(taskID)->processID)->ipcInfo->ipcTaskID) {
838 839 840 841 842 843
                AddServiceAccess(dstTid, obj->content.svc.handle);
            }
        }
    }
    return LOS_OK;
}
844
/// 创建处理对象
845 846 847
LITE_OS_SEC_TEXT STATIC UINT32 HandleObj(UINT32 dstTid, SpecialObj *obj, BOOL isRollback)
{
    UINT32 ret;
848
    UINT32 processID = OS_TCB_FROM_TID(dstTid)->processID;//获取目标任务所在进程
849
    switch (obj->type) {
850
        case OBJ_FD://fd:文件描述符
851
            ret = HandleFd(processID, obj, isRollback);
852
            break;
853
        case OBJ_PTR://指针方式
854 855
            ret = HandlePtr(processID, obj, isRollback);
            break;
856
        case OBJ_SVC://服务方式
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
            ret = HandleSvc(dstTid, (const SpecialObj *)obj, isRollback);
            break;
        default:
            ret = -EINVAL;
            break;
    }
    return ret;
}

LITE_OS_SEC_TEXT STATIC UINT32 HandleSpecialObjects(UINT32 dstTid, IpcListNode *node, BOOL isRollback)
{
    UINT32 ret = LOS_OK;
    IpcMsg *msg = &(node->msg);
    INT32 i;
    SpecialObj *obj = NULL;
    UINT32 *offset = (UINT32 *)(UINTPTR)(msg->offsets);
    if (isRollback) {
        i = msg->spObjNum;
        goto EXIT;
    }
    for (i = 0; i < msg->spObjNum; i++) {
        if (offset[i] > msg->dataSz - sizeof(SpecialObj)) {
            ret = -EINVAL;
            goto EXIT;
        }
        if ((i > 0) && (offset[i] < offset[i - 1] + sizeof(SpecialObj))) {
            ret = -EINVAL;
            goto EXIT;
        }
        obj = (SpecialObj *)((UINTPTR)msg->data + offset[i]);
        if (obj == NULL) {
            ret = -EINVAL;
            goto EXIT;
        }
        ret = HandleObj(dstTid, obj, FALSE);
        if (ret != LOS_OK) {
            goto EXIT;
        }
    }
    return LOS_OK;
EXIT:
    for (i--; i >= 0; i--) {
        obj = (SpecialObj *)((UINTPTR)msg->data + offset[i]);
        (VOID)HandleObj(dstTid, obj, TRUE);
    }
    return ret;
}

LITE_OS_SEC_TEXT STATIC UINT32 CheckMsgSize(IpcMsg *msg)
{
    UINT64 totalSize;
    UINT32 i;
    UINT32 *offset = (UINT32 *)(UINTPTR)(msg->offsets);
    SpecialObj *obj = NULL;
    if (msg->target.handle != 0) {
        return LOS_OK;
    }
    /* msg send to cms, check the msg size */
    totalSize = (UINT64)sizeof(IpcMsg) + msg->dataSz + msg->spObjNum * sizeof(UINT32);
    for (i = 0; i < msg->spObjNum; i++) {
        if (offset[i] > msg->dataSz - sizeof(SpecialObj)) {
            return -EINVAL;
        }
        if ((i > 0) && (offset[i] < offset[i - 1] + sizeof(SpecialObj))) {
            return -EINVAL;
        }
        obj = (SpecialObj *)((UINTPTR)msg->data + offset[i]);
        if (obj == NULL) {
            return -EINVAL;
        }
        if (obj->type == OBJ_PTR) {
            totalSize += obj->content.ptr.buffSz;
        }
    }
931
    (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
932
    if (totalSize > g_cmsTask.maxMsgSize) {
933
        (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
934 935
        return -EINVAL;
    }
936
    (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
    return LOS_OK;
}

LITE_OS_SEC_TEXT STATIC UINT32 CopyDataFromUser(IpcListNode *node, UINT32 bufSz, const IpcMsg *msg)
{
    UINT32 ret;
    ret = (UINT32)memcpy_s((VOID *)(&node->msg), bufSz - sizeof(LOS_DL_LIST), (const VOID *)msg, sizeof(IpcMsg));
    if (ret != LOS_OK) {
        PRINT_DEBUG("%s, %d, %u\n", __FUNCTION__, __LINE__, ret);
        return ret;
    }

    if (msg->dataSz) {
        node->msg.data = (VOID *)((UINTPTR)node + sizeof(IpcListNode));
        ret = copy_from_user((VOID *)(node->msg.data), msg->data, msg->dataSz);
        if (ret != LOS_OK) {
            PRINT_DEBUG("%s, %d\n", __FUNCTION__, __LINE__);
            return ret;
        }
    } else {
        node->msg.data = NULL;
    }

    if (msg->spObjNum) {
        node->msg.offsets = (VOID *)((UINTPTR)node + sizeof(IpcListNode) + msg->dataSz);
        ret = copy_from_user((VOID *)(node->msg.offsets), msg->offsets, msg->spObjNum * sizeof(UINT32));
        if (ret != LOS_OK) {
            PRINT_DEBUG("%s, %d, %x, %x, %d\n", __FUNCTION__, __LINE__, node->msg.offsets, msg->offsets, msg->spObjNum);
            return ret;
        }
    } else {
        node->msg.offsets = NULL;
    }
    ret = CheckMsgSize(&node->msg);
    if (ret != LOS_OK) {
        PRINT_DEBUG("%s, %d\n", __FUNCTION__, __LINE__);
        return ret;
    }
    node->msg.taskID = LOS_CurTaskIDGet();
    node->msg.processID = OsCurrProcessGet()->processID;
#ifdef LOSCFG_SECURITY_CAPABILITY
    node->msg.userID = OsCurrProcessGet()->user->userID;
    node->msg.gid = OsCurrProcessGet()->user->gid;
#endif
    return LOS_OK;
}

984
LITE_OS_SEC_TEXT STATIC BOOL IsValidReply(const IpcContent *content)
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
{
    UINT32 curProcessID = LOS_GetCurrProcessID();
    IpcListNode *node = (IpcListNode *)GetIpcKernelAddr(curProcessID, (INTPTR)(content->buffToFree));
    IpcMsg *requestMsg = &node->msg;
    IpcMsg *replyMsg = content->outMsg;
    UINT32 reqDstTid = 0;
    /* Check whether the reply matches the request */
    if ((requestMsg->type != MT_REQUEST)  ||
        (requestMsg->flag == LITEIPC_FLAG_ONEWAY) ||
        (replyMsg->timestamp != requestMsg->timestamp) ||
        (replyMsg->target.handle != requestMsg->taskID) ||
        (GetTid(requestMsg->target.handle, &reqDstTid) != 0) ||
        (OS_TCB_FROM_TID(reqDstTid)->processID != curProcessID)) {
        return FALSE;
    }
    return TRUE;
}

LITE_OS_SEC_TEXT STATIC UINT32 CheckPara(IpcContent *content, UINT32 *dstTid)
{
    UINT32 ret;
    IpcMsg *msg = content->outMsg;
    UINT32 flag = content->flag;
1008
#if (USE_TIMESTAMP == 1)
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    UINT64 now = LOS_CurrNanosec();
#endif
    if (((msg->dataSz > 0) && (msg->data == NULL)) ||
        ((msg->spObjNum > 0) && (msg->offsets == NULL)) ||
        (msg->dataSz > IPC_MSG_DATA_SZ_MAX) ||
        (msg->spObjNum > IPC_MSG_OBJECT_NUM_MAX) ||
        (msg->dataSz < msg->spObjNum * sizeof(SpecialObj))) {
        return -EINVAL;
    }
    switch (msg->type) {
        case MT_REQUEST:
            if (HasServiceAccess(msg->target.handle)) {
                ret = GetTid(msg->target.handle, dstTid);
                if (ret != LOS_OK) {
                    return -EINVAL;
                }
            } else {
1026
                PRINT_ERR("Liteipc %s, %d\n", __FUNCTION__, __LINE__);
1027 1028
                return -EACCES;
            }
1029
#if (USE_TIMESTAMP == 1)
1030 1031 1032 1033 1034 1035 1036 1037
            msg->timestamp = now;
#endif
            break;
        case MT_REPLY:
        case MT_FAILED_REPLY:
            if ((flag & BUFF_FREE) != BUFF_FREE) {
                return -EINVAL;
            }
1038
            if (!IsValidReply(content)) {
1039 1040
                return -EINVAL;
            }
1041
#if (USE_TIMESTAMP == 1)
1042
            if (now > msg->timestamp + LITEIPC_TIMEOUT_NS) {
1043 1044 1045 1046 1047
#ifdef LOSCFG_KERNEL_HOOK
                ret = GetTid(msg->target.handle, dstTid);
                if (ret != LOS_OK) {
                    *dstTid = INVAILD_ID;
                }
1048
#endif
1049 1050
                OsHookCall(LOS_HOOK_TYPE_IPC_WRITE_DROP, msg, *dstTid,
                 (*dstTid == INVAILD_ID) ? INVAILD_ID : OS_TCB_FROM_TID(*dstTid)->processID, 0);
1051
                PRINT_ERR("Liteipc A timeout reply, request timestamp:%lld, now:%lld\n", msg->timestamp, now);
1052 1053 1054 1055 1056 1057 1058
                return -ETIME;
            }
#endif
            *dstTid = msg->target.handle;
            break;
        case MT_DEATH_NOTIFY:
            *dstTid = msg->target.handle;
1059
#if (USE_TIMESTAMP == 1)
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
            msg->timestamp = now;
#endif
            break;
        default:
            PRINT_DEBUG("Unknow msg type:%d\n", msg->type);
            return -EINVAL;
    }

    if (IsTaskAlive(*dstTid) == FALSE) {
        return -EINVAL;
    }
    return LOS_OK;
}
1073
///写IPC消息队列
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
LITE_OS_SEC_TEXT STATIC UINT32 LiteIpcWrite(IpcContent *content)
{
    UINT32 ret, intSave;
    UINT32 dstTid;

    IpcMsg *msg = content->outMsg;

    ret = CheckPara(content, &dstTid);
    if (ret != LOS_OK) {
        return ret;
    }

1086 1087 1088 1089 1090 1091 1092
    LosTaskCB *tcb = OS_TCB_FROM_TID(dstTid);
    LosProcessCB *pcb = OS_PCB_FROM_PID(tcb->processID);
    if (pcb->ipcInfo == NULL) {
        PRINT_ERR("pid %u Liteipc not create\n", tcb->processID);
        return -EINVAL;
    }

1093
    UINT32 bufSz = sizeof(IpcListNode) + msg->dataSz + msg->spObjNum * sizeof(UINT32);
1094
    IpcListNode *buf = (IpcListNode *)LiteIpcNodeAlloc(tcb->processID, bufSz);
1095 1096 1097 1098 1099 1100 1101 1102 1103
    if (buf == NULL) {
        PRINT_ERR("%s, %d\n", __FUNCTION__, __LINE__);
        return -ENOMEM;
    }
    ret = CopyDataFromUser(buf, bufSz, (const IpcMsg *)msg);
    if (ret != LOS_OK) {
        PRINT_ERR("%s, %d\n", __FUNCTION__, __LINE__);
        goto ERROR_COPY;
    }
1104 1105 1106 1107 1108

    if (tcb->ipcTaskInfo == NULL) {
        tcb->ipcTaskInfo = LiteIpcTaskInit();
    }

1109 1110 1111 1112 1113
    ret = HandleSpecialObjects(dstTid, buf, FALSE);
    if (ret != LOS_OK) {
        PRINT_ERR("%s, %d\n", __FUNCTION__, __LINE__);
        goto ERROR_COPY;
    }
1114
    /* add data to list and wake up dest task *///向列表添加数据并唤醒目标任务
1115
    SCHEDULER_LOCK(intSave);
1116
    LOS_ListTailInsert(&(tcb->ipcTaskInfo->msgListHead), &(buf->listNode));
1117 1118
    OsHookCall(LOS_HOOK_TYPE_IPC_WRITE, &buf->msg, dstTid, tcb->processID, tcb->waitFlag);
    if (tcb->waitFlag == OS_TASK_WAIT_LITEIPC) {
1119 1120
        OsTaskWakeClearPendMask(tcb);
        OsSchedTaskWake(tcb);
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
        SCHEDULER_UNLOCK(intSave);
        LOS_MpSchedule(OS_MP_CPU_ALL);
        LOS_Schedule();
    } else {
        SCHEDULER_UNLOCK(intSave);
    }
    return LOS_OK;
ERROR_COPY:
    LiteIpcNodeFree(OS_TCB_FROM_TID(dstTid)->processID, buf);
    return ret;
}

LITE_OS_SEC_TEXT STATIC UINT32 CheckRecievedMsg(IpcListNode *node, IpcContent *content, LosTaskCB *tcb)
{
    UINT32 ret = LOS_OK;
    if (node == NULL) {
        return -EINVAL;
    }
    switch (node->msg.type) {
        case MT_REQUEST:
            if ((content->flag & SEND) == SEND) {
                PRINT_ERR("%s, %d\n", __FUNCTION__, __LINE__);
                ret = -EINVAL;
            }
            break;
        case MT_FAILED_REPLY:
            ret = -ENOENT;
            /* fall-through */
        case MT_REPLY:
            if ((content->flag & SEND) != SEND) {
                PRINT_ERR("%s, %d\n", __FUNCTION__, __LINE__);
                ret = -EINVAL;
            }
1154
#if (USE_TIMESTAMP == 1)
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
            if (node->msg.timestamp != content->outMsg->timestamp) {
                PRINT_ERR("Recieve a unmatch reply, drop it\n");
                ret = -EINVAL;
            }
#else
            if ((node->msg.code != content->outMsg->code) ||
                (node->msg.target.token != content->outMsg->target.token)) {
                PRINT_ERR("Recieve a unmatch reply, drop it\n");
                ret = -EINVAL;
            }
#endif
            break;
        case MT_DEATH_NOTIFY:
            break;
        default:
            PRINT_ERR("Unknow msg type:%d\n", node->msg.type);
            ret =  -EINVAL;
    }
    if (ret != LOS_OK) {
1174
        OsHookCall(LOS_HOOK_TYPE_IPC_READ_DROP, &node->msg, tcb->waitFlag);
1175 1176 1177
        (VOID)HandleSpecialObjects(LOS_CurTaskIDGet(), node, TRUE);
        (VOID)LiteIpcNodeFree(LOS_GetCurrProcessID(), (VOID *)node);
    } else {
1178
        OsHookCall(LOS_HOOK_TYPE_IPC_READ, &node->msg, tcb->waitFlag);
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
    }
    return ret;
}

LITE_OS_SEC_TEXT STATIC UINT32 LiteIpcRead(IpcContent *content)
{
    UINT32 intSave, ret;
    UINT32 selfTid = LOS_CurTaskIDGet();
    LOS_DL_LIST *listHead = NULL;
    LOS_DL_LIST *listNode = NULL;
    IpcListNode *node = NULL;
    UINT32 syncFlag = (content->flag & SEND) && (content->flag & RECV);
    UINT32 timeout = syncFlag ? LOS_MS2Tick(LITEIPC_TIMEOUT_MS) : LOS_WAIT_FOREVER;

    LosTaskCB *tcb = OS_TCB_FROM_TID(selfTid);
1194 1195 1196 1197 1198
    if (tcb->ipcTaskInfo == NULL) {
        tcb->ipcTaskInfo = LiteIpcTaskInit();
    }

    listHead = &(tcb->ipcTaskInfo->msgListHead);
1199 1200 1201
    do {
        SCHEDULER_LOCK(intSave);
        if (LOS_ListEmpty(listHead)) {
1202
            OsTaskWaitSetPendMask(OS_TASK_WAIT_LITEIPC, OS_INVALID_VALUE, timeout);
1203
            OsHookCall(LOS_HOOK_TYPE_IPC_TRY_READ, syncFlag ? MT_REPLY : MT_REQUEST, tcb->waitFlag);
1204
            ret = OsSchedTaskWait(&g_ipcPendlist, timeout, TRUE);
1205
            if (ret == LOS_ERRNO_TSK_TIMEOUT) {
1206
                OsHookCall(LOS_HOOK_TYPE_IPC_READ_TIMEOUT, syncFlag ? MT_REPLY : MT_REQUEST, tcb->waitFlag);
1207 1208 1209 1210
                SCHEDULER_UNLOCK(intSave);
                return -ETIME;
            }

1211
            if (OsTaskIsKilled(tcb)) {
1212
                OsHookCall(LOS_HOOK_TYPE_IPC_KILL, syncFlag ? MT_REPLY : MT_REQUEST, tcb->waitFlag);
1213 1214 1215 1216
                SCHEDULER_UNLOCK(intSave);
                return -ERFKILL;
            }

1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
            SCHEDULER_UNLOCK(intSave);
        } else {
            listNode = LOS_DL_LIST_FIRST(listHead);
            LOS_ListDelete(listNode);
            node = LOS_DL_LIST_ENTRY(listNode, IpcListNode, listNode);
            SCHEDULER_UNLOCK(intSave);
            ret = CheckRecievedMsg(node, content, tcb);
            if (ret == LOS_OK) {
                break;
            }
            if (ret == -ENOENT) { /* It means that we've recieved a failed reply */
                return ret;
            }
        }
    } while (1);
    node->msg.data = (VOID *)GetIpcUserAddr(LOS_GetCurrProcessID(), (INTPTR)(node->msg.data));
    node->msg.offsets = (VOID *)GetIpcUserAddr(LOS_GetCurrProcessID(), (INTPTR)(node->msg.offsets));
    content->inMsg = (VOID *)GetIpcUserAddr(LOS_GetCurrProcessID(), (INTPTR)(&(node->msg)));
    EnableIpcNodeFreeByUser(LOS_GetCurrProcessID(), (VOID *)node);
    return LOS_OK;
}

LITE_OS_SEC_TEXT STATIC UINT32 LiteIpcMsgHandle(IpcContent *con)
{
    UINT32 ret = LOS_OK;
    IpcContent localContent;
    IpcContent *content = &localContent;
    IpcMsg localMsg;
    IpcMsg *msg = &localMsg;
    IpcListNode *nodeNeedFree = NULL;

    if (copy_from_user((void *)content, (const void *)con, sizeof(IpcContent)) != LOS_OK) {
        PRINT_ERR("%s, %d\n", __FUNCTION__, __LINE__);
        return -EINVAL;
    }

    if ((content->flag & BUFF_FREE) == BUFF_FREE) {
        ret = CheckUsedBuffer(content->buffToFree, &nodeNeedFree);
        if (ret != LOS_OK) {
            PRINT_ERR("CheckUsedBuffer failed:%d\n", ret);
            return ret;
        }
    }

    if ((content->flag & SEND) == SEND) {
        if (content->outMsg == NULL) {
            PRINT_ERR("content->outmsg is null\n");
            ret = -EINVAL;
            goto BUFFER_FREE;
        }
        if (copy_from_user((void *)msg, (const void *)content->outMsg, sizeof(IpcMsg)) != LOS_OK) {
            PRINT_ERR("%s, %d\n", __FUNCTION__, __LINE__);
            ret = -EINVAL;
            goto BUFFER_FREE;
        }
        content->outMsg = msg;
        if ((content->outMsg->type < 0) || (content->outMsg->type >= MT_DEATH_NOTIFY)) {
            PRINT_ERR("LiteIpc unknow msg type:%d\n", content->outMsg->type);
            ret = -EINVAL;
            goto BUFFER_FREE;
        }
        ret = LiteIpcWrite(content);
        if (ret != LOS_OK) {
            PRINT_ERR("LiteIpcWrite failed\n");
            goto BUFFER_FREE;
        }
    }
BUFFER_FREE:
    if (nodeNeedFree != NULL) {
        UINT32 freeRet = LiteIpcNodeFree(LOS_GetCurrProcessID(), nodeNeedFree);
        ret = (freeRet == LOS_OK) ? ret : freeRet;
    }
    if (ret != LOS_OK) {
        return ret;
    }

    if ((content->flag & RECV) == RECV) {
        ret = LiteIpcRead(content);
        if (ret != LOS_OK) {
1296
            PRINT_ERR("LiteIpcRead failed ERROR: %d\n", (INT32)ret);
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
            return ret;
        }
        UINT32 offset = LOS_OFF_SET_OF(IpcContent, inMsg);
        ret = copy_to_user((char*)con + offset, (char*)content + offset, sizeof(IpcMsg *));
        if (ret != LOS_OK) {
            PRINT_ERR("%s, %d, %d\n", __FUNCTION__, __LINE__, ret);
            return -EINVAL;
        }
    }
    return ret;
}

LITE_OS_SEC_TEXT STATIC UINT32 HandleCmsCmd(CmsCmdContent *content)
{
    UINT32 ret = LOS_OK;
    CmsCmdContent localContent;
    if (content == NULL) {
        return -EINVAL;
    }
    if (IsCmsTask(LOS_CurTaskIDGet()) == FALSE) {
        return -EACCES;
    }
    if (copy_from_user((void *)(&localContent), (const void *)content, sizeof(CmsCmdContent)) != LOS_OK) {
        PRINT_ERR("%s, %d\n", __FUNCTION__, __LINE__);
        return -EINVAL;
    }
    switch (localContent.cmd) {
        case CMS_GEN_HANDLE:
            if ((localContent.taskID != 0) && (IsTaskAlive(localContent.taskID) == FALSE)) {
                return -EINVAL;
            }
            ret = GenerateServiceHandle(localContent.taskID, HANDLE_REGISTED, &(localContent.serviceHandle));
            if (ret == LOS_OK) {
                ret = copy_to_user((void *)content, (const void *)(&localContent), sizeof(CmsCmdContent));
            }
1332
            (VOID)LOS_MuxLock(&g_serviceHandleMapMux, LOS_WAIT_FOREVER);
1333
            AddServiceAccess(g_cmsTask.taskID, localContent.serviceHandle);
1334
            (VOID)LOS_MuxUnlock(&g_serviceHandleMapMux);
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
            break;
        case CMS_REMOVE_HANDLE:
            if (localContent.serviceHandle >= MAX_SERVICE_NUM) {
                return -EINVAL;
            }
            RefreshServiceHandle(localContent.serviceHandle, -1);
            break;
        case CMS_ADD_ACCESS:
            if (IsTaskAlive(localContent.taskID) == FALSE) {
                return -EINVAL;
            }
            return AddServiceAccess(localContent.taskID, localContent.serviceHandle);
        default:
            PRINT_DEBUG("Unknow cmd cmd:%d\n", localContent.cmd);
            return -EINVAL;
    }
    return ret;
}
1353
///设置IPC控制参数
1354
LITE_OS_SEC_TEXT int LiteIpcIoctl(struct file *filep, int cmd, unsigned long arg)
1355 1356
{
    UINT32 ret = LOS_OK;
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
    LosProcessCB *pcb = OsCurrProcessGet();
    ProcIpcInfo *ipcInfo = pcb->ipcInfo;

    if (ipcInfo == NULL) {
        PRINT_ERR("Liteipc pool not create!\n");
        return -EINVAL;
    }

    if (IsPoolMapped(ipcInfo) == FALSE) {
        PRINT_ERR("Liteipc Ipc pool not init, need to mmap first!\n");
1367 1368
        return -ENOMEM;
    }
1369

1370 1371 1372 1373 1374
    switch (cmd) {
        case IPC_SET_CMS:
            return SetCms(arg);
        case IPC_CMS_CMD:
            return HandleCmsCmd((CmsCmdContent *)(UINTPTR)arg);
1375
        case IPC_SET_IPC_THREAD://
1376
            if (IsCmsSet() == FALSE) {
1377
                PRINT_ERR("Liteipc ServiceManager not set!\n");
1378 1379 1380 1381 1382 1383 1384 1385
                return -EINVAL;
            }
            return SetIpcTask();
        case IPC_SEND_RECV_MSG:
            if (arg == 0) {
                return -EINVAL;
            }
            if (IsCmsSet() == FALSE) {
1386
                PRINT_ERR("Liteipc ServiceManager not set!\n");
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
                return -EINVAL;
            }
            ret = LiteIpcMsgHandle((IpcContent *)(UINTPTR)arg);
            if (ret != LOS_OK) {
                return ret;
            }
            break;
        default:
            PRINT_ERR("Unknow liteipc ioctl cmd:%d\n", cmd);
            return -EINVAL;
    }
    return ret;
}