/*
 * libsal/syslimit/priority.c
 * Support for get/setpriority system calls
 */

/*
 * Author:
 * Stuart Herbert,
 * Academic Computng Services, The University of Sheffield
 * Email: S.Herbert@sheffield.ac.uk
 */

#include <libsal/license.h>
#include <libsal/syslimit/internal.h>
#include <libsal/proto.h>
#include <libsal/defines.h>

#if	HAS_SETPRIORITY_LIMITS
#include <sys/time.h>
#include <sys/resource.h>
#endif

#if	HAS_SCHEDCTL_LIMITS
#include <sys/schedctl.h>
#endif

int sal_syslimit_getpriority(sal_syslimit *pstLimitArg)
{
#if	HAS_SETPRIORITY_LIMITS
  TEST_ARG(pstLimitArg != NULL, 1);
  
  pstLimitArg->stLimitValue.iValue = getpriority(PRIO_PROCESS, 0);
  return 1;
#else
  return 0;
#endif
}

int sal_syslimit_setpriority(sal_syslimit *pstLimitArg)
{
#if	HAS_SETPRIORITY_LIMITS
  TEST_ARG(pstLimitArg != NULL, 1);

  sal_dprintf(SAL_DEBUG_INFO, SAL_DEBUG_MSG_DEBUGHIGH, "SCHED DEBUG: using setpriority() interface\n");
  sal_dprintf(SAL_DEBUG_INFO, SAL_DEBUG_MSG_DEBUGHIGH, "SCHED DEBUG: nice value is %d\n", pstLimitArg->stLimitValue.iValue);

#if	HAS_SCHEDCTL_LIMITS
  if (pstLimitArg->stLimitValue.iValue == 20)
  {
    sal_dprintf(SAL_DEBUG_INFO, SAL_DEBUG_MSG_DEBUGHIGH, "SCHED DEBUG: calling schedctl() to make the process weightless\n");
    schedctl (NDPRI, 0, NDPLOMAX);
    return 0;
  }
#endif

  sal_dprintf(SAL_DEBUG_INFO, SAL_DEBUG_MSG_DEBUGHIGH, "SCHED DEBUG: calling setpriority() to set the nice value\n");

  if ((setpriority(PRIO_PROCESS, 0, pstLimitArg->stLimitValue.iValue)) == -1)
    return 0;
  else
    return 1;
#else
  return 0;
#endif
}
