kv_fct.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /*
  2. * Copyright (C) 2019-2020 Alibaba Group Holding Limited
  3. */
  4. #include <ulog/ulog.h>
  5. #include <aos/kv.h>
  6. #include <aos/nvram.h>
  7. #include "kv_linux.h"
  8. #define TAG "NV"
  9. static kv_t g_kv;
  10. static aos_kv_mutex_t g_kv_lock;
  11. static int __kv_init(const char *pathname)
  12. {
  13. g_kv_lock.key_file = pathname;
  14. int ret = kv_init(&g_kv, pathname);
  15. /* shmkey ftok need real path, must call after kv_init */
  16. aos_kv_mutex_new(&g_kv_lock);
  17. return ret;
  18. }
  19. static int __kv_setdata(char *key, char *buf, int bufsize)
  20. {
  21. if (g_kv.handle < 0) {
  22. return -1;
  23. }
  24. aos_kv_mutex_lock(&g_kv_lock, -1);
  25. int ret = kv_set(&g_kv, key, buf, bufsize) >= 0 ? 0 : -1;
  26. aos_kv_mutex_unlock(&g_kv_lock);
  27. return ret;
  28. }
  29. static int __kv_getdata(char *key, char *buf, int bufsize)
  30. {
  31. if (g_kv.handle < 0) {
  32. return -1;
  33. }
  34. if (key == NULL || buf == NULL || bufsize <= 0)
  35. return -1;
  36. aos_kv_mutex_lock(&g_kv_lock, -1);
  37. int ret = kv_get(&g_kv, key, buf, bufsize);
  38. aos_kv_mutex_unlock(&g_kv_lock);
  39. return ret;
  40. }
  41. static int __kv_del(char *key)
  42. {
  43. if (g_kv.handle < 0) {
  44. return -1;
  45. }
  46. aos_kv_mutex_lock(&g_kv_lock, -1);
  47. int ret = kv_rm(&g_kv, key);
  48. aos_kv_mutex_unlock(&g_kv_lock);
  49. return ret;
  50. }
  51. static int __kv_reset(void)
  52. {
  53. if (g_kv.handle < 0) {
  54. return -1;
  55. }
  56. aos_kv_mutex_lock(&g_kv_lock, -1);
  57. int ret = kv_reset(&g_kv);
  58. aos_kv_mutex_unlock(&g_kv_lock);
  59. return ret;
  60. }
  61. /*************************
  62. * Set Get API
  63. *************************/
  64. int nvram_init(const char *pathname)
  65. {
  66. return __kv_init(pathname);
  67. }
  68. int nvram_get_val(const char *key, char *value, int len)
  69. {
  70. int ret;
  71. ret = __kv_getdata((char *)key, (char *)value, len - 1);
  72. if(ret > 0) {
  73. value[ret < len ? ret : len - 1] = '\0';
  74. }
  75. return ret;
  76. }
  77. int nvram_set_val(const char *key, char *value)
  78. {
  79. return __kv_setdata((char *)key, (void *)value, strlen(value));
  80. }
  81. int nvram_del(const char *key)
  82. {
  83. return __kv_del((char *)key);
  84. }
  85. int nvram_reset(void)
  86. {
  87. return __kv_reset();
  88. }