]> git.xonotic.org Git - xonotic/darkplaces.git/blob - sys_shared.c
Sys_Sleep overhaul
[xonotic/darkplaces.git] / sys_shared.c
1 #ifdef WIN32
2 # ifndef DONT_USE_SETDLLDIRECTORY
3 #  define _WIN32_WINNT 0x0502
4 # endif
5 #endif
6
7 #include "quakedef.h"
8 #include "taskqueue.h"
9 #include "thread.h"
10 #include "libcurl.h"
11
12 #define SUPPORTDLL
13
14 #ifdef WIN32
15 # include <windows.h>
16 # include <mmsystem.h> // timeGetTime
17 # include <time.h> // localtime
18 #ifdef _MSC_VER
19 #pragma comment(lib, "winmm.lib")
20 #endif
21 #else
22 # ifdef __FreeBSD__
23 #  include <sys/sysctl.h>
24 # endif
25 # include <unistd.h>
26 # include <fcntl.h>
27 # include <sys/time.h>
28 # include <time.h>
29 # ifdef SUPPORTDLL
30 #  include <dlfcn.h>
31 # endif
32 #endif
33
34 static char sys_timestring[128];
35 char *Sys_TimeString(const char *timeformat)
36 {
37         time_t mytime = time(NULL);
38 #if _MSC_VER >= 1400
39         struct tm mytm;
40         localtime_s(&mytm, &mytime);
41         strftime(sys_timestring, sizeof(sys_timestring), timeformat, &mytm);
42 #else
43         strftime(sys_timestring, sizeof(sys_timestring), timeformat, localtime(&mytime));
44 #endif
45         return sys_timestring;
46 }
47
48
49 void Sys_Quit (int returnvalue)
50 {
51         // Unlock mutexes because the quit command may jump directly here, causing a deadlock
52         if ((cmd_local)->cbuf->lock)
53                 Cbuf_Unlock((cmd_local)->cbuf);
54         SV_UnlockThreadMutex();
55         TaskQueue_Frame(true);
56
57         if (Sys_CheckParm("-profilegameonly"))
58                 Sys_AllowProfiling(false);
59         host.state = host_shutdown;
60         Host_Shutdown();
61         exit(returnvalue);
62 }
63
64 #ifdef __cplusplus
65 extern "C"
66 #endif
67 void Sys_AllowProfiling(qbool enable)
68 {
69 #ifdef __ANDROID__
70 #ifdef USE_PROFILER
71         extern void monstartup(const char *libname);
72         extern void moncleanup(void);
73         if (enable)
74                 monstartup("libmain.so");
75         else
76                 moncleanup();
77 #endif
78 #elif (defined(__linux__) && (defined(__GLIBC__) || defined(__GNU_LIBRARY__))) || defined(__FreeBSD__)
79         extern int moncontrol(int);
80         moncontrol(enable);
81 #endif
82 }
83
84
85 /*
86 ===============================================================================
87
88 DLL MANAGEMENT
89
90 ===============================================================================
91 */
92
93 static qbool Sys_LoadDependencyFunctions(dllhandle_t dllhandle, const dllfunction_t *fcts, qbool complain, qbool has_next)
94 {
95         const dllfunction_t *func;
96         if(dllhandle)
97         {
98                 for (func = fcts; func && func->name != NULL; func++)
99                         if (!(*func->funcvariable = (void *) Sys_GetProcAddress (dllhandle, func->name)))
100                         {
101                                 if(complain)
102                                 {
103                                         Con_DPrintf (" - missing function \"%s\" - broken library!", func->name);
104                                         if(has_next)
105                                                 Con_DPrintf("\nContinuing with");
106                                 }
107                                 goto notfound;
108                         }
109                 return true;
110
111         notfound:
112                 for (func = fcts; func && func->name != NULL; func++)
113                         *func->funcvariable = NULL;
114         }
115         return false;
116 }
117
118 qbool Sys_LoadSelf(dllhandle_t *handle)
119 {
120         dllhandle_t dllhandle = 0;
121
122         if (handle == NULL)
123                 return false;
124 #ifdef WIN32
125         dllhandle = LoadLibrary (NULL);
126 #else
127         dllhandle = dlopen (NULL, RTLD_NOW | RTLD_GLOBAL);
128 #endif
129         *handle = dllhandle;
130         return true;
131 }
132
133 qbool Sys_LoadDependency (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
134 {
135 #ifdef SUPPORTDLL
136         const dllfunction_t *func;
137         dllhandle_t dllhandle = 0;
138         unsigned int i;
139
140         if (handle == NULL)
141                 return false;
142
143 #ifndef WIN32
144 #ifdef PREFER_PRELOAD
145         dllhandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
146         if(Sys_LoadDependencyFunctions(dllhandle, fcts, false, false))
147         {
148                 Con_DPrintf ("All of %s's functions were already linked in! Not loading dynamically...\n", dllnames[0]);
149                 *handle = dllhandle;
150                 return true;
151         }
152         else
153                 Sys_FreeLibrary(&dllhandle);
154 notfound:
155 #endif
156 #endif
157
158         // Initializations
159         for (func = fcts; func && func->name != NULL; func++)
160                 *func->funcvariable = NULL;
161
162         // Try every possible name
163         Con_DPrintf ("Trying to load library...");
164         for (i = 0; dllnames[i] != NULL; i++)
165         {
166                 Con_DPrintf (" \"%s\"", dllnames[i]);
167 #ifdef WIN32
168 # ifndef DONT_USE_SETDLLDIRECTORY
169 #  ifdef _WIN64
170                 SetDllDirectory("bin64");
171 #  else
172                 SetDllDirectory("bin32");
173 #  endif
174 # endif
175 #endif
176                 if(Sys_LoadLibrary(dllnames[i], &dllhandle))
177                 {
178                         if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
179                                 break;
180                         else
181                                 Sys_FreeLibrary (&dllhandle);
182                 }
183         }
184
185         // see if the names can be loaded relative to the executable path
186         // (this is for Mac OSX which does not check next to the executable)
187         if (!dllhandle && strrchr(sys.argv[0], '/'))
188         {
189                 char path[MAX_OSPATH];
190                 strlcpy(path, sys.argv[0], sizeof(path));
191                 strrchr(path, '/')[1] = 0;
192                 for (i = 0; dllnames[i] != NULL; i++)
193                 {
194                         char temp[MAX_OSPATH];
195                         strlcpy(temp, path, sizeof(temp));
196                         strlcat(temp, dllnames[i], sizeof(temp));
197                         Con_DPrintf (" \"%s\"", temp);
198
199                         if(Sys_LoadLibrary(temp, &dllhandle))
200                         {
201                                 if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
202                                         break;
203                                 else
204                                         Sys_FreeLibrary (&dllhandle);
205                         }
206                 }
207         }
208
209         // No DLL found
210         if (! dllhandle)
211         {
212                 Con_DPrintf(" - failed.\n");
213                 return false;
214         }
215
216         Con_DPrintf(" - loaded.\n");
217         Con_Printf("Loaded library \"%s\"\n", dllnames[i]);
218
219         *handle = dllhandle;
220         return true;
221 #else
222         return false;
223 #endif
224 }
225
226 qbool Sys_LoadLibrary(const char *name, dllhandle_t *handle)
227 {
228         dllhandle_t dllhandle = 0;
229
230         if(handle == NULL)
231                 return false;
232
233 #ifdef SUPPORTDLL
234 # ifdef WIN32
235         dllhandle = LoadLibrary (name);
236 # else
237         dllhandle = dlopen (name, RTLD_LAZY | RTLD_GLOBAL);
238 # endif
239 #endif
240         if(!dllhandle)
241                 return false;
242
243         *handle = dllhandle;
244         return true;
245 }
246
247 void Sys_FreeLibrary (dllhandle_t* handle)
248 {
249 #ifdef SUPPORTDLL
250         if (handle == NULL || *handle == NULL)
251                 return;
252
253 #ifdef WIN32
254         FreeLibrary (*handle);
255 #else
256         dlclose (*handle);
257 #endif
258
259         *handle = NULL;
260 #endif
261 }
262
263 void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
264 {
265 #ifdef SUPPORTDLL
266 #ifdef WIN32
267         return (void *)GetProcAddress (handle, name);
268 #else
269         return (void *)dlsym (handle, name);
270 #endif
271 #else
272         return NULL;
273 #endif
274 }
275
276 #ifdef WIN32
277 # define HAVE_TIMEGETTIME 1
278 # define HAVE_QUERYPERFORMANCECOUNTER 1
279 # define HAVE_Sleep 1
280 #endif
281
282 #ifndef WIN32
283 #if defined(CLOCK_MONOTONIC) || defined(CLOCK_HIRES)
284 # define HAVE_CLOCKGETTIME 1
285 #endif
286 // FIXME improve this check, manpage hints to DST_NONE
287 # define HAVE_GETTIMEOFDAY 1
288 #endif
289
290 #ifdef FD_SET
291 # define HAVE_SELECT 1
292 #endif
293
294 #ifndef WIN32
295 // FIXME improve this check
296 # define HAVE_USLEEP 1
297 #endif
298
299 // these are referenced elsewhere
300 cvar_t sys_usenoclockbutbenchmark = {CF_SHARED, "sys_usenoclockbutbenchmark", "0", "don't use ANY real timing, and simulate a clock (for benchmarking); the game then runs as fast as possible. Run a QC mod with bots that does some stuff, then does a quit at the end, to benchmark a server. NEVER do this on a public server."};
301 cvar_t sys_libdir = {CF_READONLY | CF_SHARED, "sys_libdir", "", "Default engine library directory"};
302
303 // these are not
304 static cvar_t sys_debugsleep = {CF_SHARED, "sys_debugsleep", "0", "write requested and attained sleep times to standard output, to be used with gnuplot"};
305 static cvar_t sys_usesdlgetticks = {CF_SHARED, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (less accurate, for debugging)"};
306 static cvar_t sys_usesdldelay = {CF_SHARED, "sys_usesdldelay", "0", "use SDL_Delay() (less accurate, for debugging)"};
307 #if HAVE_QUERYPERFORMANCECOUNTER
308 static cvar_t sys_usequeryperformancecounter = {CF_SHARED | CF_ARCHIVE, "sys_usequeryperformancecounter", "0", "use windows QueryPerformanceCounter timer (which has issues on multicore/multiprocessor machines and processors which are designed to conserve power) for timing rather than timeGetTime function (which has issues on some motherboards)"};
309 #endif
310 #if HAVE_CLOCKGETTIME
311 static cvar_t sys_useclockgettime = {CF_SHARED | CF_ARCHIVE, "sys_useclockgettime", "1", "use POSIX clock_gettime function (not adjusted by NTP on some older Linux kernels) for timing rather than gettimeofday (which has issues if the system time is stepped by ntpdate, or apparently on some Xen installations)"};
312 #endif
313
314 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
315
316 /*
317 ================
318 Sys_CheckParm
319
320 Returns the position (1 to argc-1) in the program's argument list
321 where the given parameter apears, or 0 if not present
322 ================
323 */
324 int Sys_CheckParm (const char *parm)
325 {
326         int i;
327
328         for (i=1 ; i<sys.argc ; i++)
329         {
330                 if (!sys.argv[i])
331                         continue;               // NEXTSTEP sometimes clears appkit vars.
332                 if (!strcmp (parm,sys.argv[i]))
333                         return i;
334         }
335
336         return 0;
337 }
338
339 void Sys_Init_Commands (void)
340 {
341         Cvar_RegisterVariable(&sys_debugsleep);
342         Cvar_RegisterVariable(&sys_usenoclockbutbenchmark);
343         Cvar_RegisterVariable(&sys_libdir);
344 #if HAVE_TIMEGETTIME || HAVE_QUERYPERFORMANCECOUNTER || HAVE_CLOCKGETTIME || HAVE_GETTIMEOFDAY
345         if(sys_supportsdlgetticks)
346         {
347                 Cvar_RegisterVariable(&sys_usesdlgetticks);
348                 Cvar_RegisterVariable(&sys_usesdldelay);
349         }
350 #endif
351 #if HAVE_QUERYPERFORMANCECOUNTER
352         Cvar_RegisterVariable(&sys_usequeryperformancecounter);
353 #endif
354 #if HAVE_CLOCKGETTIME
355         Cvar_RegisterVariable(&sys_useclockgettime);
356 #endif
357 }
358
359 double Sys_DirtyTime(void)
360 {
361         // first all the OPTIONAL timers
362
363         // benchmark timer (fake clock)
364         if(sys_usenoclockbutbenchmark.integer)
365         {
366                 double old_benchmark_time = benchmark_time;
367                 benchmark_time += 1;
368                 if(benchmark_time == old_benchmark_time)
369                         Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
370                 return benchmark_time * 0.000001;
371         }
372 #if HAVE_QUERYPERFORMANCECOUNTER
373         if (sys_usequeryperformancecounter.integer)
374         {
375                 // LadyHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
376                 // QueryPerformanceCounter
377                 // platform:
378                 // Windows 95/98/ME/NT/2000/XP
379                 // features:
380                 // very accurate (CPU cycles)
381                 // known issues:
382                 // does not necessarily match realtime too well (tends to get faster and faster in win98)
383                 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
384                 double timescale;
385                 LARGE_INTEGER PerformanceFreq;
386                 LARGE_INTEGER PerformanceCount;
387
388                 if (QueryPerformanceFrequency (&PerformanceFreq))
389                 {
390                         QueryPerformanceCounter (&PerformanceCount);
391         
392                         timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
393                         return ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
394                 }
395                 else
396                 {
397                         Con_Printf("No hardware timer available\n");
398                         // fall back to other clock sources
399                         Cvar_SetValueQuick(&sys_usequeryperformancecounter, false);
400                 }
401         }
402 #endif
403
404 #if HAVE_CLOCKGETTIME
405         if (sys_useclockgettime.integer)
406         {
407                 struct timespec ts;
408 #  ifdef CLOCK_MONOTONIC
409                 // linux
410                 clock_gettime(CLOCK_MONOTONIC, &ts);
411 #  else
412                 // sunos
413                 clock_gettime(CLOCK_HIGHRES, &ts);
414 #  endif
415                 return (double) ts.tv_sec + ts.tv_nsec / 1000000000.0;
416         }
417 #endif
418
419         // now all the FALLBACK timers
420         if(sys_supportsdlgetticks && sys_usesdlgetticks.integer)
421                 return (double) Sys_SDL_GetTicks() / 1000.0;
422 #if HAVE_GETTIMEOFDAY
423         {
424                 struct timeval tp;
425                 gettimeofday(&tp, NULL);
426                 return (double) tp.tv_sec + tp.tv_usec / 1000000.0;
427         }
428 #elif HAVE_TIMEGETTIME
429         {
430                 static int firsttimegettime = true;
431                 // timeGetTime
432                 // platform:
433                 // Windows 95/98/ME/NT/2000/XP
434                 // features:
435                 // reasonable accuracy (millisecond)
436                 // issues:
437                 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
438
439                 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
440                 if (firsttimegettime)
441                 {
442                         timeBeginPeriod(1);
443                         firsttimegettime = false;
444                 }
445
446                 return (double) timeGetTime() / 1000.0;
447         }
448 #else
449         // fallback for using the SDL timer if no other timer is available
450         // this calls Sys_Error() if not linking against SDL
451         return (double) Sys_SDL_GetTicks() / 1000.0;
452 #endif
453 }
454
455 extern cvar_t host_maxwait;
456 double Sys_Sleep(double time)
457 {
458         double dt;
459         uint32_t microseconds;
460
461         // convert to microseconds
462         time *= 1000000.0;
463
464         if(host_maxwait.value <= 0)
465                 time = min(time, 1000000.0);
466         else
467                 time = min(time, host_maxwait.value * 1000.0);
468
469         if (time < 1 || host.restless)
470                 return 0; // not sleeping this frame
471
472         microseconds = time; // post-validation to prevent overflow
473
474         if(sys_usenoclockbutbenchmark.integer)
475         {
476                 double old_benchmark_time = benchmark_time;
477                 benchmark_time += microseconds;
478                 if(benchmark_time == old_benchmark_time)
479                         Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
480                 return 0;
481         }
482
483         if(sys_debugsleep.integer)
484                 Sys_Printf("sys_debugsleep: requesting %u ", microseconds);
485         dt = Sys_DirtyTime();
486
487         // less important on newer libcurl so no need to disturb dedicated servers
488         if (cls.state != ca_dedicated && Curl_Select(microseconds))
489         {
490                 // a transfer is ready or we finished sleeping
491         }
492         else if(sys_supportsdlgetticks && sys_usesdldelay.integer)
493                 Sys_SDL_Delay(microseconds / 1000);
494 #if HAVE_SELECT
495         else
496         {
497                 struct timeval tv;
498                 lhnetsocket_t *s;
499                 fd_set fdreadset;
500                 int lastfd = -1;
501
502                 FD_ZERO(&fdreadset);
503                 if (cls.state == ca_dedicated && sv_checkforpacketsduringsleep.integer)
504                 {
505                         List_For_Each_Entry(s, &lhnet_socketlist.list, lhnetsocket_t, list)
506                         {
507                                 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
508                                 {
509                                         if (lastfd < s->inetsocket)
510                                                 lastfd = s->inetsocket;
511         #if defined(WIN32) && !defined(_MSC_VER)
512                                         FD_SET((int)s->inetsocket, &fdreadset);
513         #else
514                                         FD_SET((unsigned int)s->inetsocket, &fdreadset);
515         #endif
516                                 }
517                         }
518                 }
519                 tv.tv_sec = microseconds / 1000000;
520                 tv.tv_usec = microseconds % 1000000;
521                 // on Win32, select() cannot be used with all three FD list args being NULL according to MSDN
522                 // (so much for POSIX...)
523                 // bones_was_here: but a zeroed fd_set seems to be tolerated (tested on Win 7)
524                 select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
525         }
526 #elif HAVE_USLEEP
527         else
528                 usleep(microseconds);
529 #elif HAVE_Sleep
530         else
531                 Sleep(microseconds / 1000);
532 #else
533         else
534                 Sys_SDL_Delay(microseconds / 1000);
535 #endif
536
537         dt = Sys_DirtyTime() - dt;
538         if(sys_debugsleep.integer)
539                 Sys_Printf(" got %u oversleep %d\n", (unsigned int)(dt * 1000000), (unsigned int)(dt * 1000000) - microseconds);
540         return (dt < 0 || dt >= 1800) ? 0 : dt;
541 }
542
543 void Sys_Printf(const char *fmt, ...)
544 {
545         va_list argptr;
546         char msg[MAX_INPUTLINE];
547
548         va_start(argptr,fmt);
549         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
550         va_end(argptr);
551
552         Sys_Print(msg);
553 }
554
555 #ifndef WIN32
556 static const char *Sys_FindInPATH(const char *name, char namesep, const char *PATH, char pathsep, char *buf, size_t bufsize)
557 {
558         const char *p = PATH;
559         const char *q;
560         if(p && name)
561         {
562                 while((q = strchr(p, ':')))
563                 {
564                         dpsnprintf(buf, bufsize, "%.*s%c%s", (int)(q-p), p, namesep, name);
565                         if(FS_SysFileExists(buf))
566                                 return buf;
567                         p = q + 1;
568                 }
569                 if(!q) // none found - try the last item
570                 {
571                         dpsnprintf(buf, bufsize, "%s%c%s", p, namesep, name);
572                         if(FS_SysFileExists(buf))
573                                 return buf;
574                 }
575         }
576         return name;
577 }
578 #endif
579
580 static const char *Sys_FindExecutableName(void)
581 {
582 #if defined(WIN32)
583         return sys.argv[0];
584 #else
585         static char exenamebuf[MAX_OSPATH+1];
586         ssize_t n = -1;
587 #if defined(__FreeBSD__)
588         int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
589         size_t exenamebuflen = sizeof(exenamebuf)-1;
590         if (sysctl(mib, 4, exenamebuf, &exenamebuflen, NULL, 0) == 0)
591         {
592                 n = exenamebuflen;
593         }
594 #elif defined(__linux__)
595         n = readlink("/proc/self/exe", exenamebuf, sizeof(exenamebuf)-1);
596 #endif
597         if(n > 0 && (size_t)(n) < sizeof(exenamebuf))
598         {
599                 exenamebuf[n] = 0;
600                 return exenamebuf;
601         }
602         if(strchr(sys.argv[0], '/'))
603                 return sys.argv[0]; // possibly a relative path
604         else
605                 return Sys_FindInPATH(sys.argv[0], '/', getenv("PATH"), ':', exenamebuf, sizeof(exenamebuf));
606 #endif
607 }
608
609 void Sys_ProvideSelfFD(void)
610 {
611         if(sys.selffd != -1)
612                 return;
613         sys.selffd = FS_SysOpenFD(Sys_FindExecutableName(), "rb", false);
614 }
615
616 // for x86 cpus only...  (x64 has SSE2_PRESENT)
617 #if defined(SSE_POSSIBLE) && !defined(SSE2_PRESENT)
618 // code from SDL, shortened as we can expect CPUID to work
619 static int CPUID_Features(void)
620 {
621         int features = 0;
622 # if (defined(__GNUC__) || defined(__clang__) || defined(__TINYC__)) && defined(__i386__)
623         __asm__ (
624 "        movl    %%ebx,%%edi\n"
625 "        xorl    %%eax,%%eax                                           \n"
626 "        incl    %%eax                                                 \n"
627 "        cpuid                       # Get family/model/stepping/features\n"
628 "        movl    %%edx,%0                                              \n"
629 "        movl    %%edi,%%ebx\n"
630         : "=m" (features)
631         :
632         : "%eax", "%ecx", "%edx", "%edi"
633         );
634 # elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
635         __asm {
636         xor     eax, eax
637         inc     eax
638         cpuid                       ; Get family/model/stepping/features
639         mov     features, edx
640         }
641 # else
642 #  error SSE_POSSIBLE set but no CPUID implementation
643 # endif
644         return features;
645 }
646 #endif
647
648 #ifdef SSE_POSSIBLE
649 qbool Sys_HaveSSE(void)
650 {
651         // COMMANDLINEOPTION: SSE: -nosse disables SSE support and detection
652         if(Sys_CheckParm("-nosse"))
653                 return false;
654 #ifdef SSE_PRESENT
655         return true;
656 #else
657         // COMMANDLINEOPTION: SSE: -forcesse enables SSE support and disables detection
658         if(Sys_CheckParm("-forcesse") || Sys_CheckParm("-forcesse2"))
659                 return true;
660         if(CPUID_Features() & (1 << 25))
661                 return true;
662         return false;
663 #endif
664 }
665
666 qbool Sys_HaveSSE2(void)
667 {
668         // COMMANDLINEOPTION: SSE2: -nosse2 disables SSE2 support and detection
669         if(Sys_CheckParm("-nosse") || Sys_CheckParm("-nosse2"))
670                 return false;
671 #ifdef SSE2_PRESENT
672         return true;
673 #else
674         // COMMANDLINEOPTION: SSE2: -forcesse2 enables SSE2 support and disables detection
675         if(Sys_CheckParm("-forcesse2"))
676                 return true;
677         if((CPUID_Features() & (3 << 25)) == (3 << 25)) // SSE is 1<<25, SSE2 is 1<<26
678                 return true;
679         return false;
680 #endif
681 }
682 #endif
683
684 /// called to set process priority for dedicated servers
685 #if defined(__linux__)
686 #include <sys/resource.h>
687 #include <errno.h>
688
689 void Sys_InitProcessNice (void)
690 {
691         struct rlimit lim;
692         sys.nicepossible = false;
693         if(Sys_CheckParm("-nonice"))
694                 return;
695         errno = 0;
696         sys.nicelevel = getpriority(PRIO_PROCESS, 0);
697         if(errno)
698         {
699                 Con_Printf("Kernel does not support reading process priority - cannot use niceness\n");
700                 return;
701         }
702         if(getrlimit(RLIMIT_NICE, &lim))
703         {
704                 Con_Printf("Kernel does not support lowering nice level again - cannot use niceness\n");
705                 return;
706         }
707         if(lim.rlim_cur != RLIM_INFINITY && sys.nicelevel < (int) (20 - lim.rlim_cur))
708         {
709                 Con_Printf("Current nice level is below the soft limit - cannot use niceness\n");
710                 return;
711         }
712         sys.nicepossible = true;
713         sys.isnice = false;
714 }
715 void Sys_MakeProcessNice (void)
716 {
717         if(!sys.nicepossible)
718                 return;
719         if(sys.isnice)
720                 return;
721         Con_DPrintf("Process is becoming 'nice'...\n");
722         if(setpriority(PRIO_PROCESS, 0, 19))
723                 Con_Printf(CON_ERROR "Failed to raise nice level to %d\n", 19);
724         sys.isnice = true;
725 }
726 void Sys_MakeProcessMean (void)
727 {
728         if(!sys.nicepossible)
729                 return;
730         if(!sys.isnice)
731                 return;
732         Con_DPrintf("Process is becoming 'mean'...\n");
733         if(setpriority(PRIO_PROCESS, 0, sys.nicelevel))
734                 Con_Printf(CON_ERROR "Failed to lower nice level to %d\n", sys.nicelevel);
735         sys.isnice = false;
736 }
737 #else
738 void Sys_InitProcessNice (void)
739 {
740 }
741 void Sys_MakeProcessNice (void)
742 {
743 }
744 void Sys_MakeProcessMean (void)
745 {
746 }
747 #endif