4 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
6 * Licensed under the Apache License, Version 2.0 (the License);
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
23 #include <linux/input.h>
24 #include <libsyscommon/libgdbus.h>
25 #include <libsyscommon/list.h>
26 #include <device/power-internal.h>
28 #include "shared/devices.h"
29 #include "shared/device-notifier.h"
30 #include "shared/log.h"
31 #include "shared/common.h"
33 #include "power-suspend.h"
34 #include "power-dbus.h"
35 #include "power-boot.h"
36 #include "power-off.h"
37 #include "power-event-lock.h"
39 #define POWER_CONF_FILE "/etc/deviced/power.conf"
40 #define POWER_STATE_INDEX(state) ((state) ? 63 - __builtin_clzll(state) : 0)
41 #define DEFAULT_MAX_WAIT_SECOND 5 /* second */
42 #define MAX_DESC_LEN 256
44 static int delayed_init_done = 0;
45 static uint64_t current = POWER_STATE_START; /* current power state */
46 static int max_wait_timeout = DEFAULT_MAX_WAIT_SECOND;
47 static GQueue *transition_queue;
62 static GList *proc_list;
64 struct change_state_wait {
70 static const uint64_t transient_scenario_suspending[] = {
71 POWER_STATE_TRANSIENT_SUSPENDING_EARLY,
72 POWER_STATE_TRANSIENT_SUSPENDING,
73 POWER_STATE_TRANSIENT_SUSPENDING_LATE,
76 static const uint64_t transient_scenario_resuming[] = {
77 POWER_STATE_TRANSIENT_RESUMING_EARLY,
78 POWER_STATE_TRANSIENT_RESUMING,
79 POWER_STATE_TRANSIENT_RESUMING_LATE,
84 const uint64_t *scenario;
85 } transient[POWER_STATE_MAX_INDEX][POWER_STATE_MAX_INDEX] = {
86 [POWER_STATE_NORMAL_INDEX][POWER_STATE_SLEEP_INDEX] = {
87 .max_step = ARRAY_SIZE(transient_scenario_suspending),
88 .scenario = transient_scenario_suspending,
90 [POWER_STATE_SLEEP_INDEX][POWER_STATE_NORMAL_INDEX] = {
91 .max_step = ARRAY_SIZE(transient_scenario_resuming),
92 .scenario = transient_scenario_resuming,
96 static int transition_request_callback(void *data);
97 static void prepare_transition(const struct trans_info *ti);
98 static void action_transition(void);
99 static uint64_t get_next_state(void);
101 static void power_action_normal(void *data);
102 static void power_action_sleep(void *data);
103 static void power_action_poweroff(void *data);
104 static void (*const action_on_state[POWER_STATE_MAX_INDEX]) (void *) = {
105 [POWER_STATE_NORMAL_INDEX] = power_action_normal,
106 [POWER_STATE_SLEEP_INDEX] = power_action_sleep,
107 [POWER_STATE_POWEROFF_INDEX] = power_action_poweroff,
108 [POWER_STATE_REBOOT_INDEX] = power_action_poweroff,
109 [POWER_STATE_EXIT_INDEX] = power_action_poweroff,
112 uint64_t power_get_state(void)
117 static void cleanup_waiting_list(gpointer data)
119 struct change_state_wait *csw = (struct change_state_wait *) data;
121 _E("%s(pid=%d) hasn't confirmed id=%"PRIu64"(%s)", csw->pi->comm, csw->pi->pid, csw->id, state_name(csw->state));
123 if (kill(csw->pi->pid, 0) != 0) {
124 _E("cleanup not existing process: %s(pid=%d)", csw->pi->comm, csw->pi->pid);
125 proc_list = g_list_remove(proc_list, csw->pi);
132 static gboolean max_wait_expired_cb(void *data)
134 transition_context.max_wait_timer = 0;
136 g_list_free_full(g_steal_pointer(&transition_context.waitings), cleanup_waiting_list);
140 return G_SOURCE_REMOVE;
143 static gint find_pi_by_pid(gconstpointer data, gconstpointer udata)
145 const struct proc_info *pi = (const struct proc_info *) data;
146 const pid_t pid = *(const pid_t *) udata;
154 int add_change_state_wait(pid_t pid, guint64 state)
156 struct proc_info *pi = NULL;
159 l = g_list_find_custom(proc_list, &pid, find_pi_by_pid);
162 pi->state_bitmap |= state;
163 _D("pid=%d(%s) updated csw for %#"PRIx64, pi->pid, pi->comm, state);
167 pi = calloc(1, sizeof(struct proc_info));
172 pi->state_bitmap = state;
173 get_command(pid, pi->comm, sizeof(pi->comm));
174 proc_list = g_list_append(proc_list, pi);
176 _D("pid=%d(%s) added csw for %#"PRIx64, pid, pi->comm, state);
181 void remove_change_state_wait(pid_t pid, guint64 state)
183 struct proc_info *pi = NULL;
186 l = g_list_find_custom(proc_list, &pid, find_pi_by_pid);
195 _D("pid=%d(%s) removed csw for %#"PRIx64, pi->pid, pi->comm, state);
197 pi->state_bitmap &= ~state;
198 if (pi->state_bitmap == 0) {
199 proc_list = g_list_remove_link(proc_list, l);
200 free(g_steal_pointer(&l->data));
205 static gint find_csw_by_pid_id(gconstpointer data, gconstpointer udata)
207 const struct change_state_wait *csw = (const struct change_state_wait *) data;
208 const struct change_state_wait *target = (const struct change_state_wait *) udata;
210 if (csw->pi->pid == target->pi->pid && csw->id == target->id)
216 int confirm_change_state_wait(pid_t pid, guint64 id)
218 struct proc_info target_pi = { .pid = pid };
219 struct change_state_wait target_csw = { .pi = &target_pi, .id = id };
220 struct change_state_wait *csw = NULL;
223 l = g_list_find_custom(transition_context.waitings, &target_csw, find_csw_by_pid_id);
231 _D("pid=%d(%s) confirmed id=%"PRIu64"(%s)", csw->pi->pid, csw->pi->comm, csw->id, state_name(csw->state));
233 transition_context.waitings = g_list_remove_link(transition_context.waitings, l);
234 free(g_steal_pointer(&l->data));
238 if (g_list_length(transition_context.waitings) != 0)
241 // the last csw is cleared
242 g_source_remove(transition_context.max_wait_timer);
243 transition_context.max_wait_timer = 0;
250 static int alloc_unique_id(void)
257 static void power_action_normal(void *udata)
259 power_acquire_wakelock();
262 static void power_action_sleep(void *udata)
264 /* for POWER_STATE_NORMAL, POWER_STATE_POWEROFF, do not wake unlock */
265 if (current != POWER_STATE_SLEEP) {
266 _E("Ignore sleep wait done, current=%s", state_name(current));
270 power_release_wakelock();
273 static void power_action_poweroff(void *data)
275 // do not transition anymore after poweroff
276 unregister_notifier(DEVICE_NOTIFIER_REQUEST_TRANSITION_STATE, transition_request_callback);
278 poweroff_prepare(current, data);
279 poweroff_main((void *)(intptr_t) current);
282 static void broadcast_transition_info(void)
286 uint64_t next = get_next_state();
288 if (next == POWER_STATE_START)
289 signame = DEVICED_SIGNAL_POWER_CHANGE_STATE_TO_START;
290 else if (next == POWER_STATE_NORMAL)
291 signame = DEVICED_SIGNAL_POWER_CHANGE_STATE_TO_NORMAL;
292 else if (next == POWER_STATE_SLEEP)
293 signame = DEVICED_SIGNAL_POWER_CHANGE_STATE_TO_SLEEP;
294 else if (next == POWER_STATE_POWEROFF)
295 signame = DEVICED_SIGNAL_POWER_CHANGE_STATE_TO_POWEROFF;
296 else if (next == POWER_STATE_REBOOT)
297 signame = DEVICED_SIGNAL_POWER_CHANGE_STATE_TO_REBOOT;
298 else if (next == POWER_STATE_EXIT)
299 signame = DEVICED_SIGNAL_POWER_CHANGE_STATE_TO_EXIT;
300 else if (next == POWER_STATE_TRANSIENT_SUSPENDING_EARLY)
301 signame = DEVICED_SIGNAL_POWER_CHANGE_STATE_TO_SUSPENDING_EARLY;
302 else if (next == POWER_STATE_TRANSIENT_SUSPENDING)
303 signame = DEVICED_SIGNAL_POWER_CHANGE_STATE_TO_SUSPENDING;
304 else if (next == POWER_STATE_TRANSIENT_SUSPENDING_LATE)
305 signame = DEVICED_SIGNAL_POWER_CHANGE_STATE_TO_SUSPENDING_LATE;
306 else if (next == POWER_STATE_TRANSIENT_RESUMING_EARLY)
307 signame = DEVICED_SIGNAL_POWER_CHANGE_STATE_TO_RESUMING_EARLY;
308 else if (next == POWER_STATE_TRANSIENT_RESUMING)
309 signame = DEVICED_SIGNAL_POWER_CHANGE_STATE_TO_RESUMING;
310 else if (next == POWER_STATE_TRANSIENT_RESUMING_LATE)
311 signame = DEVICED_SIGNAL_POWER_CHANGE_STATE_TO_RESUMING_LATE;
315 gdbus_signal_emit(NULL, DEVICED_PATH_POWER, DEVICED_INTERFACE_POWER, signame,
316 g_variant_new("(ttti)",
317 transition_context.ti.curr,
319 transition_context.id,
320 transition_context.ti.reason));
323 static uint64_t available_starting_state(void)
325 struct trans_info *ti = NULL;
327 // If there is pending transition,
328 // the available state is the last state of pendiong transitions.
329 ti = g_queue_peek_head(transition_queue);
333 // If a transition is underway and there is no other queued transitions,
334 // the available state is the destination of the ongoing transition.
335 // Otherwise, if there neither ongoing nor queued transitions are,
336 // the available state is the current state.
337 return transition_context.ongoing ? transition_context.ti.next : current;
340 static int dequeue_transition(struct trans_info *ti)
342 struct trans_info *tail = NULL;
347 tail = g_queue_pop_tail(transition_queue);
351 *ti = (struct trans_info) {
354 .reason = tail->reason,
363 static void enqueue_transition(const struct trans_info *ti)
365 struct trans_info *ti_new = NULL;
370 ti_new = calloc(1, sizeof(struct trans_info));
374 g_queue_push_head(transition_queue, memcpy(ti_new, ti, sizeof(struct trans_info)));
377 // intermediate state of ongoing transition
378 // it might be a transient state or a destination state
379 static uint64_t get_next_state(void)
381 int curr = POWER_STATE_INDEX(transition_context.ti.curr);
382 int next = POWER_STATE_INDEX(transition_context.ti.next);
383 int step = transition_context.transient_step;
385 if (step >= transient[curr][next].max_step)
386 return transition_context.ti.next;
388 return transient[curr][next].scenario[step];
391 static void init_waiting_list(gpointer data, gpointer udata)
393 uint64_t waiting_state;
394 struct proc_info *pi = (struct proc_info *) data;
395 struct change_state_wait *csw = NULL;
397 waiting_state = get_next_state();
399 if ((pi->state_bitmap & waiting_state) == 0)
402 csw = calloc(1, sizeof(struct change_state_wait));
406 *csw = (struct change_state_wait) {
408 .id = transition_context.id,
409 .state = waiting_state,
414 transition_context.waitings = g_list_append(transition_context.waitings, csw);
417 static char *state_abbr_name(uint64_t state)
419 if (state == POWER_STATE_START)
421 if (state == POWER_STATE_NORMAL)
423 if (state == POWER_STATE_SLEEP)
425 if (state == POWER_STATE_POWEROFF)
427 if (state == POWER_STATE_REBOOT)
429 if (state == POWER_STATE_EXIT)
431 if (state == POWER_STATE_TRANSIENT_SUSPENDING_EARLY)
432 return "SUSPENDING_EARLY";
433 if (state == POWER_STATE_TRANSIENT_SUSPENDING)
435 if (state == POWER_STATE_TRANSIENT_SUSPENDING_LATE)
436 return "SUSPENDING_LATE";
437 if (state == POWER_STATE_TRANSIENT_RESUMING_EARLY)
438 return "RESUMING_EARLY";
439 if (state == POWER_STATE_TRANSIENT_RESUMING)
441 if (state == POWER_STATE_TRANSIENT_RESUMING_LATE)
442 return "RESUMING_LATE";
447 static void reload_transition_sequence(GList **sequence)
449 GList *new_sequence = NULL;
450 int curr, next, step;
452 g_list_free(g_steal_pointer(sequence));
454 curr = POWER_STATE_INDEX(transition_context.ti.curr);
455 next = POWER_STATE_INDEX(transition_context.ti.next);
457 new_sequence = g_list_append(new_sequence, state_abbr_name(transition_context.ti.curr));
458 for (step = 0; step < transient[curr][next].max_step; ++step)
459 new_sequence = g_list_append(new_sequence, state_abbr_name(transient[curr][next].scenario[step]));
460 new_sequence = g_list_append(new_sequence, state_abbr_name(transition_context.ti.next));
462 *sequence = new_sequence;
465 static const char* build_description(GList *sequence, const int seqnum)
467 static char buffer[MAX_DESC_LEN] = { 0, };
469 // leave 1 byte for terminating null character
470 char *const tail = buffer + sizeof(buffer) - 1;
472 // additional (length-1) placeholders for transitioning arrow between each state
473 int max_sequence = g_list_length(sequence) * 2 - 1;
475 GList *iter = sequence;
478 memset(buffer, 0, sizeof(buffer));
481 GList *next = iter->next;
484 head += snprintf(head, tail - head, "[%s] ", (const char *) iter->data);
486 head += snprintf(head, tail - head, " %s ", (const char *) iter->data);
492 if (n >= max_sequence)
496 head += snprintf(head, tail - head, "[=>] ");
498 head += snprintf(head, tail - head, " => ");
510 static void transition_description(int reload)
512 static GList *transition_sequence = NULL;
513 static int seqnum = 0;
517 reload_transition_sequence(&transition_sequence);
520 _D("%s", build_description(transition_sequence, seqnum++));
523 static void trigger_transition(void)
527 assert(transition_context.max_wait_timer == 0);
528 assert(is_poweroff_state(current) == 0);
530 transition_context.id = alloc_unique_id();
532 if (!transition_context.ongoing) {
533 // hold secondary wakelock not to fall asleep during transition
534 event_wake_lock(EL_POWER_TRANSITION_STATE);
535 transition_context.ongoing = 1;
538 transition_description(0);
540 broadcast_transition_info();
541 g_list_foreach(proc_list, init_waiting_list, &waiting);
543 transition_context.max_wait_timer = g_timeout_add_seconds(max_wait_timeout, max_wait_expired_cb, NULL);
548 static void action_transition(void)
550 uint64_t state = get_next_state();
552 transition_description(0);
554 if (state == transition_context.ti.next) {
555 // it has reached the destination state
556 struct trans_info ti = { 0 , };
559 current = transition_context.ti.next;
561 if (action_on_state[POWER_STATE_INDEX(current)])
562 action_on_state[POWER_STATE_INDEX(current)](transition_context.ti.data);
565 transition_context.ongoing = 0;
566 event_wake_unlock(EL_POWER_TRANSITION_STATE);
568 // trigger next transition if exist
569 retval = dequeue_transition(&ti);
571 prepare_transition(&ti);
572 trigger_transition();
575 // step into the next transient state
576 ++transition_context.transient_step;
577 trigger_transition();
581 static void prepare_transition(const struct trans_info *ti)
583 assert(transition_context.waitings == NULL);
584 assert(transition_context.max_wait_timer == 0);
587 transition_context.ti = (struct trans_info) {
590 .reason = ti->reason,
595 transition_context.ongoing = 0;
596 transition_context.transient_step = 0;
598 transition_description(1);
601 static gint find_ti_by_state(gconstpointer data, gconstpointer udata)
603 const struct trans_info *ti = (const struct trans_info *) data;
604 const uint64_t state = *(const uint64_t *) udata;
606 if (ti->curr & state)
612 static int transition_request_callback(void *data)
615 const struct trans_info *t = NULL;
616 struct trans_info ti = { 0 , };
622 available = available_starting_state();
624 ti_list = (GList *) data;
626 l = g_list_find_custom(ti_list, &available, find_ti_by_state);
635 // check invalid next state
636 if (__builtin_popcountll(t->next & POWER_STATE_ALL) != 1) {
637 _E("Invalid next state, curr=%"PRIx64", next=%"PRIx64", reason=%d", t->curr, t->next, t->reason);
641 ti = (struct trans_info) {
648 // TODO: immediate handling of poweroff?
650 if (!delayed_init_done || transition_context.ongoing) {
651 // Processes starting later than the deviced wanted to be informed
652 // about power transition that has happend before the process start. To
653 // this end, all transitions are delayed after the delayed_init_callback(),
654 // which is called on completing delayed.target. Therefore it is guaranteed
655 // that all processes that starts before delayed.target can receieve all
656 // power transition information.
657 enqueue_transition(&ti);
661 prepare_transition(&ti);
662 trigger_transition();
667 static int delayed_init_callback(void *data)
670 struct trans_info ti = { 0 , };
672 delayed_init_done = 1;
674 _D("Start deferred state transition.");
676 retval = dequeue_transition(&ti);
678 prepare_transition(&ti);
679 trigger_transition();
682 power_enable_autosleep();
687 static int load_max_wait_timeout(struct parse_result *result, void *user_data)
689 if (MATCH(result->section, "PowerState")
690 && MATCH(result->name, "ChangeStateMaxWaitSecond"))
691 max_wait_timeout = atoi(result->value);
696 void power_state_init(void *data)
698 transition_queue = g_queue_new();
700 config_parse(POWER_CONF_FILE, load_max_wait_timeout, NULL);
702 register_notifier(DEVICE_NOTIFIER_DELAYED_INIT, delayed_init_callback);
703 register_notifier(DEVICE_NOTIFIER_REQUEST_TRANSITION_STATE, transition_request_callback);
707 power_suspend_init();
708 power_event_lock_init();
710 /* Take the first transition.
712 * It is determined by bootreason and bootmode to which state to transition, POWER_STATE_NORMAL
713 * or POWER_STATE_SLEEP. it may stay in POWER_STATE_START if there is no defined action for the
714 * matching bootreason and bootmode.
716 initial_transition_by_boot_condition();
719 static const struct device_ops power_state_device_ops = {
720 DECLARE_NAME_LEN("power-state"),
721 .init = power_state_init,
722 /* It should be initilalized earlier than the almost other modules so that
723 * it can receive and handle power request from the other modules. Therefore
724 * give a high enough priority. */
728 DEVICE_OPS_REGISTER(&power_state_device_ops)