sysfs.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*
  2. * Intel MIC Platform Software Stack (MPSS)
  3. *
  4. * Copyright(c) 2013 Intel Corporation.
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License, version 2, as
  8. * published by the Free Software Foundation.
  9. *
  10. * This program is distributed in the hope that it will be useful, but
  11. * WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * General Public License for more details.
  14. *
  15. * The full GNU General Public License is included in this distribution in
  16. * the file called "COPYING".
  17. *
  18. * Intel MIC User Space Tools.
  19. */
  20. #include "mpssd.h"
  21. #define PAGE_SIZE 4096
  22. char *
  23. readsysfs(char *dir, char *entry)
  24. {
  25. char filename[PATH_MAX];
  26. char value[PAGE_SIZE];
  27. char *string = NULL;
  28. int fd;
  29. int len;
  30. if (dir == NULL)
  31. snprintf(filename, PATH_MAX, "%s/%s", MICSYSFSDIR, entry);
  32. else
  33. snprintf(filename, PATH_MAX,
  34. "%s/%s/%s", MICSYSFSDIR, dir, entry);
  35. fd = open(filename, O_RDONLY);
  36. if (fd < 0) {
  37. mpsslog("Failed to open sysfs entry '%s': %s\n",
  38. filename, strerror(errno));
  39. return NULL;
  40. }
  41. len = read(fd, value, sizeof(value));
  42. if (len < 0) {
  43. mpsslog("Failed to read sysfs entry '%s': %s\n",
  44. filename, strerror(errno));
  45. goto readsys_ret;
  46. }
  47. if (len == 0)
  48. goto readsys_ret;
  49. value[len - 1] = '\0';
  50. string = malloc(strlen(value) + 1);
  51. if (string)
  52. strcpy(string, value);
  53. readsys_ret:
  54. close(fd);
  55. return string;
  56. }
  57. int
  58. setsysfs(char *dir, char *entry, char *value)
  59. {
  60. char filename[PATH_MAX];
  61. char *oldvalue;
  62. int fd, ret = 0;
  63. if (dir == NULL)
  64. snprintf(filename, PATH_MAX, "%s/%s", MICSYSFSDIR, entry);
  65. else
  66. snprintf(filename, PATH_MAX, "%s/%s/%s",
  67. MICSYSFSDIR, dir, entry);
  68. oldvalue = readsysfs(dir, entry);
  69. fd = open(filename, O_RDWR);
  70. if (fd < 0) {
  71. ret = errno;
  72. mpsslog("Failed to open sysfs entry '%s': %s\n",
  73. filename, strerror(errno));
  74. goto done;
  75. }
  76. if (!oldvalue || strcmp(value, oldvalue)) {
  77. if (write(fd, value, strlen(value)) < 0) {
  78. ret = errno;
  79. mpsslog("Failed to write new sysfs entry '%s': %s\n",
  80. filename, strerror(errno));
  81. }
  82. }
  83. close(fd);
  84. done:
  85. if (oldvalue)
  86. free(oldvalue);
  87. return ret;
  88. }