File indexing completed on 2024-05-12 05:11:16

0001 /* This file is part of the KDE Project
0002    SPDX-FileCopyrightText: 2008 Sebastian Trueg <trueg@kde.org>
0003 
0004    Parts of this file are based on code from Strigi
0005    SPDX-FileCopyrightText: 2006-2007 Jos van den Oever <jos@vandenoever.info>
0006 
0007    SPDX-License-Identifier: LGPL-2.0-or-later
0008 */
0009 
0010 #include "priority.h"
0011 
0012 #ifndef _GNU_SOURCE
0013 #define _GNU_SOURCE
0014 #endif
0015 
0016 #include <QDebug>
0017 
0018 #ifndef _WIN32
0019 #include <cerrno>
0020 #include <sys/resource.h>
0021 #include <sys/syscall.h>
0022 #include <unistd.h>
0023 
0024 #include <sched.h>
0025 #endif
0026 
0027 #ifdef SYS_ioprio_set
0028 namespace
0029 {
0030 #ifndef IOPRIO_CLASS_IDLE
0031 enum { IOPRIO_CLASS_NONE, IOPRIO_CLASS_RT, IOPRIO_CLASS_BE, IOPRIO_CLASS_IDLE };
0032 #endif
0033 
0034 #ifndef IOPRIO_WHO_PROCESS
0035 enum { IOPRIO_WHO_PROCESS = 1, IOPRIO_WHO_PGRP, IOPRIO_WHO_USER };
0036 #endif
0037 
0038 #ifndef IOPRIO_CLASS_SHIFT
0039 const int IOPRIO_CLASS_SHIFT = 13;
0040 #endif
0041 }
0042 #endif
0043 
0044 bool lowerIOPriority()
0045 {
0046 #ifdef SYS_ioprio_set
0047     if (syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, 0, IOPRIO_CLASS_IDLE << IOPRIO_CLASS_SHIFT) < 0) {
0048         qDebug("cannot set io scheduling to idle (%s). Trying best effort.\n", strerror(errno));
0049         if (syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, 0, 7 | IOPRIO_CLASS_BE << IOPRIO_CLASS_SHIFT) < 0) {
0050             qDebug("cannot set io scheduling to best effort.\n");
0051             return false;
0052         }
0053     }
0054     return true;
0055 #else
0056     return false;
0057 #endif
0058 }
0059 
0060 bool lowerPriority()
0061 {
0062 #ifndef Q_OS_WIN
0063     return !setpriority(PRIO_PROCESS, 0, 19);
0064 #else
0065     return false;
0066 #endif
0067 }
0068 
0069 bool lowerSchedulingPriority()
0070 {
0071 #ifdef SCHED_BATCH
0072     struct sched_param param;
0073     memset(&param, 0, sizeof(param));
0074     param.sched_priority = 0;
0075     return !sched_setscheduler(0, SCHED_BATCH, &param);
0076 #else
0077     return false;
0078 #endif
0079 }
0080 
0081 bool setIdleSchedulingPriority()
0082 {
0083 #ifdef SCHED_IDLE
0084     struct sched_param param;
0085     memset(&param, 0, sizeof(param));
0086     param.sched_priority = 0;
0087     return !sched_setscheduler(0, SCHED_IDLE, &param);
0088 #else
0089     return false;
0090 #endif
0091 }