e9b2a0286265775b2258c8c3df3700b71b0cc2d2
[platform/core/system/deviced.git] / src / power / power.c
1 /*
2  * deviced
3  *
4  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
5  *
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
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  */
18
19 #include <stdio.h>
20 #include <stdint.h>
21 #include <assert.h>
22 #include <inttypes.h>
23 #include <linux/input.h>
24 #include <libsyscommon/libgdbus.h>
25 #include <libsyscommon/list.h>
26 #include <device/power-internal.h>
27
28 #include "shared/devices.h"
29 #include "shared/device-notifier.h"
30 #include "shared/log.h"
31 #include "shared/common.h"
32 #include "power.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"
38
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
43
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;
48 static struct {
49         int id;
50         int ongoing;
51         struct trans_info ti;
52         GList *waitings;
53         int transient_step;
54         int max_wait_timer;
55 } transition_context;
56
57 struct proc_info {
58         pid_t pid;
59         char comm[128];
60         guint64 state_bitmap;
61 };
62 static GList *proc_list;
63
64 struct change_state_wait {
65         struct proc_info *pi;
66         guint64 id;
67         int state;
68 };
69
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,
74 };
75
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,
80 };
81
82 static const struct {
83         int max_step;
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,
89         },
90         [POWER_STATE_SLEEP_INDEX][POWER_STATE_NORMAL_INDEX] = {
91                 .max_step = ARRAY_SIZE(transient_scenario_resuming),
92                 .scenario = transient_scenario_resuming,
93         },
94 };
95
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);
100
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,
110 };
111
112 uint64_t power_get_state(void)
113 {
114         return current;
115 }
116
117 static void cleanup_waiting_list(gpointer data)
118 {
119         struct change_state_wait *csw = (struct change_state_wait *) data;
120
121         _E("%s(pid=%d) hasn't confirmed id=%"PRIu64"(%s)", csw->pi->comm, csw->pi->pid, csw->id, state_name(csw->state));
122
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);
126                 free(csw->pi);
127         }
128
129         free(csw);
130 }
131
132 static gboolean max_wait_expired_cb(void *data)
133 {
134         transition_context.max_wait_timer = 0;
135
136         g_list_free_full(g_steal_pointer(&transition_context.waitings), cleanup_waiting_list);
137
138         action_transition();
139
140         return G_SOURCE_REMOVE;
141 }
142
143 static gint find_pi_by_pid(gconstpointer data, gconstpointer udata)
144 {
145         const struct proc_info *pi = (const struct proc_info *) data;
146         const pid_t pid = *(const pid_t *) udata;
147
148         if (pi->pid == pid)
149                 return 0;
150
151         return -1;
152 }
153
154 int add_change_state_wait(pid_t pid, guint64 state)
155 {
156         struct proc_info *pi = NULL;
157         GList *l = NULL;
158
159         l = g_list_find_custom(proc_list, &pid, find_pi_by_pid);
160         if (l && l->data) {
161                 pi = l->data;
162                 pi->state_bitmap |= state;
163                 _D("pid=%d(%s) updated csw for %#"PRIx64, pi->pid, pi->comm, state);
164                 return 0;
165         }
166
167         pi = calloc(1, sizeof(struct proc_info));
168         if (!pi)
169                 return -ENOMEM;
170
171         pi->pid = pid;
172         pi->state_bitmap = state;
173         get_command(pid, pi->comm, sizeof(pi->comm));
174         proc_list = g_list_append(proc_list, pi);
175
176         _D("pid=%d(%s) added csw for %#"PRIx64, pid, pi->comm, state);
177
178         return 0;
179 }
180
181 void remove_change_state_wait(pid_t pid, guint64 state)
182 {
183         struct proc_info *pi = NULL;
184         GList *l = NULL;
185
186         l = g_list_find_custom(proc_list, &pid, find_pi_by_pid);
187         if (!l)
188                 return;
189
190         if (!l->data)
191                 return;
192
193         pi = l->data;
194
195         _D("pid=%d(%s) removed csw for %#"PRIx64, pi->pid, pi->comm, state);
196
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));
201                 g_list_free(l);
202         }
203 }
204
205 static gint find_csw_by_pid_id(gconstpointer data, gconstpointer udata)
206 {
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;
209
210         if (csw->pi->pid == target->pi->pid && csw->id == target->id)
211                 return 0;
212
213         return -1;
214 }
215
216 int confirm_change_state_wait(pid_t pid, guint64 id)
217 {
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;
221         GList *l = NULL;
222
223         l = g_list_find_custom(transition_context.waitings, &target_csw, find_csw_by_pid_id);
224         if (!l)
225                 return 0;
226
227         if (!l->data)
228                 return 0;
229
230         csw = l->data;
231         _D("pid=%d(%s) confirmed id=%"PRIu64"(%s)", csw->pi->pid, csw->pi->comm, csw->id, state_name(csw->state));
232
233         transition_context.waitings = g_list_remove_link(transition_context.waitings, l);
234         free(g_steal_pointer(&l->data));
235         g_list_free(l);
236
237         // continue waiting
238         if (g_list_length(transition_context.waitings) != 0)
239                 return 0;
240
241         // the last csw is cleared
242         g_source_remove(transition_context.max_wait_timer);
243         transition_context.max_wait_timer = 0;
244
245         action_transition();
246
247         return 0;
248 }
249
250 static int alloc_unique_id(void)
251 {
252         static int id = 0;
253
254         return ++id;
255 }
256
257 static void power_action_normal(void *udata)
258 {
259         power_acquire_wakelock();
260 }
261
262 static void power_action_sleep(void *udata)
263 {
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));
267                 return;
268         }
269
270         power_release_wakelock();
271 }
272
273 static void power_action_poweroff(void *data)
274 {
275         // do not transition anymore after poweroff
276         unregister_notifier(DEVICE_NOTIFIER_REQUEST_TRANSITION_STATE, transition_request_callback);
277
278         poweroff_prepare(current, data);
279         poweroff_main((void *)(intptr_t) current);
280 }
281
282 static void broadcast_transition_info(void)
283 {
284         const char *signame;
285
286         uint64_t next = get_next_state();
287
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;
312         else
313                 return;
314
315         gdbus_signal_emit(NULL, DEVICED_PATH_POWER, DEVICED_INTERFACE_POWER, signame,
316                 g_variant_new("(ttti)",
317                         transition_context.ti.curr,
318                         next,
319                         transition_context.id,
320                         transition_context.ti.reason));
321 }
322
323 static uint64_t available_starting_state(void)
324 {
325         struct trans_info *ti = NULL;
326
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);
330         if (ti)
331                 return ti->next;
332
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;
338 }
339
340 static int dequeue_transition(struct trans_info *ti)
341 {
342         struct trans_info *tail = NULL;
343
344         if (!ti)
345                 return -1;
346
347         tail = g_queue_pop_tail(transition_queue);
348         if (!tail)
349                 return -1;
350
351         *ti = (struct trans_info) {
352                 .curr = tail->curr,
353                 .next = tail->next,
354                 .reason = tail->reason,
355                 .data = tail->data,
356         };
357
358         free(tail);
359
360         return 0;
361 }
362
363 static void enqueue_transition(const struct trans_info *ti)
364 {
365         struct trans_info *ti_new = NULL;
366
367         if (!ti)
368                 return;
369
370         ti_new = calloc(1, sizeof(struct trans_info));
371         if (!ti_new)
372                 return;
373
374         g_queue_push_head(transition_queue, memcpy(ti_new, ti, sizeof(struct trans_info)));
375 }
376
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)
380 {
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;
384
385         if (step >= transient[curr][next].max_step)
386                 return transition_context.ti.next;
387         else
388                 return transient[curr][next].scenario[step];
389 }
390
391 static void init_waiting_list(gpointer data, gpointer udata)
392 {
393         uint64_t waiting_state;
394         struct proc_info *pi = (struct proc_info *) data;
395         struct change_state_wait *csw = NULL;
396
397         waiting_state = get_next_state();
398
399         if ((pi->state_bitmap & waiting_state) == 0)
400                 return;
401
402         csw = calloc(1, sizeof(struct change_state_wait));
403         if (!csw)
404                 return;
405
406         *csw = (struct change_state_wait) {
407                 .pi = pi,
408                 .id = transition_context.id,
409                 .state = waiting_state,
410         };
411
412         *(int *) udata += 1;
413
414         transition_context.waitings = g_list_append(transition_context.waitings, csw);
415 }
416
417 static char *state_abbr_name(uint64_t state)
418 {
419         if (state == POWER_STATE_START)
420                 return "START";
421         if (state == POWER_STATE_NORMAL)
422                 return "NORMAL";
423         if (state == POWER_STATE_SLEEP)
424                 return "SLEEP";
425         if (state == POWER_STATE_POWEROFF)
426                 return "POWEROFF";
427         if (state == POWER_STATE_REBOOT)
428                 return "REBOOT";
429         if (state == POWER_STATE_EXIT)
430                 return "EXIT";
431         if (state == POWER_STATE_TRANSIENT_SUSPENDING_EARLY)
432                 return "SUSPENDING_EARLY";
433         if (state == POWER_STATE_TRANSIENT_SUSPENDING)
434                 return "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)
440                 return "RESUMING";
441         if (state == POWER_STATE_TRANSIENT_RESUMING_LATE)
442                 return "RESUMING_LATE";
443
444         return "INVALID";
445 }
446
447 static void reload_transition_sequence(GList **sequence)
448 {
449         GList *new_sequence = NULL;
450         int curr, next, step;
451
452         g_list_free(g_steal_pointer(sequence));
453
454         curr = POWER_STATE_INDEX(transition_context.ti.curr);
455         next = POWER_STATE_INDEX(transition_context.ti.next);
456
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));
461
462         *sequence = new_sequence;
463 }
464
465 static const char* build_description(GList *sequence, const int seqnum)
466 {
467         static char buffer[MAX_DESC_LEN] = { 0, };
468         char *head = buffer;
469         // leave 1 byte for terminating null character
470         char *const tail = buffer + sizeof(buffer) - 1;
471
472         // additional (length-1) placeholders for transitioning arrow between each state
473         int max_sequence = g_list_length(sequence) * 2 - 1;
474
475         GList *iter = sequence;
476         int n = 0;
477
478         memset(buffer, 0, sizeof(buffer));
479
480         while (iter) {
481                 GList *next = iter->next;
482
483                 if (n == seqnum)
484                         head += snprintf(head, tail - head, "[%s] ", (const char *) iter->data);
485                 else
486                         head += snprintf(head, tail - head, " %s  ", (const char *) iter->data);
487
488                 if (head >= tail)
489                         break;
490
491                 ++n;
492                 if (n >= max_sequence)
493                         break;
494
495                 if (n == seqnum)
496                         head += snprintf(head, tail - head, "[=>] ");
497                 else
498                         head += snprintf(head, tail - head, " =>  ");
499
500                 if (head >= tail)
501                         break;
502
503                 ++n;
504                 iter = next;
505         }
506
507         return buffer;
508 }
509
510 static void transition_description(int reload)
511 {
512         static GList *transition_sequence = NULL;
513         static int seqnum = 0;
514
515         if (reload) {
516                 seqnum = 0;
517                 reload_transition_sequence(&transition_sequence);
518         }
519
520         _D("%s", build_description(transition_sequence, seqnum++));
521 }
522
523 static void trigger_transition(void)
524 {
525         int waiting = 0;
526
527         assert(transition_context.max_wait_timer == 0);
528         assert(is_poweroff_state(current) == 0);
529
530         transition_context.id = alloc_unique_id();
531
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;
536         }
537
538         transition_description(0);
539
540         broadcast_transition_info();
541         g_list_foreach(proc_list, init_waiting_list, &waiting);
542         if (waiting > 0)
543                 transition_context.max_wait_timer = g_timeout_add_seconds(max_wait_timeout, max_wait_expired_cb, NULL);
544         else
545                 action_transition();
546 }
547
548 static void action_transition(void)
549 {
550         uint64_t state = get_next_state();
551
552         transition_description(0);
553
554         if (state == transition_context.ti.next) {
555                 // it has reached the destination state
556                 struct trans_info ti = { 0 , };
557                 int retval;
558
559                 current = transition_context.ti.next;
560
561                 if (action_on_state[POWER_STATE_INDEX(current)])
562                         action_on_state[POWER_STATE_INDEX(current)](transition_context.ti.data);
563
564                 // transition end
565                 transition_context.ongoing = 0;
566                 event_wake_unlock(EL_POWER_TRANSITION_STATE);
567
568                 // trigger next transition if exist
569                 retval = dequeue_transition(&ti);
570                 if (retval == 0) {
571                         prepare_transition(&ti);
572                         trigger_transition();
573                 }
574         } else {
575                 // step into the next transient state
576                 ++transition_context.transient_step;
577                 trigger_transition();
578         }
579 }
580
581 static void prepare_transition(const struct trans_info *ti)
582 {
583         assert(transition_context.waitings == NULL);
584         assert(transition_context.max_wait_timer == 0);
585
586         if (ti) {
587                 transition_context.ti = (struct trans_info) {
588                         .curr = ti->curr,
589                         .next = ti->next,
590                         .reason = ti->reason,
591                         .data = ti->data,
592                 };
593         }
594
595         transition_context.ongoing = 0;
596         transition_context.transient_step = 0;
597
598         transition_description(1);
599 }
600
601 static gint find_ti_by_state(gconstpointer data, gconstpointer udata)
602 {
603         const struct trans_info *ti = (const struct trans_info *) data;
604         const uint64_t state = *(const uint64_t *) udata;
605
606         if (ti->curr & state)
607                 return 0;
608
609         return -1;
610 }
611
612 static int transition_request_callback(void *data)
613 {
614         GList *ti_list, *l;
615         const struct trans_info *t = NULL;
616         struct trans_info ti = { 0 , };
617         uint64_t available;
618
619         if (!data)
620                 return 0;
621
622         available = available_starting_state();
623
624         ti_list = (GList *) data;
625
626         l = g_list_find_custom(ti_list, &available, find_ti_by_state);
627         if (!l)
628                 return 0;
629
630         if (!l->data)
631                 return 0;
632
633         t = l->data;
634
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);
638                 return 0;
639         }
640
641         ti = (struct trans_info) {
642                 .curr = available,
643                 .next = t->next,
644                 .reason = t->reason,
645                 .data = t->data,
646         };
647
648         // TODO: immediate handling of poweroff?
649
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);
658                 return 0;
659         }
660
661         prepare_transition(&ti);
662         trigger_transition();
663
664         return 0;
665 }
666
667 static int delayed_init_callback(void *data)
668 {
669         int retval;
670         struct trans_info ti = { 0 , };
671
672         delayed_init_done = 1;
673
674         _D("Start deferred state transition.");
675
676         retval = dequeue_transition(&ti);
677         if (retval == 0) {
678                 prepare_transition(&ti);
679                 trigger_transition();
680         }
681
682         power_enable_autosleep();
683
684         return 0;
685 }
686
687 static int load_max_wait_timeout(struct parse_result *result, void *user_data)
688 {
689         if (MATCH(result->section, "PowerState")
690                 && MATCH(result->name, "ChangeStateMaxWaitSecond"))
691                 max_wait_timeout = atoi(result->value);
692
693         return 0;
694 }
695
696 void power_state_init(void *data)
697 {
698         transition_queue = g_queue_new();
699
700         config_parse(POWER_CONF_FILE, load_max_wait_timeout, NULL);
701
702         register_notifier(DEVICE_NOTIFIER_DELAYED_INIT, delayed_init_callback);
703         register_notifier(DEVICE_NOTIFIER_REQUEST_TRANSITION_STATE, transition_request_callback);
704
705         power_dbus_init();
706         power_off_init();
707         power_suspend_init();
708         power_event_lock_init();
709
710         /* Take the first transition.
711          *
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.
715          */
716         initial_transition_by_boot_condition();
717 }
718
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. */
725         .priority          = 990,
726 };
727
728 DEVICE_OPS_REGISTER(&power_state_device_ops)