aboutsummaryrefslogtreecommitdiff
path: root/src/interface/linux/linux_sysfs.c
blob: 4f0027cd440278c26df8990cbb05af3d1ede590e (plain)
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
/*
 * Copyright (C) 2021 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

FILE_LICENCE ( GPL2_OR_LATER );

#include <string.h>
#include <errno.h>
#include <ipxe/umalloc.h>
#include <ipxe/linux_api.h>
#include <ipxe/linux.h>
#include <ipxe/linux_sysfs.h>

/** @file
 *
 * Linux sysfs files
 *
 */

/** Read blocksize */
#define LINUX_SYSFS_BLKSIZE 4096

/**
 * Read file from sysfs
 *
 * @v filename		Filename
 * @v data		Data to fill in
 * @ret len		Length read, or negative error
 */
int linux_sysfs_read ( const char *filename, userptr_t *data ) {
	userptr_t tmp;
	ssize_t read;
	size_t len;
	int fd;
	int rc;

	/* Open file */
	fd = linux_open ( filename, O_RDONLY );
	if ( fd < 0 ) {
		rc = -ELINUX ( linux_errno );
		DBGC ( filename, "LINUX could not open %s: %s\n",
		       filename, linux_strerror ( linux_errno ) );
		goto err_open;
	}

	/* Read file */
	for ( *data = UNULL, len = 0 ; ; len += read ) {

		/* (Re)allocate space */
		tmp = urealloc ( *data, ( len + LINUX_SYSFS_BLKSIZE ) );
		if ( ! tmp ) {
			rc = -ENOMEM;
			goto err_alloc;
		}
		*data = tmp;

		/* Read from file */
		read = linux_read ( fd, user_to_virt ( *data, len ),
				    LINUX_SYSFS_BLKSIZE );
		if ( read == 0 )
			break;
		if ( read < 0 ) {
			DBGC ( filename, "LINUX could not read %s: %s\n",
			       filename, linux_strerror ( linux_errno ) );
			goto err_read;
		}
	}

	/* Close file */
	linux_close ( fd );

	DBGC ( filename, "LINUX read %s\n", filename );
	return len;

 err_read:
 err_alloc:
	ufree ( *data );
	linux_close ( fd );
 err_open:
	return rc;
}