/*  slowNice.c  version 0.3  */

/* This program scans for processes with niceness value of 19
 and tries to place these processes on DOWNCLOCKED CPU CORES 2 AND 3
 via taskset, to set their affinities to these cores.
 
 The program is intended to be useful when used in conjunction with appropriate
 cpufreq-set batch commands that downclock cores that nice-value-19 processes are
 restricted to.
 
 BACKGROUND
 
 My objective in writing this program was to run BOINC processes which 
 are in no hurry to complete under conditions that would minimally affect 
 system performance and added energy consumption.
 
 In typical non-stress situations, when two or more cores are not utilized,
 downclocking two cores to near minimal clock rate and running full load under 
 these downclocked cores, will minimize additional system energy consumption, 
 minimize cpu heat and fan usage, and increase memory bandwidth to programs that 
 are not niced to the maximal value of 19 (and that tend to run on Cores 0 and 1). 
 For a BOINC setup on a quad core processor, you are effectively making your 
 machine act like a dual core while donating the other two cores to BOINC computation.
 Since little heat is generated and little power used by the slow cores, this
 leaves a lot of opportunity for the main cores to enter boosted turbo clock rates.
 
 NOTES AND POINTERS TO SETTING UP THIS SOFTWARE:
 
 This original source code is written for quad core running under Linux. 
 It can easily be modified to suit systems with higher CPU counts. 
 
Important note #1:
  To realize any benefits you must manually downclock these cores 
 via cpu-freq by running something like:
	cpufreq-set -c 3 -u 1.0GHz
	cpufreq-set -c 2 -u 1.0GHz
(modify the above to your desired frequency, as is allowable or sensible for your hardware.
run the cpufreq-info command to see the upper and lower limits of your CPU clock rate. If this
does not work you need to install a package via "apt-get install cpufrequtils" or by
consulting: https://wiki.debian.org/HowTo/CpuFrequencyScaling ).

This executable (after you've compiled this source with gcc) can be run before or after
changing the CPU configurations. 

Both the taskset and the executable likely need to be run with administrator 
priviledges.

To run all cores at unrestricted normal speeds again, run cpufreq-set again with the 
appropriate upper (non-turbo) clock rate. In my case this would be:
	cpufreq-set -c 3 -u 1.6GHz
	cpufreq-set -c 2 -u 1.6GHz
Replace 1.6GHz above with a value desired and appropriate for your hardware.

You may want to write two scripts 'downclock.run' and 'upclock.run' for
convenience; sample scripts may be provided. 

Important note #2:
 Use this program at your own risk. This small program is currently in testing status and 
so far has been tested under few configurations: so far, my Llano based laptop, which 
has 4 physical cores and 0 logical cores, of the K10 core variety. 

I've also briefly tested it on a Steamroller/Bulldozer based desktop which cluster the CPUs in 
pairs (hence the change from the previous version, ver 0.1, of restricted cores from '1,2' to '2,3'). 

I don't know what effect cpufreq-set would have on logical cores in hyperthreading processors.

Important note #3: I don't recommend using this program if you have an abundance 
(very large number of) niced-to-value-19 processes that are all active and running.
Moving them to just two downclocked cores will slow down their execution 
significantly.
 
Note #4: All nice value 19 tasks that were taskset to Cores 3,2 will remain 
taskset to those cores unless you exit the program via pressing ctrl-c. 
Hitting ctr-c will place them on UNRESTRICTED_CPUS . 

Change the pound defines strings RESTRICTED_CPUS and UNRESTRICTED_CPUS to suit your needs.
Currently they are set for a quad core processor.



this program version 0.3 detects user idle via xprintidle and have the option of
automatically unrestricting the niced processes and call cpufreq-set to downclock all cores
to a specified moderate speed. This will allow BOINC processes to run at high or low duty depending
on whether the user is idle or not. 

     ____________________________________________________________
 
 Notes:
 
 compile with:
    
    gcc -o slowNicest slowNice19.c
 
 run under administrator using su or sudo bash
 (eg sudo nice ./slowNicest )
 
 
 The polling frequency in the loop is set to 5 seconds. If desired, 
 adjust to something reasonable. 
     ___________________________________________________________
 
 Email ee@freeshell.org for bug reports, issues, questions.


  Copyleft 2015, B Laubsch.
    ____________________________________________________________
   

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.


*/

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <signal.h>
#include <unistd.h>


// THIS WORKS FOR QUAD CORES, FOR HEXA OR OCTA CORES REPLACE 0-3 WITH 0-5 OR 0-7 :
#define RESTRICED_CPUS "2,3"
#define UNRESTRICED_CPUS "0-3"

#define IDLE_TIME_msec 392000

#define DEBUG_MODE 0 

void INTquitRoutine(int);

void unrestrictNiceProcesses();

int parse19(FILE* fp) // index 1 corresponds to first entry
{ int i,j=-111;	    // return value of -111 on error.
  char c;
  for (i=j=0;j<99999&&i<18;j++) 
  {  fscanf(fp,"%c",&c); //  putc(c,stdout); puts(".");
     if (c==' ') i++; // number of spaces=i
     // if (c==' ') puts("----------------------------------------");
  }    
  i=fscanf(fp,"%d",&j);
  if (i==1) return j;
  else return -111;
}

int processNiceness(char* psf)
{ int DebugMode=0;
  DIR* dp;
  FILE* fp;
  struct dirent *entp;
  char c;
  int i,j,isNum;
  
  if ((fp=fopen(psf,"r"))==NULL) 
    {printf("\n!!!couldn't open stat file %s!!!\n",psf); return -1;}
  
  j=parse19(fp);
  if (DEBUG_MODE)
   printf("The Niceness is: %d\n",j);
  if (j==19)
   if (DebugMode) printf(" %s Niceness is: %d\n",psf,j);
  fclose(fp);
  return j;
}

int addNicePs(int ps,int* niceList) // return 1 on added 
{ int i,j;		     	     // return 0 on redundant no-add
  j=niceList[0]; // j is elements in list
  for (i=1;i<=j;i++) if (niceList[i]==ps) return(0);
  niceList[0]=j=j+1;
  niceList[j]=ps;
  return(1);
}

int main_loop(int* niceList)
{
  DIR* dp;
  struct dirent *entp;
  char c;
  int i,j;
  int isNum;
  char statfilepath[256];
  char commandstr[256];

  if ((dp = opendir("/proc/")) == NULL) 
  { printf("cannot open dir\n"); return -1; }

  while((entp=readdir(dp))!=NULL)
  {  isNum=0;
     c=entp->d_name[0];
     if (c>='0') if (c<='9') isNum=1;
     if (isNum) 
     {	sscanf(entp->d_name,"%d",&i);
      	//printf("possible number directory %s = %d\n", entp->d_name , i );
	sprintf(statfilepath,"/proc/%d/stat",i);
	if (DEBUG_MODE)
 	 printf("\n Trying to open %s...",statfilepath);
	j=processNiceness(statfilepath);
	sprintf(commandstr,"/usr/bin/taskset -p -c %s %d",RESTRICED_CPUS,i);
	if (j==19) if(addNicePs(i,niceList))
	{  printf("RUNNING %s\n",commandstr );
	   system(commandstr);
	}
     }

  }
  closedir(dp);
  return 1;
}


void greeting() {
  printf("--PRESS ctrl-C to unrestrict and re-taskset processes to CPUs 0-3 and Exit program--\n");
  printf("--PRESS ctrl-%c to EXIT immediately without further action.\n\n",'\\');
}

			// GLOBAL VARIABLES
    int niceList[21000];// maximum number of tracked nice processes is 20999
    			// niceList[0] is number of elements counter.


int readIdleTime()
{ int k;
  FILE *stream;
  stream=popen("/usr/bin/xprintidle","r");
  fscanf(stream, "%d\n", &k);
  fclose(stream);
  return(k);
}

int main(int argc, char *argv[])
{   int i;
    char commandstr[256];
    long long unsigned int u;
    int state,idleState; 
    state=idleState=0;
    
    for (i=0;i<21000;i++) niceList[i]=0;
    
    printf("  v 0.3 . Copyleft 2015. Modify this program to suit your own needs.\n");
    printf("See source code for usage instructions and notes.\n ");
    printf("IMPORTANT NOTE: THIS PROGRAM REQUIRES THAT XPRINTIDLE IS INSTALLED;\n");
    printf("IF xprintidle is not installed PRESS CTRL-C now, and run sudo apt-get install xprintidle\n\n");
 
    printf("Note, this PROGRAM comes with ABSOLUTELY NO WARRANTY.\n");
    greeting();
    
    signal(SIGINT,INTquitRoutine);
    
    printf("Setting cores to asymmetric frequency by running script ./asymClock.run\n");
    system("./asymClock.run");
    
    for(u=0;1;u++) 
    {
       if (state==0) main_loop(niceList);
       sleep(7);
       if ((u%12)==0) printf(".");  // minute mark tick
       if ((u%60)==0) greeting();
       idleState=readIdleTime();
       if (state==0) if (idleState>=IDLE_TIME_msec) 
       { state=1;
         printf("\nDownclocking and unrestricting processes. running script ./modClock.run\n");
	 system("./modClock.run");
         unrestrictNiceProcesses(); 
       }
       if (idleState<IDLE_TIME_msec) if (state==1) 
       { state=0;
         printf("\nActive state detected; running asymmetric cpu-freq script ./asymClock.run");
	 system("./asymClock.run");
         printf(" and restricting nice level 19 processes\n");
	 for (i=1;i<=niceList[0];i++) 
	 {   sprintf(commandstr,"/usr/bin/taskset -p -c %s %d",RESTRICED_CPUS,niceList[i]);
	     system(commandstr);  
	 } 
       }
    }   
    return 0;
}



void unrestrictNiceProcesses()
{  int i,p;
   char commandstr[256];
   printf(
 "\nPROGRAM IS NOW UNRESTRICTING NICED 19 PROCESSES TO CPU CORES %s .\n",UNRESTRICED_CPUS);
   for (i=1;i<=niceList[0];i++)
   {  	p=niceList[i];
   	sprintf(commandstr,"/usr/bin/taskset -p -c %s %d",UNRESTRICED_CPUS,p);
   	printf("RUNNING %s\n",commandstr );
	system(commandstr);
   }

}


void INTquitRoutine(int sig)
{  int i,p;
   char commandstr[256];
   printf("\nPROGRAM IS NOW UNRESTRICTING NICED 19 PROCESSES TO CPU CORES %s AND EXITING.\n",UNRESTRICED_CPUS);
   for (i=1;i<=niceList[0];i++)
   {  	p=niceList[i];
   	sprintf(commandstr,"/usr/bin/taskset -p -c %s %d",UNRESTRICED_CPUS,p);
   	printf("RUNNING %s\n",commandstr );
	system(commandstr);
	printf("RUNNING moderate cpu-freq script ./modClock.run and EXITING\n");
	system("./modClock.run");
	printf("Clockrates may have been changed, use command cpufreq-set to set clockrates ");
	printf("back to desired states. Type 'man cpufreq-set' for more information.\n"); 
	
   }
   
   exit(0);;
}




/**
    REFERENCES AND RESOURCES USED:
    
    I am not a programmer; here is my probably incomplete list of resources used 
    to build this program:
  
  http://superuser.com/questions/191092/linux-command-to-know-the-processor-number-in-which-a-process-is-loaded  
    
  http://stackoverflow.com/questions/4217037/catch-ctrl-c-in-c/4217070#4217070  
    
  http://www.delorie.com/gnu/docs/glibc/libc_481.html    

  http://askubuntu.com/questions/202136/how-can-a-script-detect-a-users-idle-time

**/


