4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
22 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
23 * Use is subject to license terms.
24 * Copyright 2016 Nexenta Systems, Inc. All rights reserved.
27 #include <stdio.h> /* Standard */
30 #include <sys/types.h>
38 #include <sys/todio.h> /* Time-Of-Day chip */
41 #include <sys/ipc.h> /* IPC functions */
42 #include <signal.h> /* signal handling */
45 #include <libdevinfo.h>
47 #include <sys/pm.h> /* power management driver */
48 #include <sys/uadmin.h>
49 #include <sys/openpromio.h> /* for prom access */
50 #include <sys/sysmacros.h> /* for MIN & MAX macros */
51 #include <sys/modctl.h>
52 #include <sys/stropts.h> /* for INFTIM */
60 /* External Functions */
61 extern struct tm
*localtime_r(const time_t *, struct tm
*);
62 extern void sysstat_init(void);
63 extern int check_tty(hrtime_t
*, int);
64 extern int check_disks(hrtime_t
*, int);
65 extern int check_load_ave(hrtime_t
*, float);
66 extern int check_nfs(hrtime_t
*, int);
67 extern int last_disk_activity(hrtime_t
*, int);
68 extern int last_tty_activity(hrtime_t
*, int);
69 extern int last_load_ave_activity(hrtime_t
*);
70 extern int last_nfs_activity(hrtime_t
*, int);
73 #define TOD "/dev/tod"
74 #define PROM "/dev/openprom"
75 #define PB "/dev/power_button"
76 #define SRN "/dev/srn"
77 #define LOGFILE "./powerd.log"
80 #define ATTACH_THREAD 1
83 #define CHECK_INTERVAL 5
84 #define IDLECHK_INTERVAL 15
85 #define MINS_TO_SECS 60
86 #define HOURS_TO_SECS (60 * 60)
87 #define DAYS_TO_SECS (24 * 60 * 60)
88 #define HOURS_TO_MINS 60
89 #define DAYS_TO_MINS (24 * 60)
91 #define LIFETIME_SECS (7 * 365 * DAYS_TO_SECS)
92 #define DEFAULT_POWER_CYCLE_LIMIT 10000
93 #define DEFAULT_SYSTEM_BOARD_DATE 804582000 /* July 1, 1995 */
97 typedef enum {root
, options
} prom_node_t
;
100 static struct cprconfig asinfo
;
101 static time_t shutdown_time
; /* Time for next shutdown check */
102 static time_t checkidle_time
; /* Time for next idleness check */
103 static time_t last_resume
;
104 pwr_info_t
*info
; /* private as config data buffer */
105 static int pb_fd
; /* power button driver */
106 static int broadcast
; /* Enables syslog messages */
107 static int start_calc
;
108 static int autoshutdown_en
;
109 static int do_idlecheck
;
110 static int got_sighup
;
111 static int estar_v2_prop
;
112 static int estar_v3_prop
;
113 static int log_power_cycles_error
= 0;
114 static int log_system_board_date_error
= 0;
115 static int log_no_autoshutdown_warning
= 0;
116 static mutex_t poweroff_mutex
;
118 static char *autoshutdown_cmd
[] = {
119 "/usr/bin/sys-suspend",
120 "-n", "-d", ":0", NULL
123 static char *power_button_cmd
[] = {
124 "/usr/bin/sys-suspend",
125 "-h", "-d", ":0", NULL
129 static char *autoS3_cmd
[] = {
130 "/usr/bin/sys-suspend",
131 "-n", "-d", ":0", NULL
135 static char pidpath
[] = PIDPATH
;
136 static char scratch
[PATH_MAX
];
139 /* Local Functions */
140 static void alarm_handler(int);
141 static void thaw_handler(int);
142 static void kill_handler(int);
143 static void work_handler(int);
144 static void check_shutdown(time_t *, hrtime_t
*);
145 static void check_idleness(time_t *, hrtime_t
*);
146 static int last_system_activity(hrtime_t
*);
147 static int run_idlecheck(void);
148 static void set_alarm(time_t);
149 static int poweroff(const char *, char **);
150 static int is_ok2shutdown(time_t *);
151 static int get_prom(int, prom_node_t
, char *, char *, size_t);
152 static void power_button_monitor(void *);
153 static int open_pidfile(char *);
154 static int write_pidfile(int, pid_t
);
155 static int read_cpr_config(void);
156 static void system_activity_monitor(void);
158 static void autos3_monitor(void);
160 static void do_attach(void);
161 static void *attach_devices(void *);
162 static int powerd_debug
;
166 logerror(const char *fmt
, ...)
172 vsyslog(LOG_ERR
, fmt
, args
);
178 estrcpy(char *dst
, char *src
, size_t dlen
)
182 slen
= strlcpy(dst
, src
, dlen
);
184 logerror("%s: string too long \"%s ...\"\n"
185 "(len %d, max %d)\n", prog
, dst
, slen
, dlen
- 1);
192 main(int argc
, char *argv
[])
196 struct sigaction act
;
199 char errmsg
[PATH_MAX
+ 64];
203 if (geteuid() != 0) {
204 (void) fprintf(stderr
, "%s: Must be root\n", prog
);
208 if ((pid_fd
= open_pidfile(prog
)) == -1)
215 while ((c
= getopt(argc
, argv
, "nd")) != EOF
) {
224 (void) fprintf(stderr
, "Usage: %s [-n]\n", prog
);
229 pm_fd
= open(PM
, O_RDWR
);
231 (void) snprintf(errmsg
, sizeof (errmsg
), "%s: %s", prog
, PM
);
238 * Initialize mutex lock used to insure only one command to
241 if (mutex_init(&poweroff_mutex
, USYNC_THREAD
, NULL
) != 0) {
242 (void) fprintf(stderr
,
243 "%s: Unable to initialize mutex lock\n", prog
);
247 if ((info
= (pwr_info_t
*)malloc(sizeof (pwr_info_t
))) == NULL
) {
248 (void) snprintf(errmsg
, sizeof (errmsg
), "%s: malloc", prog
);
254 * Daemon is set to go...
256 if ((pid
= fork()) < 0)
262 openlog(prog
, 0, LOG_DAEMON
);
263 if (write_pidfile(pid_fd
, pid
) == -1) /* logs errors on failure */
265 (void) close(pid_fd
);
268 * Close all the parent's file descriptors (Bug 1225843).
276 * Connect stdout to the console.
278 if (dup2(open("/dev/console", O_WRONLY
|O_NOCTTY
), 1) == -1) {
279 logerror("Unable to connect to the console.");
282 info
->pd_flags
= PD_AC
;
283 info
->pd_idle_time
= -1;
284 info
->pd_start_time
= 0;
285 info
->pd_finish_time
= 0;
288 * Allow SIGQUIT, SIGINT and SIGTERM signals to terminate us
291 act
.sa_handler
= kill_handler
;
292 (void) sigemptyset(&act
.sa_mask
);
294 (void) sigaction(SIGQUIT
, &act
, NULL
);
295 (void) sigaction(SIGINT
, &act
, NULL
);
296 (void) sigaction(SIGTERM
, &act
, NULL
);
298 (void) sigfillset(&sigmask
);
299 (void) sigdelset(&sigmask
, SIGQUIT
);
300 (void) sigdelset(&sigmask
, SIGINT
);
301 (void) sigdelset(&sigmask
, SIGTERM
);
302 (void) thr_sigsetmask(SIG_SETMASK
, &sigmask
, NULL
);
305 * If "power_button" device node can be opened, create a new
306 * thread to monitor the power button.
308 if ((pb_fd
= open(PB
, O_RDONLY
)) != -1) {
310 logerror("powerd starting power button monitor.");
311 if (thr_create(NULL
, NULL
,
312 (void *(*)(void *))power_button_monitor
, NULL
,
313 THR_DAEMON
, NULL
) != 0) {
314 logerror("Unable to monitor system's power button.");
321 * Create a new thread to monitor system activity and suspend
325 logerror("powerd starting system activity monitor.");
326 if (thr_create(NULL
, NULL
,
327 (void *(*)(void *))system_activity_monitor
, NULL
,
328 THR_DAEMON
, NULL
) != 0) {
329 logerror("Unable to create thread to monitor system activity.");
334 * Create a new thread to handle autos3 trigger
337 logerror("powerd starting autos3 monitor.");
338 if (thr_create(NULL
, NULL
,
339 (void *(*)(void *))autos3_monitor
, NULL
, THR_DAEMON
, NULL
) != 0) {
340 logerror("Unable to create thread to monitor autos3 activity.");
345 * Block until we receive an explicit terminate signal
347 (void) sigsuspend(&sigmask
);
353 system_activity_monitor(void)
355 struct sigaction act
;
359 * Setup for gathering system's statistic.
364 * In addition to the SIGQUIT, SIGINT and SIGTERM signals already
365 * being handled, this thread also needs to handle SIGHUP, SIGALRM
366 * and SIGTHAW signals.
368 (void) sigemptyset(&act
.sa_mask
);
370 act
.sa_handler
= alarm_handler
;
371 (void) sigaction(SIGALRM
, &act
, NULL
);
372 act
.sa_handler
= work_handler
;
373 (void) sigaction(SIGHUP
, &act
, NULL
);
374 act
.sa_handler
= thaw_handler
;
375 (void) sigaction(SIGTHAW
, &act
, NULL
);
378 * Invoke work_handler with a dummy SIGHUP signal to read
379 * cpr config file, get autoshutdown properties and schedule
380 * an alarm if needed.
382 work_handler(SIGHUP
);
385 * Wait for signal to read file
387 (void) thr_sigsetmask(0, 0, &sigmask
);
388 (void) sigdelset(&sigmask
, SIGHUP
);
389 (void) sigdelset(&sigmask
, SIGALRM
);
390 (void) sigdelset(&sigmask
, SIGTHAW
);
391 (void) thr_sigsetmask(SIG_SETMASK
, &sigmask
, NULL
);
393 (void) sigsuspend(&sigmask
);
394 } while (errno
== EINTR
);
401 struct pollfd poll_fd
;
402 srn_event_info_t srn_event
; /* contains suspend type */
405 fd
= open(SRN
, O_RDWR
|O_EXCL
|O_NDELAY
);
407 logerror("Unable to open %s: %s", SRN
, strerror(errno
));
408 thr_exit((void *)(intptr_t)errno
);
412 * Tell device we want the special sauce
414 ret
= ioctl(fd
, SRN_IOC_AUTOSX
, NULL
);
416 logerror("Ioctl SRN_IOC_AUTOSX failed: %s", strerror(errno
));
418 thr_exit((void *)(intptr_t)errno
);
424 poll_fd
.events
= POLLIN
;
425 if (poll(&poll_fd
, 1, -1) < 0) {
431 logerror("Poll error: %s", strerror(errno
));
433 thr_exit((void *)(intptr_t)errno
);
437 ret
= ioctl(fd
, SRN_IOC_NEXTEVENT
, &srn_event
);
439 logerror("ioctl error: %s", strerror(errno
));
441 thr_exit((void *)(intptr_t)errno
);
443 switch (srn_event
.ae_type
) {
446 logerror("ioctl returns type: %d",
450 logerror("Unsupported target state %d",
454 (void) poweroff("AutoS3", autoS3_cmd
);
461 read_cpr_config(void)
465 if ((asfd
= open(CPR_CONFIG
, O_RDONLY
)) < 0) {
466 logerror("Unable to open CPR config file '%s'", CPR_CONFIG
);
470 if (read(asfd
, (void *)&asinfo
, sizeof (asinfo
)) != sizeof (asinfo
)) {
471 logerror("Unable to read CPR config file '%s'", CPR_CONFIG
);
483 thaw_handler(int sig
)
486 last_resume
= time(NULL
);
491 kill_handler(int sig
)
493 int ret_code
= EXIT_SUCCESS
;
503 (void) mutex_destroy(&poweroff_mutex
);
504 (void) unlink(pidpath
);
511 alarm_handler(int sig
)
517 hr_now
= gethrtime();
518 if (checkidle_time
<= now
&& checkidle_time
!= 0)
519 check_idleness(&now
, &hr_now
);
520 if (shutdown_time
<= now
&& shutdown_time
!= 0)
521 check_shutdown(&now
, &hr_now
);
528 work_handler(int sig
)
532 struct stat stat_buf
;
535 info
->pd_flags
= PD_AC
;
538 * Parse the config file for autoshutdown and idleness entries.
540 if (read_cpr_config() < 0)
544 * Since Oct. 1, 1995, any new system shipped had root
545 * property "energystar-v2" defined in its prom. Systems
546 * shipped after July 1, 1999, will have "energystar-v3"
549 estar_v2_prop
= asinfo
.is_cpr_default
;
551 info
->pd_flags
|= asinfo
.is_autowakeup_capable
;
553 if (strlen(asinfo
.idlecheck_path
) > 0) {
554 if (stat(asinfo
.idlecheck_path
, &stat_buf
) != 0) {
555 logerror("unable to access idlecheck program \"%s\".",
556 asinfo
.idlecheck_path
);
557 } else if (!(stat_buf
.st_mode
& S_IXUSR
)) {
558 logerror("idlecheck program \"%s\" is not executable.",
559 asinfo
.idlecheck_path
);
565 if (strlen(asinfo
.as_behavior
) == 0 ||
566 strcmp(asinfo
.as_behavior
, "noshutdown") == 0 ||
567 strcmp(asinfo
.as_behavior
, "unconfigured") == 0) {
568 info
->pd_autoshutdown
= 0;
569 } else if (strcmp(asinfo
.as_behavior
, "default") == 0) {
570 info
->pd_autoshutdown
= estar_v2_prop
;
571 } else if (strcmp(asinfo
.as_behavior
, "shutdown") == 0 ||
572 strcmp(asinfo
.as_behavior
, "autowakeup") == 0) {
573 info
->pd_autoshutdown
= asinfo
.is_cpr_capable
;
575 logerror("autoshutdown behavior \"%s\" unrecognized.",
577 info
->pd_autoshutdown
= 0;
580 if (info
->pd_autoshutdown
) {
581 info
->pd_idle_time
= asinfo
.as_idle
;
582 info
->pd_start_time
=
583 (asinfo
.as_sh
* 60 + asinfo
.as_sm
) % DAYS_TO_MINS
;
584 info
->pd_finish_time
=
585 (asinfo
.as_fh
* 60 + asinfo
.as_fm
) % DAYS_TO_MINS
;
586 info
->pd_autoresume
=
587 (strcmp(asinfo
.as_behavior
, "autowakeup") == 0) ? 1 : 0;
589 autoshutdown_en
= (asinfo
.as_idle
>= 0 && info
->pd_autoshutdown
)
593 (void) fprintf(stderr
, "autoshutdown_en = %d, as_idle = %d, "
594 "pd_autoresume = %d\n",
595 autoshutdown_en
, asinfo
.as_idle
, info
->pd_autoresume
);
597 (void) fprintf(stderr
, " pd_start_time=%d, pd_finish_time=%d\n",
598 info
->pd_start_time
, info
->pd_finish_time
);
602 now
= last_resume
= time(NULL
);
603 hr_now
= gethrtime();
604 check_idleness(&now
, &hr_now
);
605 check_shutdown(&now
, &hr_now
);
610 check_shutdown(time_t *now
, hrtime_t
*hr_now
)
613 int kbd
, mouse
, system
, least_idle
, idlecheck_time
;
617 time_t start_of_day
, time_since_last_resume
;
619 extern long conskbd_idle_time(void);
620 extern long consms_idle_time(void);
621 static int warned_kbd
, warned_ms
; /* print error msg one time */
623 if (!autoshutdown_en
) {
628 (void) localtime_r(now
, &tmp_time
);
631 tmp_time
.tm_hour
= 0;
632 start_of_day
= mktime(&tmp_time
);
633 s
= start_of_day
+ info
->pd_start_time
* 60;
634 f
= start_of_day
+ info
->pd_finish_time
* 60;
635 if ((s
< f
&& *now
>= s
&& *now
< f
) ||
636 (s
>= f
&& (*now
< f
|| *now
>= s
))) {
637 if ((mouse
= (int)consms_idle_time()) < 0) {
640 logerror("powerd: failed to get "
641 "idle time for console mouse");
645 if ((kbd
= (int)conskbd_idle_time()) < 0) {
648 logerror("powerd: failed to get "
649 "idle time for console keyboard");
654 system
= last_system_activity(hr_now
);
655 /* who is the last to go idle */
656 least_idle
= MIN(system
, MIN(kbd
, mouse
));
659 * Calculate time_since_last_resume and the next_time
663 time_since_last_resume
= time(NULL
) - last_resume
;
664 next_time
= info
->pd_idle_time
* 60 -
665 MIN(least_idle
, time_since_last_resume
);
668 fprintf(stderr
, " check_shutdown: next_time=%d\n", next_time
);
672 * If we have get the SIGTHAW signal at this point - our
673 * calculation of time_since_last_resume is wrong so
674 * - we need to recalculate.
676 while (start_calc
== 0) {
677 /* need to redo calculation */
679 time_since_last_resume
= time(NULL
) - last_resume
;
680 next_time
= info
->pd_idle_time
* 60 -
681 MIN(least_idle
, time_since_last_resume
);
685 * Only when everything else is idle, run the user's idlecheck
688 if (next_time
<= 0 && do_idlecheck
) {
690 idlecheck_time
= run_idlecheck();
691 next_time
= info
->pd_idle_time
* 60 -
692 MIN(idlecheck_time
, MIN(least_idle
,
693 time_since_last_resume
));
695 * If we have caught SIGTHAW or SIGHUP, need to
698 while (start_calc
== 0 || got_sighup
== 1) {
701 idlecheck_time
= run_idlecheck();
702 time_since_last_resume
= time(NULL
) -
704 next_time
= info
->pd_idle_time
* 60 -
705 MIN(idlecheck_time
, MIN(least_idle
,
706 time_since_last_resume
));
710 if (next_time
<= 0) {
711 if (is_ok2shutdown(now
)) {
713 * Setup the autowakeup alarm. Clear it
714 * right after poweroff, just in case if
715 * shutdown doesn't go through.
717 if (info
->pd_autoresume
)
718 tod_fd
= open(TOD
, O_RDWR
);
719 if (info
->pd_autoresume
&& tod_fd
!= -1) {
720 wakeup_time
= (*now
< f
) ? f
:
723 * A software fix for hardware
726 if ((wakeup_time
- *now
) < 180) {
728 "Since autowakeup time is less than 3 minutes away, "
729 "autoshutdown will not occur.");
730 shutdown_time
= *now
+ 180;
731 (void) close(tod_fd
);
734 if (ioctl(tod_fd
, TOD_SET_ALARM
,
735 &wakeup_time
) == -1) {
736 logerror("Unable to program TOD"
737 " alarm for autowakeup.");
738 (void) close(tod_fd
);
743 (void) poweroff("Autoshutdown",
746 if (info
->pd_autoresume
&& tod_fd
!= -1) {
747 if (ioctl(tod_fd
, TOD_CLEAR_ALARM
,
749 logerror("Unable to clear "
750 "alarm in TOD device.");
751 (void) close(tod_fd
);
755 /* wait at least 5 mins */
756 shutdown_time
= *now
+
757 ((info
->pd_idle_time
* 60) > 300 ?
758 (info
->pd_idle_time
* 60) : 300);
761 shutdown_time
= *now
+ 300;
764 shutdown_time
= *now
+ next_time
;
765 } else if (s
< f
&& *now
>= f
) {
766 shutdown_time
= s
+ DAYS_TO_SECS
;
772 is_ok2shutdown(time_t *now
)
775 char power_cycles_st
[LLEN
];
776 char power_cycle_limit_st
[LLEN
];
777 char system_board_date_st
[LLEN
];
778 int power_cycles
, power_cycle_limit
, free_cycles
, scaled_cycles
;
779 time_t life_began
, life_passed
;
780 int no_power_cycles
= 0;
781 int no_system_board_date
= 0;
786 if ((prom_fd
= open(PROM
, O_RDWR
)) == -1 &&
793 * when #power-cycles property does not exist
794 * power cycles are unlimited.
796 if (get_prom(prom_fd
, options
, "#power-cycles",
797 power_cycles_st
, sizeof (power_cycles_st
)) == 0)
800 if (get_prom(prom_fd
, root
, "power-cycle-limit",
801 power_cycle_limit_st
, sizeof (power_cycle_limit_st
)) == 0) {
802 power_cycle_limit
= DEFAULT_POWER_CYCLE_LIMIT
;
804 power_cycle_limit
= atoi(power_cycle_limit_st
);
808 * Allow 10% of power_cycle_limit as free cycles.
810 free_cycles
= power_cycle_limit
/ 10;
812 power_cycles
= atoi(power_cycles_st
);
813 if (power_cycles
< 0)
815 else if (power_cycles
<= free_cycles
)
818 if (no_power_cycles
&& log_power_cycles_error
== 0) {
819 logerror("Invalid PROM property \"#power-cycles\" was found.");
820 log_power_cycles_error
++;
823 if (get_prom(prom_fd
, options
, "system-board-date",
824 system_board_date_st
, sizeof (system_board_date_st
)) == 0) {
825 no_system_board_date
++;
827 life_began
= strtol(system_board_date_st
, (char **)NULL
, 16);
828 if (life_began
> *now
) {
829 no_system_board_date
++;
832 if (no_system_board_date
) {
833 if (log_system_board_date_error
== 0) {
834 logerror("No or invalid PROM property "
835 "\"system-board-date\" was found.");
836 log_system_board_date_error
++;
838 life_began
= DEFAULT_SYSTEM_BOARD_DATE
;
841 life_passed
= *now
- life_began
;
844 * Since we don't keep the date that last free_cycle is ended, we
845 * need to spread (power_cycle_limit - free_cycles) over the entire
846 * 7-year life span instead of (lifetime - date free_cycles ended).
848 scaled_cycles
= (int)(((float)life_passed
/ (float)LIFETIME_SECS
) *
849 (power_cycle_limit
- free_cycles
));
855 (void) fprintf(stderr
, "Actual power_cycles = %d\t"
856 "Scaled power_cycles = %d\n", power_cycles
, scaled_cycles
);
858 if (power_cycles
> scaled_cycles
) {
859 if (log_no_autoshutdown_warning
== 0) {
860 logerror("Automatic shutdown has been temporarily "
861 "suspended in order to preserve the reliability "
863 log_no_autoshutdown_warning
++;
871 (void) close(prom_fd
);
876 check_idleness(time_t *now
, hrtime_t
*hr_now
)
880 * Check idleness only when autoshutdown is enabled.
882 if (!autoshutdown_en
) {
887 info
->pd_ttychars_idle
= check_tty(hr_now
, asinfo
.ttychars_thold
);
888 info
->pd_loadaverage_idle
=
889 check_load_ave(hr_now
, asinfo
.loadaverage_thold
);
890 info
->pd_diskreads_idle
= check_disks(hr_now
, asinfo
.diskreads_thold
);
891 info
->pd_nfsreqs_idle
= check_nfs(hr_now
, asinfo
.nfsreqs_thold
);
894 (void) fprintf(stderr
, "Idle ttychars for %d secs.\n",
895 info
->pd_ttychars_idle
);
896 (void) fprintf(stderr
, "Idle loadaverage for %d secs.\n",
897 info
->pd_loadaverage_idle
);
898 (void) fprintf(stderr
, "Idle diskreads for %d secs.\n",
899 info
->pd_diskreads_idle
);
900 (void) fprintf(stderr
, "Idle nfsreqs for %d secs.\n",
901 info
->pd_nfsreqs_idle
);
904 checkidle_time
= *now
+ IDLECHK_INTERVAL
;
908 last_system_activity(hrtime_t
*hr_now
)
910 int act_idle
, latest
;
912 latest
= info
->pd_idle_time
* 60;
913 act_idle
= last_tty_activity(hr_now
, asinfo
.ttychars_thold
);
914 latest
= MIN(latest
, act_idle
);
915 act_idle
= last_load_ave_activity(hr_now
);
916 latest
= MIN(latest
, act_idle
);
917 act_idle
= last_disk_activity(hr_now
, asinfo
.diskreads_thold
);
918 latest
= MIN(latest
, act_idle
);
919 act_idle
= last_nfs_activity(hr_now
, asinfo
.nfsreqs_thold
);
920 latest
= MIN(latest
, act_idle
);
928 char pm_variable
[LLEN
];
934 * Reap any child process which has been left over.
936 while (waitpid((pid_t
)-1, &status
, WNOHANG
) > 0)
940 * Execute the user's idlecheck script and set variable PM_IDLETIME.
941 * Returned exit value is the idle time in minutes.
943 if ((child
= fork1()) == 0) {
944 (void) sprintf(pm_variable
, "PM_IDLETIME=%d",
946 (void) putenv(pm_variable
);
947 cp
= strrchr(asinfo
.idlecheck_path
, '/');
949 cp
= asinfo
.idlecheck_path
;
952 (void) execl(asinfo
.idlecheck_path
, cp
, NULL
);
954 } else if (child
== -1) {
955 return (info
->pd_idle_time
* 60);
959 * Wait until the idlecheck program completes.
961 if (waitpid(child
, &status
, 0) != child
) {
963 * We get here if the calling process gets a signal.
965 return (info
->pd_idle_time
* 60);
968 if (WEXITSTATUS(status
) < 0) {
969 return (info
->pd_idle_time
* 60);
971 return (WEXITSTATUS(status
) * 60);
976 set_alarm(time_t now
)
978 time_t itime
, stime
, next_time
, max_time
;
981 max_time
= MAX(checkidle_time
, shutdown_time
);
986 itime
= (checkidle_time
== 0) ? max_time
: checkidle_time
;
987 stime
= (shutdown_time
== 0) ? max_time
: shutdown_time
;
988 next_time
= MIN(itime
, stime
);
989 next_alarm
= (next_time
<= now
) ? 1 : (next_time
- now
);
990 (void) alarm(next_alarm
);
993 (void) fprintf(stderr
, "Currently @ %s", ctime(&now
));
994 (void) fprintf(stderr
, "Checkidle in %d secs\n", checkidle_time
- now
);
995 (void) fprintf(stderr
, "Shutdown in %d secs\n", shutdown_time
- now
);
996 (void) fprintf(stderr
, "Next alarm goes off in %d secs\n", next_alarm
);
997 (void) fprintf(stderr
, "************************************\n");
1002 poweroff(const char *msg
, char **cmd_argv
)
1004 struct stat statbuf
;
1008 char ehome
[] = "HOME=";
1009 char euser
[] = "LOGNAME=";
1013 if (mutex_trylock(&poweroff_mutex
) != 0)
1016 if (stat("/dev/console", &statbuf
) == -1 ||
1017 (pwd
= getpwuid(statbuf
.st_uid
)) == NULL
) {
1018 (void) mutex_unlock(&poweroff_mutex
);
1023 syslog(LOG_NOTICE
, msg
);
1025 if (*cmd_argv
== NULL
) {
1026 logerror("No command to run.");
1027 (void) mutex_unlock(&poweroff_mutex
);
1031 home
= malloc(strlen(pwd
->pw_dir
) + sizeof (ehome
));
1032 user
= malloc(strlen(pwd
->pw_name
) + sizeof (euser
));
1033 if (home
== NULL
|| user
== NULL
) {
1036 logerror("No memory.");
1037 (void) mutex_unlock(&poweroff_mutex
);
1040 (void) strcpy(home
, ehome
);
1041 (void) strcat(home
, pwd
->pw_dir
);
1042 (void) strcpy(user
, euser
);
1043 (void) strcat(user
, pwd
->pw_name
);
1046 * Need to simulate the user enviroment, minimaly set HOME, and USER.
1048 if ((child
= fork1()) == 0) {
1049 (void) putenv(home
);
1050 (void) putenv(user
);
1051 (void) setgid(pwd
->pw_gid
);
1052 (void) setuid(pwd
->pw_uid
);
1055 * check for shutdown flag and set environment
1057 for (ca
= cmd_argv
; *ca
; ca
++) {
1058 if (strcmp("-h", *ca
) == 0) {
1059 (void) putenv("SYSSUSPENDDODEFAULT=");
1064 (void) execv(cmd_argv
[0], cmd_argv
);
1070 (void) mutex_unlock(&poweroff_mutex
);
1075 while (pid
!= child
)
1076 pid
= wait(&status
);
1077 if (WEXITSTATUS(status
)) {
1078 (void) syslog(LOG_ERR
, "Failed to exec \"%s\".", cmd_argv
[0]);
1079 (void) mutex_unlock(&poweroff_mutex
);
1083 (void) mutex_unlock(&poweroff_mutex
);
1087 #define PBUFSIZE 256
1090 * Gets the value of a prom property at either root or options node. It
1091 * returns 1 if it is successful, otherwise it returns 0 .
1094 get_prom(int prom_fd
, prom_node_t node_name
,
1095 char *property_name
, char *property_value
, size_t len
)
1098 char buf
[PBUFSIZE
+ sizeof (uint_t
)];
1099 struct openpromio opp
;
1101 register struct openpromio
*opp
= &(oppbuf
.opp
);
1104 if (prom_fd
== -1) {
1108 switch (node_name
) {
1110 (void *) memset(oppbuf
.buf
, 0, PBUFSIZE
);
1111 opp
->oprom_size
= PBUFSIZE
;
1112 if (ioctl(prom_fd
, OPROMNEXT
, opp
) < 0) {
1117 * Passing null string will give us the first property.
1119 (void *) memset(oppbuf
.buf
, 0, PBUFSIZE
);
1121 opp
->oprom_size
= PBUFSIZE
;
1122 if (ioctl(prom_fd
, OPROMNXTPROP
, opp
) < 0) {
1125 if (strcmp(opp
->oprom_array
, property_name
) == 0) {
1129 } while (opp
->oprom_size
> 0);
1134 if (got_it
&& property_value
== NULL
) {
1137 opp
->oprom_size
= PBUFSIZE
;
1138 if (ioctl(prom_fd
, OPROMGETPROP
, opp
) < 0) {
1141 if (opp
->oprom_size
== 0) {
1142 *property_value
= '\0';
1144 estrcpy(property_value
, opp
->oprom_array
, len
);
1148 estrcpy(opp
->oprom_array
, property_name
, PBUFSIZE
);
1149 opp
->oprom_size
= PBUFSIZE
;
1150 if (ioctl(prom_fd
, OPROMGETOPT
, opp
) < 0) {
1153 if (opp
->oprom_size
== 0) {
1156 if (property_value
!= NULL
) {
1157 estrcpy(property_value
, opp
->oprom_array
, len
);
1161 logerror("Only root node and options node are supported.\n");
1168 #define isspace(ch) ((ch) == ' ' || (ch) == '\t')
1169 #define iseol(ch) ((ch) == '\n' || (ch) == '\r' || (ch) == '\f')
1173 power_button_monitor(void *arg
)
1178 if (ioctl(pb_fd
, PB_BEGIN_MONITOR
, NULL
) == -1) {
1179 logerror("Failed to monitor the power button.");
1180 thr_exit((void *) 0);
1184 pfd
.events
= POLLIN
;
1188 if (poll(&pfd
, 1, INFTIM
) == -1) {
1189 logerror("Failed to poll for power button events.");
1190 thr_exit((void *) 0);
1193 if (!(pfd
.revents
& POLLIN
))
1197 * Monitor the power button, but only take action if
1198 * gnome-power-manager is not running.
1200 * ret greater than 0 means could not find process.
1202 ret
= system("/usr/bin/pgrep -fx gnome-power-manager");
1204 if (ioctl(pfd
.fd
, PB_GET_EVENTS
, &events
) == -1) {
1205 logerror("Failed to get power button events.");
1206 thr_exit((void *) 0);
1209 if ((ret
> 0) && (events
& PB_BUTTON_PRESS
) &&
1210 (poweroff(NULL
, power_button_cmd
) != 0)) {
1211 logerror("Power button is pressed, powering "
1212 "down the system!");
1215 * Send SIGPWR signal to the init process to
1216 * shut down the system.
1218 if (kill(1, SIGPWR
) == -1)
1219 (void) uadmin(A_SHUTDOWN
, AD_POWEROFF
, 0);
1223 * Clear any power button event that has happened
1224 * meanwhile we were busy processing the last one.
1226 if (ioctl(pfd
.fd
, PB_GET_EVENTS
, &events
) == -1) {
1227 logerror("Failed to get power button events.");
1228 thr_exit((void *) 0);
1236 if (read_cpr_config() < 0)
1240 * If autopm behavior is explicitly enabled for energystar-v2, or
1241 * set to default for energystar-v3, create a new thread to attach
1244 estar_v3_prop
= asinfo
.is_autopm_default
;
1245 if ((strcmp(asinfo
.apm_behavior
, "enable") == 0) ||
1246 (estar_v3_prop
&& strcmp(asinfo
.apm_behavior
, "default") == 0)) {
1248 logerror("powerd starting device attach thread.");
1249 if (thr_create(NULL
, NULL
, attach_devices
, NULL
,
1250 THR_DAEMON
, NULL
) != 0) {
1251 logerror("Unable to create thread to attach devices.");
1258 attach_devices(void *arg
)
1260 di_node_t root_node
;
1262 (void) sleep(60); /* let booting finish first */
1264 if ((root_node
= di_init("/", DINFOFORCE
)) == DI_NODE_NIL
) {
1265 logerror("Failed to attach devices.");
1271 * Unload all the modules.
1273 (void) modctl(MODUNLOAD
, 0);
1280 * Create a file which will contain our pid. Pmconfig will check this file
1281 * to see if we are running and can use the pid to signal us. Returns the
1282 * file descriptor if successful, -1 otherwise.
1284 * Note: Deal with attempt to launch multiple instances and also with existence
1285 * of an obsolete pid file caused by an earlier abort.
1288 open_pidfile(char *me
)
1291 const char *e1
= "%s: Cannot open pid file for read: ";
1292 const char *e2
= "%s: Cannot unlink obsolete pid file: ";
1293 const char *e3
= "%s: Either another daemon is running or the"
1294 " process is defunct (pid %d). \n";
1295 const char *e4
= "%s: Cannot create pid file: ";
1298 if ((fd
= open(pidpath
, O_CREAT
| O_EXCL
| O_WRONLY
, 0444)) == -1) {
1299 if (errno
== EEXIST
) {
1303 if ((fp
= fopen(pidpath
, "r")) == NULL
) {
1304 (void) fprintf(stderr
, e1
, me
);
1311 (void) fscanf(fp
, "%ld", &pid
);
1314 if (unlink(pidpath
) == -1) {
1315 (void) fprintf(stderr
, e2
, me
);
1318 } else /* try without corrupted file */
1322 /* Is pid for a running process */
1323 if (kill(pid
, 0) == -1) {
1324 if (errno
== ESRCH
) {
1325 if (unlink(pidpath
) == -1) {
1326 (void) fprintf(stderr
, e2
, me
);
1329 } else /* try without obsolete file */
1332 } else { /* powerd deamon still running or defunct */
1333 (void) fprintf(stderr
, e3
, me
, pid
);
1337 } else { /* create failure not due to existing file */
1338 (void) fprintf(stderr
, e4
, me
);
1344 (void) fchown(fd
, (uid_t
)-1, (gid_t
)0);
1349 * Write a pid to the pid file. Report errors to syslog.
1353 write_pidfile(int fd
, pid_t pid
)
1356 int rc
= 0; /* assume success */
1358 len
= sprintf(scratch
, "%ld\n", pid
);
1359 if (write(fd
, scratch
, len
) != len
) {
1360 logerror("Cannot write pid file: %s", strerror(errno
));