PUBLIC int spin_check(spin_t *s) { /* Check whether a timeout has taken place. Return TRUE if the caller * should continue spinning, and FALSE if a timeout has occurred. The * implementation assumes that it is okay to spin a little bit too long * (up to a full clock tick extra). */ u64_t cur_tsc, tsc_delta; clock_t now, micro_delta; switch (s->s_state) { case STATE_INIT: s->s_state = STATE_BASE_TS; break; case STATE_BASE_TS: s->s_state = STATE_TS; read_tsc_64(&s->s_base_tsc); break; case STATE_TS: read_tsc_64(&cur_tsc); tsc_delta = sub64(cur_tsc, s->s_base_tsc); micro_delta = tsc_64_to_micros(tsc_delta); if (micro_delta >= s->s_usecs) { s->s_timeout = TRUE; return FALSE; } if (micro_delta >= TSC_SPIN) { s->s_usecs -= micro_delta; getuptime(&s->s_base_uptime); s->s_state = STATE_UPTIME; } break; case STATE_UPTIME: getuptime(&now); /* We assume that sys_hz() caches its return value. */ micro_delta = ((now - s->s_base_uptime) * 1000 / sys_hz()) * 1000; if (micro_delta >= s->s_usecs) { s->s_timeout = TRUE; return FALSE; } break; default: panic("spin_check: invalid state %d", s->s_state); } return TRUE; }
/*========================================= * Shutting down (Program did not crash ^^) * - Log our current up time *----------------------------------------- */ int sig_final () { time_t curtime; char curtime2[24]; FILE *fp; long seconds = 0, day = 24*60*60, hour = 60*60, minute = 60, days = 0, hours = 0, minutes = 0; fp = fopen("log/uptime.log","a"); if (fp) { time(&curtime); strftime(curtime2, 24, "%m/%d/%Y %H:%M:%S", localtime(&curtime)); seconds = getuptime(); days = seconds/day; seconds -= (seconds/day>0)?(seconds/day)*day:0; hours = seconds/hour; seconds -= (seconds/hour>0)?(seconds/hour)*hour:0; minutes = seconds/minute; seconds -= (seconds/minute>0)?(seconds/minute)*minute:0; fprintf(fp, "%s: %s %s - %ld days, %ld hours, %ld minutes, %ld seconds.\n", curtime2, server_name, (crash_flag ? "crashed" : "uptime"), days, hours, minutes, seconds); fclose(fp); } return 1; }
/*===========================================================================* * flt_alarm * *===========================================================================*/ clock_t flt_alarm(clock_t dt) { int r; if(dt < 0) return next_alarm; r = sys_setalarm(dt, 0); if(r != OK) panic("sys_setalarm failed: %d", r); if(dt == 0) { if(!next_alarm) panic("clearing unset alarm: %d", r); next_alarm = 0; } else { if(next_alarm) panic("overwriting alarm: %d", r); if ((r = getuptime(&next_alarm)) != OK) panic("getuptime failed: %d", r); next_alarm += dt; } return next_alarm; }
/*===========================================================================* * sigaction_dmp * *===========================================================================*/ PUBLIC void sigaction_dmp() { struct mproc *mp; int i, n=0; static int prev_i = 0; clock_t uptime; printf("Process manager (PM) signal action dump\n"); getsysinfo(PM_PROC_NR, SI_PROC_TAB, mproc); getuptime(&uptime); printf("-process- -nr- --ignore- --catch- --block- -tomess- -pending- -alarm---\n"); for (i=prev_i; i<NR_PROCS; i++) { mp = &mproc[i]; if (mp->mp_pid == 0 && i != PM_PROC_NR) continue; if (++n > 22) break; printf("%8.8s %3d ", mp->mp_name, i); printf(" %08x %08x %08x %08x ", mp->mp_ignore, mp->mp_catch, mp->mp_sigmask, mp->mp_sig2mess); printf("%08x ", mp->mp_sigpending); if (mp->mp_flags & ALARM_ON) printf("%8u", mp->mp_timer.tmr_exp_time-uptime); else printf(" -"); printf("\n"); } if (i >= NR_PROCS) i = 0; else printf("--more--\r"); prev_i = i; }
static void frame_timer_callback(void *data) { struct timeval prev; getuptime(&prev); frame++; if (frame >= FRAMES) frame = 0; update_canvas(frame_canvas, frames[frame]); struct timeval cur; getuptime(&cur); plan_frame_timer(tv_sub_diff(&cur, &prev)); }
/*===========================================================================* * do_gettime * *===========================================================================*/ int do_gettime(void) { clock_t ticks, realtime, clock; time_t boottime; int s; if ( (s=getuptime(&ticks, &realtime, &boottime)) != OK) panic("do_time couldn't get uptime: %d", s); switch (m_in.m_lc_pm_time.clk_id) { case CLOCK_REALTIME: clock = realtime; break; case CLOCK_MONOTONIC: clock = ticks; break; default: return EINVAL; /* invalid/unsupported clock_id */ } mp->mp_reply.m_pm_lc_time.sec = boottime + (clock / system_hz); mp->mp_reply.m_pm_lc_time.nsec = (uint32_t) ((clock % system_hz) * 1000000000ULL / system_hz); return(OK); }
/* ** Name: void reply(dpeth_t *dep, int err) ** Function: Fills a DL_TASK_REPLY reply message and sends it. */ static void reply(dpeth_t * dep, int err) { message reply; int status = FALSE; if (dep->de_flags & DEF_ACK_SEND) status |= DL_PACK_SEND; if (dep->de_flags & DEF_ACK_RECV) status |= DL_PACK_RECV; reply.m_type = DL_TASK_REPLY; reply.DL_PORT = dep - de_table; reply.DL_PROC = dep->de_client; reply.DL_STAT = status /* | ((u32_t) err << 16) */; reply.DL_COUNT = dep->de_read_s; getuptime(&reply.DL_CLCK); DEBUG(printf("\t reply %d (%ld)\n", reply.m_type, reply.DL_STAT)); if ((status = send(dep->de_client, &reply)) == OK) { dep->de_read_s = 0; dep->de_flags &= NOT(DEF_ACK_SEND | DEF_ACK_RECV); } else if (status != ELOCKED || err == OK) panic(dep->de_name, SendErrMsg, status); return; }
/*===========================================================================* * sigaction_dmp * *===========================================================================*/ void sigaction_dmp() { struct mproc *mp; int i, n=0; static int prev_i = 0; clock_t uptime; if (getsysinfo(PM_PROC_NR, SI_PROC_TAB, mproc, sizeof(mproc)) != OK) { printf("Error obtaining table from PM. Perhaps recompile IS?\n"); return; } getuptime(&uptime); printf("Process manager (PM) signal action dump\n"); printf("-process- -nr- --ignore- --catch- --block- -pending- -alarm---\n"); for (i=prev_i; i<NR_PROCS; i++) { mp = &mproc[i]; if (mp->mp_pid == 0 && i != PM_PROC_NR) continue; if (++n > 22) break; printf("%8.8s %3d ", mp->mp_name, i); printf(" %08lx %08lx %08lx ", mp->mp_ignore, mp->mp_catch, mp->mp_sigmask); printf("%08lx ", mp->mp_sigpending); if (mp->mp_flags & ALARM_ON) printf("%8d", mp->mp_timer.tmr_exp_time-uptime); else printf(" -"); printf("\n"); } if (i >= NR_PROCS) i = 0; else printf("--more--\r"); prev_i = i; }
/***************************************************************************** * get_current_clock * ****************************************************************************/ static myclock_t get_current_clock() { /* returns the current clock tick */ myclock_t ret; getuptime(&ret); return ret; }
int main (int argc, char **argv) { // base values int status, intvalue; int upminutes, uphours, updays; double value, uptime; char* perf; char* output_message; /* Parse extra opts if any */ argv = np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); value = getuptime(); if (verbose >= 3) { printf("Uptime in seconds returned from timespec struct: %f\n", value); } intvalue = (int)value; updays = intvalue / 86400; uphours = (intvalue % 86400) / 3600; upminutes = ((intvalue % 86400) % 3600) / 60; if (!strncmp(timeunit, "minutes", strlen("minutes"))) { uptime = intvalue / 60; } else if (!strncmp(timeunit, "hours", strlen("hours"))) { uptime = intvalue / 3600; } else if (!strncmp(timeunit, "days", strlen("days"))) { uptime = intvalue / 86400; } else { uptime = intvalue; } xasprintf(&output_message,_("%u day(s) %u hour(s) %u minute(s)"), updays, uphours, upminutes); xasprintf(&perf,_("%s"), fperfdata("uptime", uptime, "", my_thresholds->warning?TRUE:FALSE, my_thresholds->warning?my_thresholds->warning->end:0, my_thresholds->critical?TRUE:FALSE, my_thresholds->critical?my_thresholds->critical->end:0, FALSE, 0, FALSE, 0) ); status = get_status(uptime, my_thresholds); if (status == STATE_OK) { printf("Uptime %s: %s | %s\n", _("OK"), output_message, perf); } else if (status == STATE_WARNING) { printf("Uptime %s: %s | %s\n", _("WARNING"), output_message, perf); } else if (status == STATE_CRITICAL) { printf("Uptime %s: %s | %s\n", _("CRITICAL"), output_message, perf); } return status; } // end main
static void print_uptime(void) { struct timeval uptime; getuptime(&uptime); printf("%s: Up %ld days, %ld hours, %ld minutes, %ld seconds\n", NAME, uptime.tv_sec / DAY, (uptime.tv_sec % DAY) / HOUR, (uptime.tv_sec % HOUR) / MINUTE, uptime.tv_sec % MINUTE); }
static void dointr(void) { unsigned long *intrcnt, uptime; uint64_t inttotal; size_t clen, inamlen, intrcntlen, istrnamlen; unsigned int i, nintr; char *intrname, *tintrname; uptime = getuptime(); if (kd != NULL) { kread(X_SINTRCNT, &intrcntlen, sizeof(intrcntlen)); kread(X_SINTRNAMES, &inamlen, sizeof(inamlen)); if ((intrcnt = malloc(intrcntlen)) == NULL || (intrname = malloc(inamlen)) == NULL) err(1, "malloc()"); kread(X_INTRCNT, intrcnt, intrcntlen); kread(X_INTRNAMES, intrname, inamlen); } else { for (intrcnt = NULL, intrcntlen = 1024; ; intrcntlen *= 2) { if ((intrcnt = reallocf(intrcnt, intrcntlen)) == NULL) err(1, "reallocf()"); if (mysysctl("hw.intrcnt", intrcnt, &intrcntlen, NULL, 0) == 0) break; } for (intrname = NULL, inamlen = 1024; ; inamlen *= 2) { if ((intrname = reallocf(intrname, inamlen)) == NULL) err(1, "reallocf()"); if (mysysctl("hw.intrnames", intrname, &inamlen, NULL, 0) == 0) break; } } nintr = intrcntlen / sizeof(unsigned long); tintrname = intrname; istrnamlen = strlen("interrupt"); for (i = 0; i < nintr; i++) { clen = strlen(tintrname); if (clen > istrnamlen) istrnamlen = clen; tintrname += clen + 1; } (void)printf("%-*s %20s %10s\n", (int)istrnamlen, "interrupt", "total", "rate"); inttotal = 0; for (i = 0; i < nintr; i++) { if (intrname[0] != '\0' && (*intrcnt != 0 || aflag)) (void)printf("%-*s %20lu %10lu\n", (int)istrnamlen, intrname, *intrcnt, *intrcnt / uptime); intrname += strlen(intrname) + 1; inttotal += *intrcnt++; } (void)printf("%-*s %20" PRIu64 " %10" PRIu64 "\n", (int)istrnamlen, "Total", inttotal, inttotal / uptime); }
char *HandleUptimeCmd(char *buf, char *arg, int index) { char *tmp = buf; if (!arg) arg = "s"; switch (*arg) { case 's': case 'S': topcase: strcpy(tmp, "System uptime: "); tmp += 15; tmp += GetUptimeString(getuptime(), tmp); if (arg) { break; } else { strcpy(tmp, " | "); tmp += 5; } case 'l': case 'L': strcpy(tmp, "Loaded uptime: "); tmp += 15; tmp += GetUptimeString(getuptime() - loadedtime, tmp); if (arg) { break; } else { strcpy(tmp, " | "); tmp += 5; } case 'c': case 'C': strcpy(tmp, "Connection uptime: "); tmp += 19; tmp += GetUptimeString(getuptime() - bot[index]->connectedtime, tmp); break; default: arg = NULL; goto topcase; } return buf; }
/* ** Name: void el3_send(dpeth_t *dep, int count) ** Function: Send function. Called from main to transit a packet or ** from interrupt handler when Tx FIFO gets available. */ static void el3_send(dpeth_t * dep, int from_int, int count) { clock_t now; int ix; short int TxStatus; getuptime(&now); if ((dep->de_flags & DEF_XMIT_BUSY) && (now - dep->de_xmit_start) > 4) { DEBUG(printf("3c509: Transmitter timed out. Resetting ....\n");)
/*===========================================================================* * root_uptime * *===========================================================================*/ static void root_uptime(void) { /* Print the current uptime. */ clock_t ticks; ldiv_t division; if (getuptime(&ticks) != OK) return; division = ldiv(100L * ticks / sys_hz(), 100L); buf_printf("%ld.%0.2ld\n", division.quot, division.rem); }
/*===========================================================================* * do_time * *===========================================================================*/ PUBLIC int do_time() { /* Perform the time(tp) system call. This returns the time in seconds since * 1.1.1970. MINIX is an astrophysically naive system that assumes the earth * rotates at a constant rate and that such things as leap seconds do not * exist. */ clock_t uptime; int s; if ( (s=getuptime(&uptime)) != OK) panic(__FILE__,"do_time couldn't get uptime", s); mp->mp_reply.reply_time = (time_t) (boottime + (uptime/HZ)); mp->mp_reply.reply_utime = (uptime%HZ)*1000000/HZ; return(OK); }
void setup_chat_banner(dccchat_t *chat) { char *tempstr; tempstr = mymalloc(maxtextlength); getuptime(tempstr, 0, gdata.startuptime, maxtextlength); writedccchat(chat, 0, "Welcome to %s\n", get_user_nick()); writedccchat(chat, 0, "iroffer-dinoex " VERSIONLONG "%s%s\n", gdata.hideos ? "" : " - ", gdata.hideos ? "" : gdata.osstring); writedccchat(chat, 0, " running %s\n", tempstr); writedccchat(chat, 0, " \n"); writedccchat(chat, 0, "Enter Your Password:\n"); mydelete(tempstr); }
/*===========================================================================* * set_timer * *===========================================================================*/ void set_timer(timer_t *tp, int ticks, tmr_func_t watchdog, int arg) { int r; clock_t now, prev_time = 0, next_time; if ((r = getuptime(&now)) != OK) panic("set_timer: couldn't get uptime"); /* Set timer argument and add timer to the list. */ tmr_arg(tp)->ta_int = arg; prev_time = tmrs_settimer(&timers, tp, now+ticks, watchdog, &next_time); /* Reschedule our synchronous alarm if necessary. */ if (expiring == 0 && (! prev_time || prev_time > next_time)) { if (sys_setalarm(next_time, 1) != OK) panic("set_timer: couldn't set alarm"); } }
/*===========================================================================* * clock_time * *===========================================================================*/ time_t clock_time() { /* This routine returns the time in seconds since 1.1.1970. MINIX is an * astrophysically naive system that assumes the earth rotates at a constant * rate and that such things as leap seconds do not exist. */ register int r; clock_t uptime; clock_t realtime; time_t boottime; r = getuptime(&uptime, &realtime, &boottime); if (r != OK) panic("clock_time err: %d", r); return( (time_t) (boottime + (realtime/system_hz))); }
/*===========================================================================* * pm_set_timer * *===========================================================================*/ PUBLIC void pm_set_timer(timer_t *tp, int ticks, tmr_func_t watchdog, int arg) { int r; clock_t now, prev_time = 0, next_time; if ((r = getuptime(&now)) != OK) panic(__FILE__, "PM couldn't get uptime", NO_NUM); /* Set timer argument and add timer to the list. */ tmr_arg(tp)->ta_int = arg; prev_time = tmrs_settimer(&pm_timers,tp,now+ticks,watchdog,&next_time); /* Reschedule our synchronous alarm if necessary. */ if (! prev_time || prev_time > next_time) { if (sys_setalarm(next_time, 1) != OK) panic(__FILE__, "PM set timer couldn't set alarm.", NO_NUM); } return; }
/*===========================================================================* * do_stime * *===========================================================================*/ PUBLIC int do_stime() { /* Perform the stime(tp) system call. Retrieve the system's uptime (ticks * since boot) and store the time in seconds at system boot in the global * variable 'boottime'. */ clock_t uptime; int s; if (mp->mp_effuid != SUPER_USER) { return(EPERM); } if ( (s=getuptime(&uptime)) != OK) panic(__FILE__,"do_stime couldn't get uptime", s); boottime = (long) m_in.stime - (uptime/HZ); /* Also inform FS about the new system time. */ tell_fs(STIME, boottime, 0, 0); return(OK); }
/*===========================================================================* * sef_cb_init_fresh * *===========================================================================*/ static int sef_cb_init_fresh(int type, sef_init_info_t *UNUSED(info)) { clock_t uptime; int r; /* Parse the given parameters. */ if (env_argc > 1) optset_parse(optset_table, env_argv[1]); if (driver_label[0] == '\0') panic("no driver label given"); if (ds_retrieve_label_endpt(driver_label, &driver_endpt)) panic("unable to resolve driver label"); if (driver_minor > 255) panic("no or invalid driver minor given"); #if DEBUG printf("FBD: driver label '%s' (endpt %d), minor %d\n", driver_label, driver_endpt, driver_minor); #endif /* Initialize resources. */ fbd_buf = alloc_contig(BUF_SIZE, 0, NULL); assert(fbd_buf != NULL); if ((r = getuptime(&uptime)) != OK) panic("getuptime failed (%d)\n", r); srand48(uptime); /* Announce we are up! */ blockdriver_announce(type); return OK; }
/*===========================================================================* * do_stime * *===========================================================================*/ int do_stime(void) { /* Perform the stime(tp) system call. Retrieve the system's uptime (ticks * since boot) and pass the new time in seconds at system boot to the kernel. */ clock_t uptime, realtime; time_t boottime; int s; if (mp->mp_effuid != SUPER_USER) { return(EPERM); } if ( (s=getuptime(&uptime, &realtime, &boottime)) != OK) panic("do_stime couldn't get uptime: %d", s); boottime = m_in.m_lc_pm_time.sec - (realtime/system_hz); s= sys_stime(boottime); /* Tell kernel about boottime */ if (s != OK) panic("pm: sys_stime failed: %d", s); return(OK); }
/*===========================================================================* * clock_timespec * *===========================================================================*/ struct timespec clock_timespec(void) { /* This routine returns the time in seconds since 1.1.1970. MINIX is an * astrophysically naive system that assumes the earth rotates at a constant * rate and that such things as leap seconds do not exist. */ register int r; struct timespec tv; clock_t uptime; clock_t realtime; time_t boottime; r = getuptime(&uptime, &realtime, &boottime); if (r != OK) panic("clock_timespec err: %d", r); tv.tv_sec = (time_t) (boottime + (realtime/system_hz)); /* We do not want to overflow, and system_hz can be as high as 50kHz */ assert(system_hz < LONG_MAX/40000); tv.tv_nsec = (realtime%system_hz) * 40000 / system_hz * 25000; return tv; }
static void my_uptime(RESULT * result, const int argc, RESULT * argv[]) { int age; static double uptime = 0.0; static struct timeval last_value; struct timeval now; if (argc > 1) { error("uptime(): wrong number of parameters"); SetResult(&result, R_STRING, ""); return; } gettimeofday(&now, NULL); age = (now.tv_sec - last_value.tv_sec) * 1000 + (now.tv_usec - last_value.tv_usec) / 1000; /* reread every 100 msec only */ if (fd == -2 || age == 0 || age > 100) { uptime = getuptime(); if (uptime < 0.0) { error("parse(/proc/uptime) failed!"); SetResult(&result, R_STRING, ""); return; } last_value = now; } if (argc == 0) { SetResult(&result, R_NUMBER, &uptime); } else { SetResult(&result, R_STRING, struptime(uptime, R2S(argv[0]))); } return; }
int fibril_condvar_wait_timeout(fibril_condvar_t *fcv, fibril_mutex_t *fm, suseconds_t timeout) { awaiter_t wdata; assert(fibril_mutex_is_locked(fm)); if (timeout < 0) return ETIMEOUT; awaiter_initialize(&wdata); wdata.fid = fibril_get_id(); wdata.to_event.inlist = timeout > 0; wdata.wu_event.inlist = true; futex_down(&async_futex); if (timeout) { getuptime(&wdata.to_event.expires); tv_add(&wdata.to_event.expires, timeout); async_insert_timeout(&wdata); } list_append(&wdata.wu_event.link, &fcv->waiters); _fibril_mutex_unlock_unsafe(fm); fibril_switch(FIBRIL_TO_MANAGER); fibril_mutex_lock(fm); /* async_futex not held after fibril_switch() */ futex_down(&async_futex); if (wdata.to_event.inlist) list_remove(&wdata.to_event.link); if (wdata.wu_event.inlist) list_remove(&wdata.wu_event.link); futex_up(&async_futex); return wdata.to_event.occurred ? ETIMEOUT : EOK; }
static void dovmstat(unsigned int interval, int reps) { struct vmtotal total; time_t uptime, halfuptime; struct devinfo *tmp_dinfo; size_t size; int ncpus, maxid; u_long cpumask; int rate_adj; uptime = getuptime() / 1000000000LL; halfuptime = uptime / 2; rate_adj = 1; ncpus = 1; maxid = 0; /* * If the user stops the program (control-Z) and then resumes it, * print out the header again. */ (void)signal(SIGCONT, needhdr); /* * If our standard output is a tty, then install a SIGWINCH handler * and set wresized so that our first iteration through the main * vmstat loop will peek at the terminal's current rows to find out * how many lines can fit in a screenful of output. */ if (isatty(fileno(stdout)) != 0) { wresized = 1; (void)signal(SIGWINCH, needresize); } else { wresized = 0; winlines = VMSTAT_DEFAULT_LINES; } if (kd != NULL) { if (namelist[X_STATHZ].n_type != 0 && namelist[X_STATHZ].n_value != 0) kread(X_STATHZ, &hz, sizeof(hz)); if (!hz) kread(X_HZ, &hz, sizeof(hz)); } else { struct clockinfo clockrate; size = sizeof(clockrate); mysysctl("kern.clockrate", &clockrate, &size, NULL, 0); if (size != sizeof(clockrate)) errx(1, "clockrate size mismatch"); hz = clockrate.hz; } if (Pflag) { ncpus = getcpuinfo(&cpumask, &maxid); size_cp_times = sizeof(long) * (maxid + 1) * CPUSTATES; cur_cp_times = calloc(1, size_cp_times); last_cp_times = calloc(1, size_cp_times); } for (hdrcnt = 1;;) { if (!--hdrcnt) printhdr(maxid, cpumask); if (kd != NULL) { if (kvm_getcptime(kd, cur.cp_time) < 0) errx(1, "kvm_getcptime: %s", kvm_geterr(kd)); } else { size = sizeof(cur.cp_time); mysysctl("kern.cp_time", &cur.cp_time, &size, NULL, 0); if (size != sizeof(cur.cp_time)) errx(1, "cp_time size mismatch"); } if (Pflag) { size = size_cp_times; mysysctl("kern.cp_times", cur_cp_times, &size, NULL, 0); if (size != size_cp_times) errx(1, "cp_times mismatch"); } tmp_dinfo = last.dinfo; last.dinfo = cur.dinfo; cur.dinfo = tmp_dinfo; last.snap_time = cur.snap_time; /* * Here what we want to do is refresh our device stats. * getdevs() returns 1 when the device list has changed. * If the device list has changed, we want to go through * the selection process again, in case a device that we * were previously displaying has gone away. */ switch (devstat_getdevs(NULL, &cur)) { case -1: errx(1, "%s", devstat_errbuf); break; case 1: { int retval; num_devices = cur.dinfo->numdevs; generation = cur.dinfo->generation; retval = devstat_selectdevs(&dev_select, &num_selected, &num_selections, &select_generation, generation, cur.dinfo->devices, num_devices, matches, num_matches, specified_devices, num_devices_specified, select_mode, maxshowdevs, 0); switch (retval) { case -1: errx(1, "%s", devstat_errbuf); break; case 1: printhdr(maxid, cpumask); break; default: break; } } default: break; } fill_vmmeter(&sum); fill_vmtotal(&total); (void)printf("%1d %1d %1d", total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw); #define vmstat_pgtok(a) ((a) * (sum.v_page_size >> 10)) #define rate(x) (((x) * rate_adj + halfuptime) / uptime) /* round */ if (hflag) { printf(""); prthuman(total.t_avm * (u_int64_t)sum.v_page_size, 5); printf(" "); prthuman(total.t_free * (u_int64_t)sum.v_page_size, 5); printf(" "); (void)printf("%5lu ", (unsigned long)rate(sum.v_vm_faults - osum.v_vm_faults)); } else { printf(" %7d", vmstat_pgtok(total.t_avm)); printf(" %7d ", vmstat_pgtok(total.t_free)); (void)printf("%4lu ", (unsigned long)rate(sum.v_vm_faults - osum.v_vm_faults)); } (void)printf("%3lu ", (unsigned long)rate(sum.v_reactivated - osum.v_reactivated)); (void)printf("%3lu ", (unsigned long)rate(sum.v_swapin + sum.v_vnodein - (osum.v_swapin + osum.v_vnodein))); (void)printf("%3lu ", (unsigned long)rate(sum.v_swapout + sum.v_vnodeout - (osum.v_swapout + osum.v_vnodeout))); (void)printf("%5lu ", (unsigned long)rate(sum.v_tfree - osum.v_tfree)); (void)printf("%4lu ", (unsigned long)rate(sum.v_pdpages - osum.v_pdpages)); devstats(); (void)printf("%4lu %5lu %5lu", (unsigned long)rate(sum.v_intr - osum.v_intr), (unsigned long)rate(sum.v_syscall - osum.v_syscall), (unsigned long)rate(sum.v_swtch - osum.v_swtch)); if (Pflag) pcpustats(ncpus, cpumask, maxid); else cpustats(); (void)printf("\n"); (void)fflush(stdout); if (reps >= 0 && --reps <= 0) break; osum = sum; uptime = interval; rate_adj = 1000; /* * We round upward to avoid losing low-frequency events * (i.e., >= 1 per interval but < 1 per millisecond). */ if (interval != 1) halfuptime = (uptime + 1) / 2; else halfuptime = 0; (void)usleep(interval * 1000); } }
unsigned char * var_extensible_vmstat(struct variable *vp, oid * name, size_t * length, int exact, size_t * var_len, WriteMethod ** write_method) { int loop; time_t time_new = getuptime(); static time_t time_old; static time_t time_diff; #if defined(KERN_CP_TIME) static uint64_t cpu_old[CPUSTATES]; static uint64_t cpu_new[CPUSTATES]; static uint64_t cpu_diff[CPUSTATES]; static uint64_t cpu_total; #elif defined(KERN_CPTIME) static long cpu_old[CPUSTATES]; static long cpu_new[CPUSTATES]; static long cpu_diff[CPUSTATES]; static long cpu_total; #else static long cpu_old[CPUSTATES]; static long cpu_new[CPUSTATES]; static long cpu_diff[CPUSTATES]; static long cpu_total; #endif long cpu_sum; double cpu_prc; static struct uvmexp mem_old, mem_new; int mem_mib[] = { CTL_VM, VM_UVMEXP }; int mem_size = sizeof(struct uvmexp); static long long_ret; static char errmsg[300]; long_ret = 0; /* set to 0 as default */ if (header_generic(vp, name, length, exact, var_len, write_method)) return (NULL); /* * Update structures (only if time has passed) */ if (time_new != time_old) { #ifdef KERN_CP_TIME int mib[2] = { CTL_KERN, KERN_CP_TIME }; int ssize = sizeof(cpu_new); if (sysctl(mib, 2, cpu_new, &ssize, NULL, 0) < 0) memset(cpu_new, 0, sizeof(cpu_new)); #elif defined(KERN_CPTIME) int mib[2] = { CTL_KERN, KERN_CPTIME }; int ssize = sizeof(cpu_new); if (sysctl(mib, 2, cpu_new, &ssize, NULL, 0) < 0) memset(cpu_new, 0, sizeof(cpu_new)); #else /* * CPU usage */ auto_nlist(CPTIME_SYMBOL, (char *) cpu_new, sizeof(cpu_new)); #endif time_diff = time_new - time_old; time_old = time_new; cpu_total = 0; for (loop = 0; loop < CPUSTATES; loop++) { cpu_diff[loop] = cpu_new[loop] - cpu_old[loop]; cpu_old[loop] = cpu_new[loop]; cpu_total += cpu_diff[loop]; } if (cpu_total == 0) cpu_total = 1; /* * Memory info */ mem_old = mem_new; sysctl(mem_mib, 2, &mem_new, &mem_size, NULL, 0); } /* * Rate macro */ #define rate(x) (((x)+ time_diff/2) / time_diff) /* * Page-to-kb macro */ #define ptok(p) ((p) * (mem_new.pagesize >> 10)) switch (vp->magic) { case MIBINDEX: long_ret = 1; return ((u_char *) (&long_ret)); case ERRORNAME: /* dummy name */ sprintf(errmsg, "systemStats"); *var_len = strlen(errmsg); return ((u_char *) (errmsg)); case SWAPIN: long_ret = ptok(mem_new.swapins - mem_old.swapins); long_ret = rate(long_ret); return ((u_char *) (&long_ret)); case SWAPOUT: long_ret = ptok(mem_new.swapouts - mem_old.swapouts); long_ret = rate(long_ret); return ((u_char *) (&long_ret)); case IOSENT: #if NETSNMP_NO_DUMMY_VALUES return NULL; #endif long_ret = -1; return ((u_char *) (&long_ret)); case IORECEIVE: #if NETSNMP_NO_DUMMY_VALUES return NULL; #endif long_ret = -1; return ((u_char *) (&long_ret)); case SYSINTERRUPTS: long_ret = rate(mem_new.intrs - mem_old.intrs); return ((u_char *) (&long_ret)); case SYSCONTEXT: long_ret = rate(mem_new.swtch - mem_old.swtch); return ((u_char *) (&long_ret)); case CPUUSER: cpu_sum = cpu_diff[CP_USER] + cpu_diff[CP_NICE]; cpu_prc = (float) cpu_sum / (float) cpu_total; long_ret = cpu_prc * CPU_PRC; return ((u_char *) (&long_ret)); case CPUSYSTEM: cpu_sum = cpu_diff[CP_SYS] + cpu_diff[CP_INTR]; cpu_prc = (float) cpu_sum / (float) cpu_total; long_ret = cpu_prc * CPU_PRC; return ((u_char *) (&long_ret)); case CPUIDLE: cpu_sum = cpu_diff[CP_IDLE]; cpu_prc = (float) cpu_sum / (float) cpu_total; long_ret = cpu_prc * CPU_PRC; return ((u_char *) (&long_ret)); case CPURAWUSER: long_ret = cpu_new[CP_USER]; return ((u_char *) (&long_ret)); case CPURAWNICE: long_ret = cpu_new[CP_NICE]; return ((u_char *) (&long_ret)); case CPURAWSYSTEM: long_ret = cpu_new[CP_SYS] + cpu_new[CP_INTR]; return ((u_char *) (&long_ret)); case CPURAWIDLE: long_ret = cpu_new[CP_IDLE]; return ((u_char *) (&long_ret)); case CPURAWKERNEL: long_ret = cpu_new[CP_SYS]; return ((u_char *) (&long_ret)); case CPURAWINTR: long_ret = cpu_new[CP_INTR]; return ((u_char *) (&long_ret)); /* * reserved for future use */ /* * case ERRORFLAG: * return((u_char *) (&long_ret)); * case ERRORMSG: * return((u_char *) (&long_ret)); */ } return NULL; }
int main(int argc, char **argv) { char text[256]; int i; #ifdef _WIN32 HMODULE hLib; WSADATA wsadata; WSAStartup(0x0202, &wsadata); InitUptimePerfCounter(); hLib = LoadLibrary("advapi32.dll"); if (hLib) lpfnRtlGenRandom = (_RtlGenRandom)GetProcAddress(hLib, "SystemFunction036"); #ifdef _DEBUG _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_CHECK_CRT_DF | _CRTDBG_ALLOC_MEM_DF); #endif #endif GetOS(text); printf("\n -- Phyros " BOT_VER " -- %s --\n\n", text); loadedtime = getuptime(); #ifndef _WIN32 SetPipeSignalHandler(); if (getuid() == 0) { printf("WARNING: should not be running as root!\n"); setuid(GetUidFromUsername("nobody")); } //////should set the group id instead so files can be modified at runtime #endif botpluser = malloc(sizeof(LUSER)); botpluser->access = 103; strcpy(botpluser->username, "the bot"); maintid = get_self_tid(); #ifndef _DEBUG SetSegvSignalHandler(); #endif tagbans[WCP_BACK] = RadixInit(); tagbans[WCP_FRONT] = RadixInit(); tagbans[WCP_BOTH] = RadixInit(); phrases = RadixInit(); cdkeys = VectorInit(8); //banqueue = malloc(BANQUEUE_INITIALSIZE * sizeof(char *)); //bqsize = BANQUEUE_INITIALSIZE; SetDefaultConfig(); LoadConfig(); LoadUsers(); LoadCDKeys(); GetRealms(); BlacklistLoad(); LoadPhrases(); CmdTreeInit(); LoadAccessModifications(); ParseCmdLine(argc, argv); for (i = 0; i != 3; i++) { if (!hashes[i][0]) { gstate |= GFS_USEBNLS; printf("WARNING: path for binary \'%s\' not set, falling back to BNLS checkrevision\n", hash_filenames[i]); break; } } if (gstate & GFS_CHECKUPDATES) { printf(" - checking %s%s for updates...\n", updatesite, updateverfile); printf("%s\n", updateresult[CheckUpdate(updatesite, updateverfile)]); } CreateAsyncTimer(); ptimertid = _CreateThread(PeriodicTimerWaitProc, NULL); AddPeriodicTimer(TIMER_NULLPKT, 10, NullPacketTimerProc); setjmp(jmpenv); ////////////////////////////////////////////TEST BATTERY////////////////////////////////////// /*ChatHandleChannel("Clan Blah", 0, 0); //ChatHandleJoin("loladfg", 0, 43, "PXES 0 0 0 0 0 PXES", 0, 0); ChatHandleJoin("loladf1aaaaaaaaaa", 0, 43, "PXES 0 0 0 0 0 PXES", 0, 0); ChatHandleJoin("loladf2bbbbbfffe", 0, 43, "PXES 0 0 0 0 0 PXES", 0, 0); ChatHandleJoin("loladf3", 0, 43, "PXES 0 0 0 0 0 PXES", 0, 0); ChatHandleJoin("loladf4", 0, 43, "PXES 0 0 0 0 0 PXES", 0, 0); ChatHandleJoin("loladf5", 0, 43, "PXES 0 0 0 0 0 PXES", 0, 0); ChatHandleJoin("loladf6", 0, 43, "PXES 0 0 0 0 0 PXES", 0, 0); ChatHandleJoin("loladf7", 0, 43, "PXES 0 0 0 0 0 PXES", 0, 0); ChatHandleJoin("loladf8", 0, 43, "PXES 0 0 0 0 0 PXES", 0, 0); ChatHandleJoin("loladf9", 0, 43, "PXES 0 0 0 0 0 PXES", 0, 0); ChatHandleJoin("loladfa", 0, 43, "PXES 0 0 0 0 0 PXES", 0, 0); ChatHandleJoin("loladfb", 0, 43, "PXES 0 0 0 0 0 PXES", 0, 0); ChatHandleJoin("loladfc", 0, 43, "PXES 0 0 0 0 0 PXES", 0, 0); ChatHandleJoin("loladfd", 0, 43, "PXES 0 0 0 0 0 PXES", 0, 0); */ /*printf("%x\n", FindTextInWildcards(tagbans, "asdfgdfg")); printf("%x\n", FindTextInWildcards(tagbans, "as[tg]gdfg")); printf("%x\n", FindTextInWildcards(tagbans, "asdfgdfg[tg]")); printf("%x\n", FindTextInWildcards(tagbans, "asdfgdfg")); printf("%x\n", FindPhraseban(phrases, "raiasdfdasdfzomgzasdfasdfasdfasdf")); printf("%x\n", FindPhraseban(phrases, "raiasdfgdfgbloop")); printf("%x\n", FindPhraseban(phrases, "bloo asfukdfgdfg zomg"));*/ ///////////////////////////////////////////////////////////////////////////////////////////// while (1) { fgets(text, sizeof(text), stdin); text[strlen(text) - 1] = 0; if (*(int16_t *)text == '//') CheckCommand(NULL, text, 0, 0); else QueueAdd(text, curbotinc()); } return 0; }
/*===========================================================================* * sef_cb_init_fresh * *===========================================================================*/ PRIVATE int sef_cb_init_fresh(int type, sef_init_info_t *info) { /* Initialize the reincarnation server. */ struct boot_image *ip; int s,i; int nr_image_srvs, nr_image_priv_srvs, nr_uncaught_init_srvs; struct rproc *rp; struct rproc *replica_rp; struct rprocpub *rpub; struct boot_image image[NR_BOOT_PROCS]; struct boot_image_priv *boot_image_priv; struct boot_image_sys *boot_image_sys; struct boot_image_dev *boot_image_dev; int pid, replica_pid; endpoint_t replica_endpoint; int ipc_to; int *calls; int all_c[] = { ALL_C, NULL_C }; int no_c[] = { NULL_C }; /* See if we run in verbose mode. */ env_parse("rs_verbose", "d", 0, &rs_verbose, 0, 1); if ((s = sys_getinfo(GET_HZ, &system_hz, sizeof(system_hz), 0, 0)) != OK) panic("Cannot get system timer frequency\n"); /* Initialize the global init descriptor. */ rinit.rproctab_gid = cpf_grant_direct(ANY, (vir_bytes) rprocpub, sizeof(rprocpub), CPF_READ); if(!GRANT_VALID(rinit.rproctab_gid)) { panic("unable to create rprocpub table grant: %d", rinit.rproctab_gid); } /* Initialize some global variables. */ rupdate.flags = 0; shutting_down = FALSE; /* Get a copy of the boot image table. */ if ((s = sys_getimage(image)) != OK) { panic("unable to get copy of boot image table: %d", s); } /* Determine the number of system services in the boot image table. */ nr_image_srvs = 0; for(i=0;i<NR_BOOT_PROCS;i++) { ip = &image[i]; /* System services only. */ if(iskerneln(_ENDPOINT_P(ip->endpoint))) { continue; } nr_image_srvs++; } /* Determine the number of entries in the boot image priv table and make sure * it matches the number of system services in the boot image table. */ nr_image_priv_srvs = 0; for (i=0; boot_image_priv_table[i].endpoint != NULL_BOOT_NR; i++) { boot_image_priv = &boot_image_priv_table[i]; /* System services only. */ if(iskerneln(_ENDPOINT_P(boot_image_priv->endpoint))) { continue; } nr_image_priv_srvs++; } if(nr_image_srvs != nr_image_priv_srvs) { panic("boot image table and boot image priv table mismatch"); } /* Reset the system process table. */ for (rp=BEG_RPROC_ADDR; rp<END_RPROC_ADDR; rp++) { rp->r_flags = 0; rp->r_pub = &rprocpub[rp - rproc]; rp->r_pub->in_use = FALSE; } /* Initialize the system process table in 4 steps, each of them following * the appearance of system services in the boot image priv table. * - Step 1: set priviliges, sys properties, and dev properties (if any) * for every system service. */ for (i=0; boot_image_priv_table[i].endpoint != NULL_BOOT_NR; i++) { boot_image_priv = &boot_image_priv_table[i]; /* System services only. */ if(iskerneln(_ENDPOINT_P(boot_image_priv->endpoint))) { continue; } /* Lookup the corresponding entries in other tables. */ boot_image_info_lookup(boot_image_priv->endpoint, image, &ip, NULL, &boot_image_sys, &boot_image_dev); rp = &rproc[boot_image_priv - boot_image_priv_table]; rpub = rp->r_pub; /* * Set privileges. */ /* Get label. */ strcpy(rpub->label, boot_image_priv->label); /* Force a static priv id for system services in the boot image. */ rp->r_priv.s_id = static_priv_id( _ENDPOINT_P(boot_image_priv->endpoint)); /* Initialize privilege bitmaps and signal manager. */ rp->r_priv.s_flags = boot_image_priv->flags; /* priv flags */ rp->r_priv.s_trap_mask= SRV_OR_USR(rp, SRV_T, USR_T); /* traps */ ipc_to = SRV_OR_USR(rp, SRV_M, USR_M); /* targets */ fill_send_mask(&rp->r_priv.s_ipc_to, ipc_to == ALL_M); rp->r_priv.s_sig_mgr= SRV_OR_USR(rp, SRV_SM, USR_SM); /* sig mgr */ rp->r_priv.s_bak_sig_mgr = NONE; /* backup sig mgr */ /* Initialize kernel call mask bitmap. */ calls = SRV_OR_USR(rp, SRV_KC, USR_KC) == ALL_C ? all_c : no_c; fill_call_mask(calls, NR_SYS_CALLS, rp->r_priv.s_k_call_mask, KERNEL_CALL, TRUE); /* Set the privilege structure. */ if(boot_image_priv->endpoint != RS_PROC_NR) { if ((s = sys_privctl(ip->endpoint, SYS_PRIV_SET_SYS, &(rp->r_priv))) != OK) { panic("unable to set privilege structure: %d", s); } } /* Synch the privilege structure with the kernel. */ if ((s = sys_getpriv(&(rp->r_priv), ip->endpoint)) != OK) { panic("unable to synch privilege structure: %d", s); } /* * Set sys properties. */ rpub->sys_flags = boot_image_sys->flags; /* sys flags */ /* * Set dev properties. */ rpub->dev_flags = boot_image_dev->flags; /* device flags */ rpub->dev_nr = boot_image_dev->dev_nr; /* major device number */ rpub->dev_style = boot_image_dev->dev_style; /* device style */ rpub->dev_style2 = boot_image_dev->dev_style2; /* device style 2 */ /* Get process name. */ strcpy(rpub->proc_name, ip->proc_name); /* Build command settings. */ rp->r_cmd[0]= '\0'; rp->r_script[0]= '\0'; build_cmd_dep(rp); /* Initialize vm call mask bitmap. */ calls = SRV_OR_USR(rp, SRV_VC, USR_VC) == ALL_C ? all_c : no_c; fill_call_mask(calls, NR_VM_CALLS, rpub->vm_call_mask, VM_RQ_BASE, TRUE); /* Scheduling parameters. */ rp->r_scheduler = SRV_OR_USR(rp, SRV_SCH, USR_SCH); rp->r_priority = SRV_OR_USR(rp, SRV_Q, USR_Q); rp->r_quantum = SRV_OR_USR(rp, SRV_QT, USR_QT); /* Get some settings from the boot image table. */ rpub->endpoint = ip->endpoint; /* Set some defaults. */ rp->r_old_rp = NULL; /* no old version yet */ rp->r_new_rp = NULL; /* no new version yet */ rp->r_prev_rp = NULL; /* no prev replica yet */ rp->r_next_rp = NULL; /* no next replica yet */ rp->r_uid = 0; /* root */ rp->r_check_tm = 0; /* not checked yet */ getuptime(&rp->r_alive_tm); /* currently alive */ rp->r_stop_tm = 0; /* not exiting yet */ rp->r_restarts = 0; /* no restarts so far */ rp->r_period = 0; /* no period yet */ rp->r_exec = NULL; /* no in-memory copy yet */ rp->r_exec_len = 0; /* Mark as in use and active. */ rp->r_flags = RS_IN_USE | RS_ACTIVE; rproc_ptr[_ENDPOINT_P(rpub->endpoint)]= rp; rpub->in_use = TRUE; } /* - Step 2: allow every system service in the boot image to run. */ nr_uncaught_init_srvs = 0; for (i=0; boot_image_priv_table[i].endpoint != NULL_BOOT_NR; i++) { boot_image_priv = &boot_image_priv_table[i]; /* System services only. */ if(iskerneln(_ENDPOINT_P(boot_image_priv->endpoint))) { continue; } /* Lookup the corresponding slot in the system process table. */ rp = &rproc[boot_image_priv - boot_image_priv_table]; rpub = rp->r_pub; /* RS is already running as we speak. */ if(boot_image_priv->endpoint == RS_PROC_NR) { if ((s = init_service(rp, SEF_INIT_FRESH)) != OK) { panic("unable to initialize RS: %d", s); } continue; } /* Allow the service to run. */ if ((s = sched_init_proc(rp)) != OK) { panic("unable to initialize scheduling: %d", s); } if ((s = sys_privctl(rpub->endpoint, SYS_PRIV_ALLOW, NULL)) != OK) { panic("unable to initialize privileges: %d", s); } /* Initialize service. We assume every service will always get * back to us here at boot time. */ if(boot_image_priv->flags & SYS_PROC) { if ((s = init_service(rp, SEF_INIT_FRESH)) != OK) { panic("unable to initialize service: %d", s); } if(rpub->sys_flags & SF_SYNCH_BOOT) { /* Catch init ready message now to synchronize. */ catch_boot_init_ready(rpub->endpoint); } else { /* Catch init ready message later. */ nr_uncaught_init_srvs++; } } } /* - Step 3: let every system service complete initialization by * catching all the init ready messages left. */ while(nr_uncaught_init_srvs) { catch_boot_init_ready(ANY); nr_uncaught_init_srvs--; } /* - Step 4: all the system services in the boot image are now running. * Complete the initialization of the system process table in collaboration * with other system services. */ for (i=0; boot_image_priv_table[i].endpoint != NULL_BOOT_NR; i++) { boot_image_priv = &boot_image_priv_table[i]; /* System services only. */ if(iskerneln(_ENDPOINT_P(boot_image_priv->endpoint))) { continue; } /* Lookup the corresponding slot in the system process table. */ rp = &rproc[boot_image_priv - boot_image_priv_table]; rpub = rp->r_pub; /* Get pid from PM. */ rp->r_pid = getnpid(rpub->endpoint); if(rp->r_pid == -1) { panic("unable to get pid"); } } /* Set alarm to periodically check service status. */ if (OK != (s=sys_setalarm(RS_DELTA_T, 0))) panic("couldn't set alarm: %d", s); /* Now create a new RS instance with a private page table and let the current * instance live update into the replica. Clone RS' own slot first. */ rp = rproc_ptr[_ENDPOINT_P(RS_PROC_NR)]; if((s = clone_slot(rp, &replica_rp)) != OK) { panic("unable to clone current RS instance: %d", s); } /* Fork a new RS instance. */ pid = srv_fork(); if(pid == -1) { panic("unable to fork a new RS instance"); } replica_pid = pid ? pid : getpid(); replica_endpoint = getnprocnr(replica_pid); replica_rp->r_pid = replica_pid; replica_rp->r_pub->endpoint = replica_endpoint; if(pid == 0) { /* New RS instance running. */ /* Live update the old instance into the new one. */ s = update_service(&rp, &replica_rp, RS_SWAP); if(s != OK) { panic("unable to live update RS: %d", s); } cpf_reload(); /* Clean up the old RS instance, the new instance will take over. */ cleanup_service(rp); /* Map out our own text and data. */ unmap_ok = 1; _minix_unmapzero(); /* Ask VM to pin memory for the new RS instance. */ if((s = vm_memctl(RS_PROC_NR, VM_RS_MEM_PIN)) != OK) { panic("unable to pin memory for the new RS instance: %d", s); } } else { /* Old RS instance running. */ /* Set up privileges for the new instance and let it run. */ s = sys_privctl(replica_endpoint, SYS_PRIV_SET_SYS, &(replica_rp->r_priv)); if(s != OK) { panic("unable to set privileges for the new RS instance: %d", s); } if ((s = sched_init_proc(replica_rp)) != OK) { panic("unable to initialize RS replica scheduling: %d", s); } s = sys_privctl(replica_endpoint, SYS_PRIV_YIELD, NULL); if(s != OK) { panic("unable to yield control to the new RS instance: %d", s); } NOT_REACHABLE; } return(OK); }