// PyEPL: hardware/rt/realtime.cpp
//
// Copyright (C) 2003-2005 Michael J. Kahana
// Authors: Ian Schleifer, Per Sederberg, Aaron Geller, Josh Jacobs
// URL: http://memory.psych.upenn.edu/programming/pyepl
//
// Distributed under the terms of the GNU Lesser General Public License
// (LGPL). See the license.txt that came with this file.

#include "realtime.h"

#include <iostream> 
using std::cout;
using std::cerr;
using std::endl;

void set_realtime_priority(int period, int computation, int constraint)
{
       struct thread_time_constraint_policy ttcpolicy;
       int bus_speed, mib [2] = { CTL_HW, HW_BUS_FREQ };
       size_t len;   
       int ret;

       len = sizeof (bus_speed);
       sysctl (mib, 2, &bus_speed, &len, NULL, 0);

       // 120, 2400, 1200 original
       // 120, 9600, 1200 on Powerbook

       /* Is it enough? */
       ttcpolicy.period = bus_speed / period;
       ttcpolicy.computation = bus_speed / computation;
       ttcpolicy.constraint = bus_speed / constraint;
       ttcpolicy.preemptible = 1;

       ret = thread_policy_set(mach_thread_self (),
                          THREAD_TIME_CONSTRAINT_POLICY,
                          (int*)&ttcpolicy,
                          THREAD_TIME_CONSTRAINT_POLICY_COUNT);

       if (ret != KERN_SUCCESS)
       {
	 // it failed
	 cerr << "Set realtime priority failed" << endl;
       }
}
