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