1/******************************************************************************/
2/*                                                                            */
3/* Copyright (c) International Business Machines  Corp., 2007                 */
4/*                                                                            */
5/* This program is free software;  you can redistribute it and/or modify      */
6/* it under the terms of the GNU General Public License as published by       */
7/* the Free Software Foundation; either version 2 of the License, or          */
8/* (at your option) any later version.                                        */
9/*                                                                            */
10/* This program is distributed in the hope that it will be useful,            */
11/* but WITHOUT ANY WARRANTY;  without even the implied warranty of            */
12/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See                  */
13/* the GNU General Public License for more details.                           */
14/*                                                                            */
15/* You should have received a copy of the GNU General Public License          */
16/* along with this program;  if not, write to the Free Software               */
17/* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA    */
18/*                                                                            */
19/******************************************************************************/
20
21/******************************************************************************/
22/*                                                                            */
23/* File:        cpuctl_test02.c                                               */
24/*                                                                            */
25/* Description: This is a c program that tests the cpucontroller fairness of  */
26/*              scheduling the tasks according to their group shares. This    */
27/*              testcase tests the ability of the cpu controller to provide   */
28/*              fairness for share values (absolute).                         */
29/*                                                                            */
30/* Total Tests: 2                                                             */
31/*                                                                            */
32/* Test 04:     Nice value effect on group scheduling                         */
33/* Test 05:     Task migration test                                           */
34/*                                                                            */
35/* Test Name:   cpu_controller_test02                                         */
36/*                                                                            */
37/* Test Assertion                                                             */
38/*              Please refer to the file cpuctl_testplan.txt                  */
39/*                                                                            */
40/* Author:      Sudhir Kumar skumar@linux.vnet.ibm.com                        */
41/*                                                                            */
42/* History:                                                                   */
43/* Created-     20/12/2007 -Sudhir Kumar <skumar@linux.vnet.ibm.com>          */
44/*                                                                            */
45/******************************************************************************/
46
47#include <unistd.h>
48#include <math.h>
49#include <signal.h>
50#include <stdio.h>
51#include <stdlib.h>
52#include <string.h>
53#include <sys/resource.h>
54#include <sys/syscall.h>
55#include <sys/time.h>
56#include <sys/types.h>
57#include <sys/stat.h>
58#include <fcntl.h>
59#include <time.h>
60#include <unistd.h>
61
62#include "../libcontrollers/libcontrollers.h"
63#include "test.h"		/* LTP harness APIs */
64
65#define TIME_INTERVAL	30	/* Time interval in seconds */
66#define NUM_INTERVALS	3	/* How many iterations of TIME_INTERVAL */
67
68char *TCID = "cpuctl_test02";
69int TST_TOTAL = 1;
70pid_t scriptpid;
71char path[] = "/dev/cpuctl";
72
73extern void cleanup()
74{
75	kill(scriptpid, SIGUSR1);	/* Inform the shell to do cleanup */
76	tst_exit();		/* Report exit status */
77}
78
79int migrate_task();
80volatile int timer_expired = 0;
81
82int main(int argc, char *argv[])
83{
84
85	int test_num;
86	int task_num;
87	int len;
88	int num_cpus;		/* Total time = TIME_INTERVAL *num_cpus in the machine */
89	int migrate = 0;	/* For task migration */
90	char mygroup[FILENAME_MAX], mytaskfile[FILENAME_MAX];
91	char mysharesfile[FILENAME_MAX], ch;
92	/* Following variables are to capture parameters from script */
93	char *group_num_p, *mygroup_p, *script_pid_p, *num_cpus_p, *test_num_p,
94	    *task_num_p;
95	pid_t pid;
96	gid_t mygroup_num;	/* A number attached with a group */
97	int fd;			/* A descriptor to open a fifo for synchronized start */
98	int counter = 0;	/* To take n number of readings */
99	double total_cpu_time,	/* Accumulated cpu time */
100	 delta_cpu_time,	/* Time the task could run on cpu(s) (in an interval) */
101	 prev_cpu_time = 0;
102	double exp_cpu_time;	/* Expected time in % as obtained by shares calculation */
103
104	struct rusage cpu_usage;
105	time_t current_time, prev_time, delta_time;
106	unsigned int fmyshares, num_tasks;	/* f-> from file. num_tasks is tasks in this group */
107	struct sigaction newaction, oldaction;
108
109	mygroup_num = -1;
110	num_cpus = 0;
111	task_num = 0;
112	test_num = 0;
113
114	/* Signal handling for alarm */
115	sigemptyset(&newaction.sa_mask);
116	newaction.sa_handler = signal_handler_alarm;
117	newaction.sa_flags = 0;
118	sigaction(SIGALRM, &newaction, &oldaction);
119
120	/* Collect the parameters passed by the script */
121	group_num_p = getenv("GROUP_NUM");
122	mygroup_p = getenv("MYGROUP");
123	script_pid_p = getenv("SCRIPT_PID");
124	num_cpus_p = getenv("NUM_CPUS");
125	test_num_p = getenv("TEST_NUM");
126	task_num_p = getenv("TASK_NUM");
127	/* Check if all of them are valid */
128	if ((test_num_p != NULL)
129	    && (((test_num = atoi(test_num_p)) == 4)
130		|| ((test_num = atoi(test_num_p)) == 5))) {
131		if ((group_num_p != NULL) && (mygroup_p != NULL)
132		    && (script_pid_p != NULL) && (num_cpus_p != NULL)
133		    && (task_num_p != NULL)) {
134			mygroup_num = atoi(group_num_p);
135			scriptpid = atoi(script_pid_p);
136			num_cpus = atoi(num_cpus_p);
137			task_num = atoi(task_num_p);
138			sprintf(mygroup, "%s", mygroup_p);
139		} else {
140			tst_brkm(TBROK, cleanup,
141				 "Invalid other input parameters\n");
142		}
143	} else {
144		tst_brkm(TBROK, cleanup, "Invalid test number passed\n");
145	}
146
147	sprintf(mytaskfile, "%s", mygroup);
148	sprintf(mysharesfile, "%s", mygroup);
149	strcat(mytaskfile, "/tasks");
150	strcat(mysharesfile, "/cpu.shares");
151	pid = getpid();
152	write_to_file(mytaskfile, "a", pid);	/* Assign the task to it's group */
153
154	fd = open("./myfifo", 0);
155	if (fd == -1) {
156		tst_brkm(TBROK, cleanup,
157			 "Could not open fifo for synchronization");
158	}
159
160	read(fd, &ch, 1);	/* To block all tasks here and fire them up at the same time */
161
162	/*
163	 * We now calculate the expected % cpu time of this task by getting
164	 * it's group's shares, the total shares of all the groups and the
165	 * number of tasks in this group.
166	 */
167	FLAG = 0;
168	total_shares = 0;
169	shares_pointer = &total_shares;
170	len = strlen(path);
171	if (!strncpy(fullpath, path, len))
172		tst_brkm(TBROK, cleanup, "Could not copy directory path %s ",
173			 path);
174
175	if (scan_shares_files(shares_pointer) != 0)
176		tst_brkm(TBROK, cleanup,
177			 "From function scan_shares_files in %s ", fullpath);
178
179	/* return val: -1 in case of function error, else 2 is min share value */
180	if ((fmyshares = read_shares_file(mysharesfile)) < 2)
181		tst_brkm(TBROK, cleanup, "in reading shares files  %s ",
182			 mysharesfile);
183
184	if ((read_file(mytaskfile, GET_TASKS, &num_tasks)) < 0)
185		tst_brkm(TBROK, cleanup, "in reading tasks files  %s ",
186			 mytaskfile);
187
188	exp_cpu_time = (double)(fmyshares * 100) / (total_shares * num_tasks);
189
190	prev_time = time(NULL);	/* Note down the time */
191
192	while (1) {
193		/* Need to run some cpu intensive task, which also frequently checks the timer value */
194		double f = 274.345, mytime;	/*just a float number to take sqrt */
195		alarm(TIME_INTERVAL);
196		timer_expired = 0;
197		while (!timer_expired)	/* Let the task run on cpu for TIME_INTERVAL */
198			f = sqrt(f * f);	/* Time of this operation should not be high otherwise we can
199						 * exceed the TIME_INTERVAL to measure cpu usage
200						 */
201		current_time = time(NULL);
202		delta_time = current_time - prev_time;	/* Duration in case its not exact TIME_INTERVAL */
203
204		getrusage(0, &cpu_usage);
205		total_cpu_time = (cpu_usage.ru_utime.tv_sec + cpu_usage.ru_utime.tv_usec * 1e-6 +	/* user time */
206				  cpu_usage.ru_stime.tv_sec + cpu_usage.ru_stime.tv_usec * 1e-6);	/* system time */
207		delta_cpu_time = total_cpu_time - prev_cpu_time;
208
209		prev_cpu_time = total_cpu_time;
210		prev_time = current_time;
211
212		/* calculate % cpu time each task gets */
213		if (delta_time > TIME_INTERVAL)
214			mytime =
215			    (delta_cpu_time * 100) / (delta_time * num_cpus);
216		else
217			mytime =
218			    (delta_cpu_time * 100) / (TIME_INTERVAL * num_cpus);
219
220		fprintf(stdout, "Grp:-%3d task-%3d:CPU TIME{calc:-%6.2f(s)i.e. %6.2f(%%)exp:-%6.2f(%%)}\
221with %u(shares) in %lu (s) INTERVAL\n", mygroup_num, task_num, delta_cpu_time,
222			mytime, exp_cpu_time, fmyshares, delta_time);
223
224		counter++;
225
226		if (counter >= NUM_INTERVALS) {	/* Take n sets of readings for each shares value */
227			switch (test_num) {
228			case 4:	/* Test04 */
229				exit(0);	/* This task is done with its job */
230				break;
231			case 5:	/* Test 05 */
232				if (migrate == 0) {
233					counter = 0;
234					fprintf(stdout,
235						"FIRST RUN COMPLETED FOR TASK %d\n",
236						task_num);
237					migrate = 1;
238				} else {
239					fprintf(stdout,
240						"SECOND RUN COMPLETED FOR TASK %d\n",
241						task_num);
242					exit(0);
243				}
244				break;
245			default:
246				tst_brkm(TBROK, cleanup,
247					 "Invalid test number passed\n");
248				break;
249
250			}	/* end switch */
251		}
252		if ((migrate == 1) && (counter == 0)) {
253			if (task_num == 1) {
254				if (migrate_task() != 0)
255					tst_brkm(TFAIL, cleanup,
256						 "Could not migrate task 1 ");
257				else
258					fprintf(stdout,
259						"TASK 1 MIGRATED FROM GROUP 1 TO GROUP 2\n");
260				strcpy(mytaskfile, "/dev/cpuctl/group_2/tasks");
261			}
262			/*
263			 * Read the shares files and again calculate the cpu fraction
264			 * In test 2(case 4) we need to read tasks file as we migrate task
265			 * Q?? How to ensure other tasks do not read before task 1 migration
266			 */
267			if ((read_file(mytaskfile, GET_TASKS, &num_tasks)) < 0)
268				tst_brkm(TBROK, cleanup,
269					 "in reading tasks files  %s ",
270					 mytaskfile);
271			exp_cpu_time =
272			    (double)(fmyshares * 100) / (total_shares *
273							 num_tasks);
274		}
275	}			/* end while */
276}				/* end main */
277
278int migrate_task()
279{
280	char target[32] = "/dev/cpuctl/group_2/tasks";	/* Hard coding..Will try dynamic */
281	pid_t pid = getpid();
282	return (write_to_file(target, "a", pid));
283}
284