/*
 * Copyright (C) 2000 TimeSys Corporation
 *
 * This is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * This software 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <rk/rk.h>
#include <signal.h>

rk_resource_set_t rs;

void 
print_usage(char *cmdname){
  printf("Usage: %s <resource_set> <load: ms> <period: ms> <soft-0/hard-1>\n", cmdname);
}

int 
main(int argc, char *argv[]){

  rk_reserve_t	cpu_rsv;
  /* default is 10 ms / 1 second (1%) */
  int load = 10;   
  int period = 1000; 
  int hard = 1;

  if (argc != 5){
    print_usage(argv[0]);
    return -1;
  }
  
  if ((rs = (rk_resource_set_t)atoi(argv[1])) == NULL) {
    fprintf(stderr, "%s: could not create resource set.  TimeSys RK module loaded?\n", argv[0]);
    exit(-1);
  }

  load = atoi(argv[2]);
  period = atoi(argv[3]);
  hard = atoi(argv[4]);

  {
    rk_reserve_param_data_t p; /* specify sch_mode, enforcement, replenishment */
      cpu_reserve_attr_data_t attr;

      if (hard) {
	p.enf_mode = RSV_HARD;		/* enum in rk.h   */ 
	p.sch_mode = RSV_HARD;
	p.rep_mode = RSV_HARD;
      }
      else {
 	p.enf_mode = RSV_SOFT;		/* enum in rk.h   */ 
	p.sch_mode = RSV_SOFT;
	p.rep_mode = RSV_SOFT;
      }

      attr.compute_time.tv_sec = load/1000;
      attr.compute_time.tv_nsec = (load%1000) * 1000000;
      attr.period.tv_sec = period/1000;
      attr.period.tv_nsec = (period%1000) * 1000000;
      attr.deadline = attr.period;

      printf("reserve is set for (%d,%d) in (%d,%d) w/ deadline (%d,%d) \n", 
	     (int)attr.compute_time.tv_sec,
	     (int)attr.compute_time.tv_nsec,
	     (int)attr.period.tv_sec,
	     (int)attr.period.tv_nsec,
	     (int)attr.deadline.tv_sec,
	     (int)attr.deadline.tv_nsec);
      if ((load*1000) > (period*800)) {
	printf("Load is beyond 80 percent \n");
	return (int)NULL_RESERVE;
      }
      
      attr.blocking_time.tv_sec = (long int) 0;
      attr.blocking_time.tv_nsec = (long int) 0;
      attr.start_time.tv_sec = (long int) 0;
      attr.start_time.tv_nsec = (long int) 0; 
      attr.reserve_type = p;
      cpu_rsv = rk_cpu_reserve_create(rs, &attr);
  }

  printf("Resource Set (0x%x)=(%d) CPU Reserve (0x%x)=(%d)\n", 
	 (int)rs, (int)rs, (int)cpu_rsv, (int)cpu_rsv);
  
  return (int)cpu_rsv; 
}
