1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include "chre/core/init.h"
17 
18 #include <errno.h>
19 #include <zephyr/sys/printk.h>
20 #include <zephyr/kernel.h>
21 
22 #include "chre/core/event_loop_manager.h"
23 #include "chre/core/static_nanoapps.h"
24 #include "chre/target_platform/init.h"
25 
26 namespace chre {
27 namespace zephyr {
28 namespace {
29 
30 K_THREAD_STACK_DEFINE(chre_stack_area, CONFIG_CHRE_TASK_STACK_SIZE);
31 struct k_thread chre_thread_data;
32 k_tid_t chre_tid;
33 
chreThreadEntry(void *,void *,void *)34 void chreThreadEntry(void *, void *, void *) {
35   chre::init();
36   chre::EventLoopManagerSingleton::get()->lateInit();
37   chre::loadStaticNanoapps();
38 
39   chre::EventLoopManagerSingleton::get()->getEventLoop().run();
40 
41   // we only get here if the CHRE EventLoop exited
42   chre::deinit();
43 
44   chre_tid = nullptr;
45 }
46 }  // namespace
47 
init()48 int init() {
49   static const char *thread_name = CONFIG_CHRE_TASK_NAME;
50   chre_tid = k_thread_create(&chre_thread_data, chre_stack_area,
51                              K_THREAD_STACK_SIZEOF(chre_stack_area),
52                              chreThreadEntry, nullptr, nullptr, nullptr,
53                              CONFIG_CHRE_TASK_PRIORITY, 0, K_NO_WAIT);
54 
55   if (chre_tid == nullptr) {
56     printk("Failed to create thread\n");
57     return -EINVAL;
58   }
59 
60   if (int rc = k_thread_name_set(chre_tid, thread_name); rc != 0) {
61     printk("Failed to set thread name to \"%s\": %d\n", CONFIG_CHRE_TASK_NAME,
62            rc);
63   }
64 
65 //  chpp::init();
66   return 0;
67 }
68 
deinit()69 void deinit() {
70   if (chre_tid != nullptr) {
71     chre::EventLoopManagerSingleton ::get()->getEventLoop().stop();
72   }
73 //  chpp::deinit();
74 }
75 
getChreTaskId()76 k_tid_t getChreTaskId() {
77   return chre_tid;
78 }
79 
80 }  // namespace chre::zephyr
81 
82 }  // namespace chre
83