File: intel_gpu_frequency.c

package info (click to toggle)
intel-gpu-tools 2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 64,504 kB
  • sloc: xml: 781,458; ansic: 378,272; python: 8,407; yacc: 2,781; perl: 1,196; sh: 1,177; lex: 487; asm: 227; lisp: 35; makefile: 30
file content (509 lines) | stat: -rw-r--r-- 11,713 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/*
 * Copyright © 2015,2018,2025 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include <assert.h>
#include <dirent.h>
#include <fcntl.h>
#include <getopt.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>

#include "drmtest.h"
#include "igt_device.h"
#include "intel_chipset.h"

#define VERSION "1.0"

static int device, devid;

enum {
	CUR=0,
	MIN,
	EFF,
	MAX,
	RP0,
	RPn
};

struct freq_info {
	const char *name;
	const char *mode;
	FILE *filp;
	char *path;
	bool write;
};

static struct freq_info info[] = {
	{ "cur", "r"  },
	{ "min", "rb+" },
	{ "RP1", "r" },
	{ "max", "rb+" },
	{ "RP0", "r" },
	{ "RPn", "r" }
};

static char *
get_sysfs_path(const char *which)
{
	static const char fmt[] = "/sys/class/drm/card%1d/gt_%3s_freq_mhz";
	char *path;
	int ret;

#define STATIC_STRLEN(string) (sizeof(string) / sizeof(string [0]))
	ret = asprintf(&path, fmt, device, which);
	assert(ret == (STATIC_STRLEN(fmt) - 3));
#undef STATIC_STRLEN

	return path;
}

/* Returns:
 * 1 if Intel card was bound by i915 driver
 * 0 otherwise
 * -errno on error
 */
static int
is_intel_card(int card)
{
	static const char fmt[] = "/sys/class/drm/card%d/device/driver/module/drivers";
	char path[PATH_MAX];
	struct dirent *entry;
	int dirfd;
	DIR *dirp;
	int found = 0;

	if (card < 0)
		return -1;

	sprintf(path, fmt, card);

	dirfd = open(path, O_RDONLY | O_DIRECTORY);
	if (dirfd < 0)
		return -errno;

	dirp = fdopendir(dirfd);
	if (!dirp) {
		int err = errno;

		close(dirfd);
		return -err;
	}

	while ((entry = readdir(dirp))) {
		if (strcmp(entry->d_name, ".") == 0 ||
		    strcmp(entry->d_name, "..") == 0)
			continue;

		if (strncmp(entry->d_name, "pci:", 4))
			continue;

		if (!strcmp(entry->d_name, "pci:i915")) {
			found = 1;
			break;
		}
	}

	closedir(dirp);

	return found;
}

static void __attribute__((noreturn))
exit_error(const char *msg, int err)
{
	if (msg)
		fprintf(stderr, "%s\n", msg);

	if (err > 0)
		fprintf(stderr, "Error: %d %s\n", err, strerror(err));

	exit(EXIT_FAILURE);
}

static int
get_intel_card(void)
{
	struct dirent *entry;
	int intel_card = -1;
	int dirfd, err;
	DIR *dirp;

	dirfd = open("/dev/dri/", O_RDONLY | O_DIRECTORY);
	if (dirfd < 0)
		exit_error("Cannot open /dev/dri/", errno);

	dirp = fdopendir(dirfd);
	if (!dirp) {
		err = errno;
		close(dirfd);
		exit_error("Cannot open directory /dev/dri/", err);
	}

	while ((entry = readdir(dirp))) {
		int num;

		if (strcmp(entry->d_name, ".") == 0 ||
		    strcmp(entry->d_name, "..") == 0)
			continue;

		if (entry->d_type == DT_DIR)
			continue;

		if (strncmp(entry->d_name, "card", 4))
			continue;

		if (sscanf(entry->d_name, "card%d", &num) != 1)
			exit_error("Cannot parse card ID as integer", 0);

		if (is_intel_card(num) > 0) {
			intel_card = num;
			break;
		}
	}

	closedir(dirp);

	return intel_card;
}

static void
initialize_read_info(struct freq_info *freq_info)
{
	if (freq_info->filp)
		return;

	freq_info->path = get_sysfs_path(freq_info->name);
	assert(freq_info->path);
	freq_info->filp = fopen(freq_info->path, "r");
	assert(freq_info->filp);
}

static void
initialize_write_info(struct freq_info *freq_info)
{
	if (freq_info->write)
		return;

	if (freq_info->filp)
		fclose(freq_info->filp);
	else
		freq_info->path = get_sysfs_path(freq_info->name);

	assert(freq_info->path);
	freq_info->filp = fopen(freq_info->path, freq_info->mode);
	if (!(freq_info->filp)) {
		fprintf(stderr, "Cannot open file %s for write mode %s\nerror %d %s\n",
			freq_info->path, freq_info->mode, errno, strerror(errno));
		exit(EXIT_FAILURE);
	}

	freq_info->write = true;
}

static void wait_freq_settle(void)
{
	struct timespec ts;

	/* FIXME: Lazy sleep without check. */
	ts.tv_sec = 0;
	ts.tv_nsec = 20000;
	clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, NULL);
}

static void set_frequency(struct freq_info *freq_info, int val)
{
	initialize_write_info(freq_info);
	rewind(freq_info->filp);
	assert(fprintf(freq_info->filp, "%d", val) > 0);

	wait_freq_settle();
}

static int get_frequency(struct freq_info *freq_info)
{
	int val;

	initialize_read_info(freq_info);
	rewind(freq_info->filp);
	assert(fscanf(freq_info->filp, "%d", &val)==1);

	return val;
}

static const char *
get_shortname(const char *prog)
{
	const char *slash = strrchr(prog, '/');

	return slash ? slash + 1 : prog;
}

static void __attribute__((noreturn))
usage(const char *prog, int err)
{
	const char *shortname = get_shortname(prog);

	printf("%s A program to manipulate Intel GPU frequencies.\n\n", shortname);
	printf("Usage: %s [-e] [--min | --max] [--get] [--set frequency_mhz]\n\n", shortname);
	printf("Options: \n");
	printf("  -e		Lock frequency to the most efficient frequency\n");
	printf("  -g, --get     Get all the frequency settings\n");
	printf("  -s, --set     Lock frequency to an absolute value (MHz)\n");
	printf("  -c, --custom  Set a min, or max frequency \"min=X | max=Y\"\n");
	printf("  -m  --max     Lock frequency to max frequency\n");
	printf("  -i  --min     Lock frequency to min (never a good idea, DEBUG ONLY)\n");
	printf("  -d  --defaults  Return the system to hardware defaults\n");
	printf("  -h  --help    Returns this\n");
	printf("  -v  --version Version\n");
	printf("\n");
	printf("Examples:\n");
	printf("   intel_gpu_frequency --get\t\tGet the current and minimum frequency\n");
	printf("   intel_gpu_frequency --set 400\tLock frequency to 400Mhz\n");
	printf("   intel_gpu_frequency --custom max=750\tSet the max frequency to 750MHz\n");
	printf("\n");
	printf("Report bugs to https://gitlab.freedesktop.org/drm/igt-gpu-tools/-/issues\n");
	exit(err);
}

static void
version(const char *prog)
{
	printf("%s: %s\n", get_shortname(prog), VERSION);
	printf("Copyright © 2015,2018,2025 Intel Corporation\n");
}

static void
parse_version_or_help(int argc, char *argv[])
{
	char *s;
	int c;

	if (argc == 1) /* No args */
		return;

	s = argv[1];
	c = *s++;
	if (c == '-')
		c = *s++;
	if (c == '-')
		c = *s++;

	if (c == 'v') {
		version(argv[0]);
		exit(EXIT_SUCCESS);
	}

	if (c == 'h')
		usage(argv[0], EXIT_SUCCESS);
}

/* Returns read or write operation */
static bool
parse(int argc, char *argv[], bool *act_upon, size_t act_upon_n, int *new_freq)
{
	int c, tmp;
	bool write = false;

	/* No args means -g" */
	if (argc == 1) {
		for (c = 0; c < act_upon_n; c++)
			act_upon[c] = true;
		goto done;
	}
	while (1) {
		int option_index = 0;
		static struct option long_options[] = {
			{ "get", no_argument, NULL, 'g' },
			{ "set", required_argument, NULL, 's' },
			{ "custom", required_argument, NULL, 'c'},
			{ "min", no_argument, NULL, 'i' },
			{ "max", no_argument, NULL, 'm' },
			{ "defaults", no_argument, NULL, 'd' },
			{ "help", no_argument, NULL, 'h' },
			{ "version", no_argument, NULL, 'v' },
			{ NULL, 0, NULL, 0}
		};

		c = getopt_long(argc, argv, "egs:c:midh", long_options, &option_index);
		if (c == -1)
			break;

		switch (c) {
		case 'g':
			if (write == true)
				fprintf(stderr, "Read and write operations not support simultaneously.\n");
			{
				int i;
				for (i = 0; i < act_upon_n; i++)
					act_upon[i] = true;
			}
			break;
		case 's':
			if (!optarg)
				usage(argv[0], EXIT_FAILURE);

			if (write == true) {
				fprintf(stderr, "Only one write may be specified at a time\n");
				exit(EXIT_FAILURE);
			}

			write = true;
			act_upon[MIN] = true;
			act_upon[MAX] = true;
			sscanf(optarg, "%d", &new_freq[MAX]);
			new_freq[MIN] = new_freq[MAX];
			break;
		case 'c':
			if (!optarg)
				usage(argv[0], EXIT_FAILURE);

			if (write == true) {
				fprintf(stderr, "Only one write may be specified at a time\n");
				exit(EXIT_FAILURE);
			}

			write = true;

			if (!strncmp("min=", optarg, 4)) {
				act_upon[MIN] = true;
				sscanf(optarg+4, "%d", &new_freq[MIN]);
			} else if (!strncmp("max=", optarg, 4)) {
				act_upon[MAX] = true;
				sscanf(optarg+4, "%d", &new_freq[MAX]);
			} else {
				fprintf(stderr, "Selected unmodifiable frequency\n");
				exit(EXIT_FAILURE);
			}
			break;
		case 'e': /* efficient */
			if (IS_VALLEYVIEW(devid) || IS_CHERRYVIEW(devid)) {
				/* the LP parts have special efficient frequencies */
				fprintf(stderr,
					"FIXME: Warning efficient frequency information is incorrect.\n");
				exit(EXIT_FAILURE);
			}
			tmp = get_frequency(&info[EFF]);
			new_freq[MIN] = tmp;
			new_freq[MAX] = tmp;
			act_upon[MIN] = true;
			act_upon[MAX] = true;
			write = true;
			break;
		case 'i': /* mIn */
			tmp = get_frequency(&info[RPn]);
			new_freq[MIN] = tmp;
			new_freq[MAX] = tmp;
			act_upon[MIN] = true;
			act_upon[MAX] = true;
			write = true;
			break;
		case 'm': /* max */
			tmp = get_frequency(&info[RP0]);
			new_freq[MIN] = tmp;
			new_freq[MAX] = tmp;
			act_upon[MIN] = true;
			act_upon[MAX] = true;
			write = true;
			break;
		case 'd': /* defaults */
			new_freq[MIN] = get_frequency(&info[RPn]);
			new_freq[MAX] = get_frequency(&info[RP0]);
			act_upon[MIN] = true;
			act_upon[MAX] = true;
			write = true;
			break;
		default:
			fprintf(stderr, "Error: unknown option\n");
			usage(argv[0], EXIT_FAILURE);
		}
	}

done:
	return write;
}

int main(int argc, char *argv[])
{

	bool write, fail, targets[MAX+1] = {false};
	int i, fd, try = 1, set_freq[MAX+1] = {0};

	parse_version_or_help(argc, argv);

	device = get_intel_card();
	if (device < 0)
		exit_error("No Intel card found in /dev/dri\n", 0);

	fd = __drm_open_driver(DRIVER_INTEL);
	if (fd >= 0) {
		devid = intel_get_drm_devid(fd);
		close(fd);
	}

	write = parse(argc, argv, targets, ARRAY_SIZE(targets), set_freq);
	fail = write;

	/* If we've previously locked the frequency, we need to make sure to set things
	 * in the correct order, or else the operation will fail (ie. min = max = 200,
	 * and we set min to 300, we fail because it would try to set min >
	 * max). This can be accomplished be going either forward or reverse
	 * through the loop. MIN is always before MAX.
	 *
	 * XXX: Since only min and max are at play, the super lazy way is to do this
	 * 3 times and if we still fail after 3, it's for real.
	 */
again:
	if (try > 2) {
		fprintf(stderr, "Did not achieve desired freq.\n");
		exit(EXIT_FAILURE);
	}
	for (i = 0; i < ARRAY_SIZE(targets); i++) {
		if (targets[i] == false)
			continue;

		if (write) {
			set_frequency(&info[i], set_freq[i]);
			if (get_frequency(&info[i]) != set_freq[i])
				fail = true;
			else
				fail = false;
		} else {
			printf("%s: %d MHz\n", info[i].name, get_frequency(&info[i]));
		}
	}

	if (fail) {
		try++;
		goto again;
	}

	for (i = 0; i < ARRAY_SIZE(targets); i++) {
		if (info[i].filp) {
			fclose(info[i].filp);
			free(info[i].path);
		}
	}

	return EXIT_SUCCESS;
}