1 /* This file is part of the KDE Project
2    SPDX-FileCopyrightText: 2008 Sebastian Trueg <trueg@kde.org>
3 
4    Parts of this file are based on code from Strigi
5    SPDX-FileCopyrightText: 2006-2007 Jos van den Oever <jos@vandenoever.info>
6 
7    SPDX-License-Identifier: LGPL-2.0-or-later
8 */
9 
10 #include "priority.h"
11 
12 #ifndef _GNU_SOURCE
13 #define _GNU_SOURCE
14 #endif
15 
16 #include <QDebug>
17 
18 #ifndef _WIN32
19 #include <cerrno>
20 #include <sys/resource.h>
21 #include <sys/syscall.h>
22 #include <unistd.h>
23 
24 #include <sched.h>
25 #endif
26 
27 #ifdef SYS_ioprio_set
28 namespace
29 {
30 #ifndef IOPRIO_CLASS_IDLE
31 enum { IOPRIO_CLASS_NONE, IOPRIO_CLASS_RT, IOPRIO_CLASS_BE, IOPRIO_CLASS_IDLE };
32 #endif
33 
34 #ifndef IOPRIO_WHO_PROCESS
35 enum { IOPRIO_WHO_PROCESS = 1, IOPRIO_WHO_PGRP, IOPRIO_WHO_USER };
36 #endif
37 
38 #ifndef IOPRIO_CLASS_SHIFT
39 const int IOPRIO_CLASS_SHIFT = 13;
40 #endif
41 }
42 #endif
43 
lowerIOPriority()44 bool lowerIOPriority()
45 {
46 #ifdef SYS_ioprio_set
47     if (syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, 0, IOPRIO_CLASS_IDLE << IOPRIO_CLASS_SHIFT) < 0) {
48         qDebug("cannot set io scheduling to idle (%s). Trying best effort.\n", strerror(errno));
49         if (syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, 0, 7 | IOPRIO_CLASS_BE << IOPRIO_CLASS_SHIFT) < 0) {
50             qDebug("cannot set io scheduling to best effort.\n");
51             return false;
52         }
53     }
54     return true;
55 #else
56     return false;
57 #endif
58 }
59 
lowerPriority()60 bool lowerPriority()
61 {
62 #ifndef Q_OS_WIN
63     return !setpriority(PRIO_PROCESS, 0, 19);
64 #else
65     return false;
66 #endif
67 }
68 
lowerSchedulingPriority()69 bool lowerSchedulingPriority()
70 {
71 #ifdef SCHED_BATCH
72     struct sched_param param;
73     memset(&param, 0, sizeof(param));
74     param.sched_priority = 0;
75     return !sched_setscheduler(0, SCHED_BATCH, &param);
76 #else
77     return false;
78 #endif
79 }
80 
setIdleSchedulingPriority()81 bool setIdleSchedulingPriority()
82 {
83 #ifdef SCHED_IDLE
84     struct sched_param param;
85     memset(&param, 0, sizeof(param));
86     param.sched_priority = 0;
87     return !sched_setscheduler(0, SCHED_IDLE, &param);
88 #else
89     return false;
90 #endif
91 }
92