services/settings/index.html · services/settings/index.rst 공식 원문 ↗

Zephyr 3.7.0 · OS Services · Persistent Configuration

Settings

Device configuration과 runtime state를 key-value로 복원하고 저장합니다.

Official pathservices/settings/index.html
Source fileservices/settings/index.rst
Source versionZephyr 3.7.0
TranslationFull · reviewed

본문 기준: Zephyr 3.7.0 LTS3 · 이후 유지보수 패치는 별도입니다.

Part 1

요약·해설

Settings handler의 h_get·h_set·h_commit·h_export, source/destination backend contract, storage location, 최신 record와 garbage collection, custom backend를 설명합니다.

Load

Sources → h_set

Apply

h_commit

Save

h_export → destination

Part 2

접을 수 있는 영어 원문 전체

영어 원문 전체 펼치기
원문 SHA-256 E163F1D93FD596C0AE7E7A32D6FF7D7390791F25FC682E46466F1DA8960AC992
.. _settings_api:

Settings
########

The settings subsystem gives modules a way to store persistent per-device
configuration and runtime state.  A variety of storage implementations are
provided behind a common API using FCB, NVS, or a file system.  These different
implementations give the application developer flexibility to select an
appropriate storage medium, and even change it later as needs change.  This
subsystem is used by various Zephyr components and can be used simultaneously by
user applications.

Settings items are stored as key-value pair strings.  By convention,
the keys can be organized by the package and subtree defining the key,
for example the key ``id/serial`` would define the ``serial`` configuration
element for the package ``id``.

Convenience routines are provided for converting a key value to
and from a string type.

For an example of the settings subsystem refer to :zephyr:code-sample:`settings` sample.

.. note::

   As of Zephyr release 2.1 the recommended backend for non-filesystem
   storage is :ref:`NVS <nvs_api>`.

Handlers
********

Settings handlers for subtree implement a set of handler functions.
These are registered using a call to ``settings_register()``.

**h_get**
    This gets called when asking for a settings element value by its name using
    ``settings_runtime_get()`` from the runtime backend.

**h_set**
    This gets called when the value is loaded from persisted storage with
    ``settings_load()``, or when using ``settings_runtime_set()`` from the
    runtime backend.

**h_commit**
    This gets called after the settings have been loaded in full.
    Sometimes you don't want an individual setting value to take
    effect right away, for example if there are multiple settings
    which are interdependent.

**h_export**
    This gets called to write all current settings. This happens
    when ``settings_save()`` tries to save the settings or transfer to any
    user-implemented back-end.

Backends
********

Backends are meant to load and save data to/from setting handlers, and
implement a set of handler functions. These are registered using a call to
``settings_src_register()`` for backends that can load data, and/or
``settings_dst_register()`` for backends that can save data. The current
implementation allows for multiple source backends but only a single destination
backend.

**csi_load**
    This gets called when loading values from persistent storage using
    ``settings_load()``.

**csi_save**
    This gets called when saving a single setting to persistent storage using
    ``settings_save_one()``.

**csi_save_start**
    This gets called when starting a save of all current settings using
    ``settings_save()``.

**csi_save_end**
    This gets called after having saved of all current settings using
    ``settings_save()``.

Zephyr Storage Backends
***********************

Zephyr has three storage backends: a Flash Circular Buffer
(:kconfig:option:`CONFIG_SETTINGS_FCB`), a file in the filesystem
(:kconfig:option:`CONFIG_SETTINGS_FILE`), or non-volatile storage
(:kconfig:option:`CONFIG_SETTINGS_NVS`).

You can declare multiple sources for settings; settings from
all of these are restored when ``settings_load()`` is called.

There can be only one target for writing settings; this is where
data is stored when you call ``settings_save()``, or ``settings_save_one()``.

FCB read target is registered using ``settings_fcb_src()``, and write target
using ``settings_fcb_dst()``. As a side-effect,  ``settings_fcb_src()``
initializes the FCB area, so it must be called before calling
``settings_fcb_dst()``. File read target is registered using
``settings_file_src()``, and write target by using ``settings_file_dst()``.
Non-volatile storage read target is registered using
``settings_nvs_src()``, and write target by using
``settings_nvs_dst()``.

Storage Location
****************

The FCB and non-volatile storage (NVS) backends both look for a fixed
partition with label "storage" by default. A different partition can be
selected by setting the ``zephyr,settings-partition`` property of the
chosen node in the devicetree.

The file path used by the file backend to store settings is selected via the
option ``CONFIG_SETTINGS_FILE_PATH``.

Loading data from persisted storage
***********************************

A call to ``settings_load()`` uses an ``h_set`` implementation
to load settings data from storage to volatile memory.
After all data is loaded, the ``h_commit`` handler is issued,
signalling the application that the settings were successfully
retrieved.

Technically FCB and file backends may store some history of the entities.
This means that the newest data entity is stored after any
older existing data entities.
Starting with Zephyr 2.1, the back-end must filter out all old entities and
call the callback with only the newest entity.

Storing data to persistent storage
**********************************

A call to ``settings_save_one()`` uses a backend implementation to store
settings data to the storage medium. A call to ``settings_save()`` uses an
``h_export`` implementation to store different data in one operation using
``settings_save_one()``.
A key need to be covered by a ``h_export`` only if it is supposed to be stored
by ``settings_save()`` call.

For both FCB and file back-end only storage requests with data which
changes most actual key's value are stored, therefore there is no need to check
whether a value changed by the application. Such a storage mechanism implies
that storage can contain multiple value assignments for a key , while only the
last is the current value for the key.

Garbage collection
==================
When storage becomes full (FCB) or consumes too much space (file),
the backend removes non-recent key-value pairs records and unnecessary
key-delete records.

Secure domain settings
**********************
Currently settings doesn't provide scheme of being secure, and non-secure
configuration storage simultaneously for the same instance.
It is recommended that secure domain uses its own settings instance and it might
provide data for non-secure domain using dedicated interface if needed
(case dependent).

Example: Device Configuration
*****************************

This is a simple example, where the settings handler only implements ``h_set``
and ``h_export``. ``h_set`` is called when the value is restored from storage
(or when set initially), and ``h_export`` is used to write the value to
storage thanks to ``storage_func()``. The user can also implement some other
export functionality, for example, writing to the shell console).

.. code-block:: c

    #define DEFAULT_FOO_VAL_VALUE 1

    static int8 foo_val = DEFAULT_FOO_VAL_VALUE;

    static int foo_settings_set(const char *name, size_t len,
                                settings_read_cb read_cb, void *cb_arg)
    {
        const char *next;
        int rc;

        if (settings_name_steq(name, "bar", &next) && !next) {
            if (len != sizeof(foo_val)) {
                return -EINVAL;
            }

            rc = read_cb(cb_arg, &foo_val, sizeof(foo_val));
            if (rc >= 0) {
                /* key-value pair was properly read.
                 * rc contains value length.
                 */
                return 0;
            }
            /* read-out error */
            return rc;
        }

        return -ENOENT;
    }

    static int foo_settings_export(int (*storage_func)(const char *name,
                                                       const void *value,
                                                       size_t val_len))
    {
        return storage_func("foo/bar", &foo_val, sizeof(foo_val));
    }

    struct settings_handler my_conf = {
        .name = "foo",
        .h_set = foo_settings_set,
        .h_export = foo_settings_export
    };

Example: Persist Runtime State
******************************

This is a simple example showing how to persist runtime state. In this example,
only ``h_set`` is defined, which is used when restoring value from
persisted storage.

In this example, the ``main`` function increments ``foo_val``, and then
persists the latest number. When the system restarts, the application calls
``settings_load()`` while initializing, and ``foo_val`` will continue counting
up from where it was before restart.

.. code-block:: c

    #include <zephyr/kernel.h>
    #include <zephyr/sys/reboot.h>
    #include <zephyr/settings/settings.h>
    #include <zephyr/sys/printk.h>
    #include <inttypes.h>

    #define DEFAULT_FOO_VAL_VALUE 0

    static uint8_t foo_val = DEFAULT_FOO_VAL_VALUE;

    static int foo_settings_set(const char *name, size_t len,
                                settings_read_cb read_cb, void *cb_arg)
    {
        const char *next;
        int rc;

        if (settings_name_steq(name, "bar", &next) && !next) {
            if (len != sizeof(foo_val)) {
                return -EINVAL;
            }

            rc = read_cb(cb_arg, &foo_val, sizeof(foo_val));
            if (rc >= 0) {
                return 0;
            }

            return rc;
        }


        return -ENOENT;
    }

    struct settings_handler my_conf = {
        .name = "foo",
        .h_set = foo_settings_set
    };

    int main(void)
    {
        settings_subsys_init();
        settings_register(&my_conf);
        settings_load();

        foo_val++;
        settings_save_one("foo/bar", &foo_val, sizeof(foo_val));

        printk("foo: %d\n", foo_val);

        k_msleep(1000);
        sys_reboot(SYS_REBOOT_COLD);
    }

Example: Custom Backend Implementation
**************************************

This is a simple example showing how to register a simple custom backend
handler (:kconfig:option:`CONFIG_SETTINGS_CUSTOM`).

.. code-block:: c

    static int settings_custom_load(struct settings_store *cs,
                                    const struct settings_load_arg *arg)
    {
        //...
    }

    static int settings_custom_save(struct settings_store *cs, const char *name,
                                    const char *value, size_t val_len)
    {
        //...
    }

    /* custom backend interface */
    static struct settings_store_itf settings_custom_itf = {
        .csi_load = settings_custom_load,
        .csi_save = settings_custom_save,
    };

    /* custom backend node */
    static struct settings_store settings_custom_store = {
        .cs_itf = &settings_custom_itf
    };

    int settings_backend_init(void)
    {
        /* register custom backend */
        settings_dst_register(&settings_custom_store);
        settings_src_register(&settings_custom_store);
        return 0;
    }

API Reference
*************

The Settings subsystem APIs are provided by ``settings.h``:

API for general settings usage
==============================
.. doxygengroup:: settings

API for key-name processing
===========================
.. doxygengroup:: settings_name_proc

API for runtime settings manipulation
=====================================
.. doxygengroup:: settings_rt

API of backend interface
========================
..  doxygengroup:: settings_backend

Part 3

한국어 전문 번역

Settings subsystem은 module이 device별 persistent configuration과 runtime state를 저장하게 합니다. 공통 API 뒤에 FCB, NVS 또는 file-system backend를 둘 수 있어 storage medium을 선택하고 나중에 요구가 바뀌면 교체할 수 있습니다. Zephyr component와 user application이 동시에 사용할 수도 있습니다.

Item은 string key와 value의 pair로 저장합니다. 관례상 package와 subtree를 /로 구분하므로 id/serial은 id package의 serial element입니다. String type으로 변환하는 convenience routine도 제공합니다.

공식 settings code sample에서 전체 사용 예를 볼 수 있습니다. Filesystem이 아닌 storage에는 Zephyr 2.1부터 NVS backend가 권장됩니다.

Persistent settings load·save contract
Source backendFCB · File · NVS, 여러 개 등록 가능
settings_load()
h_set최신 key value를 volatile state에 복원
모든 key 완료
h_commit상호 의존 setting을 한 번에 적용
h_export → settings_save_one()
Destination backend하나만 등록, 변경된 최신 value 저장

Handlers

Settings subtree handler는 callback 집합을 구현하고 settings_register()로 등록합니다.

h_get
settings_runtime_get()이 name으로 현재 value를 요청할 때 호출됩니다.
h_set
settings_load()가 persistent value를 복원하거나 settings_runtime_set()이 runtime value를 설정할 때 호출됩니다.
h_commit
전체 settings load 뒤 호출됩니다. 서로 의존하는 여러 value를 모두 받은 다음 한 번에 적용해야 할 때 사용합니다.
h_export
settings_save() 또는 user backend transfer가 현재 value 전체를 쓰려 할 때 호출됩니다.

Backends

Backend는 storage와 handler 사이에서 data를 load·save합니다. Load backend는 settings_src_register(), save backend는 settings_dst_register()로 등록합니다. Source는 여러 개 둘 수 있지만 destination은 하나만 둘 수 있습니다.

csi_load
settings_load() 때 persistent storage에서 value를 읽습니다.
csi_save
settings_save_one()으로 key 하나를 저장합니다.
csi_save_start
settings_save() 전체 저장 시작 전에 호출됩니다.
csi_save_end
전체 현재 setting 저장이 끝난 뒤 호출됩니다.

Zephyr Storage Backends

공식 backend는 FCB(CONFIG_SETTINGS_FCB), filesystem file(CONFIG_SETTINGS_FILE), NVS(CONFIG_SETTINGS_NVS) 세 가지입니다.

여러 source를 선언하면 settings_load()가 모두 복원합니다. Write target은 하나뿐이며 settings_save()와 settings_save_one()의 data가 그곳에 저장됩니다.

FCB source는 settings_fcb_src(), destination은 settings_fcb_dst()로 등록합니다. Source 등록이 FCB area를 초기화하므로 반드시 destination보다 먼저 호출해야 합니다. File은 settings_file_src()/settings_file_dst(), NVS는 settings_nvs_src()/settings_nvs_dst()를 사용합니다.

Storage Location

FCB와 NVS는 기본적으로 label이 storage인 fixed partition을 찾습니다. 다른 partition을 쓰려면 Devicetree chosen node의 zephyr,settings-partition property를 지정합니다. File backend path는 CONFIG_SETTINGS_FILE_PATH로 선택합니다.

Loading data from persisted storage

settings_load()는 각 최신 stored value를 h_set에 전달해 volatile memory를 복원합니다. 모든 data를 읽고 나면 h_commit을 호출해 retrieval 완료와 적용 시점을 알립니다.

FCB와 file backend에는 같은 key의 history가 남을 수 있어 오래된 entity 뒤에 더 새 entity가 기록됩니다. Zephyr 2.1부터 backend는 old entity를 걸러내고 callback에는 최신 entity 하나만 전달해야 합니다.

Storing data to persistent storage

settings_save_one()은 backend를 통해 key 하나를 저장합니다. settings_save()은 handler의 h_export를 호출하고 export callback이 여러 key를 settings_save_one()으로 내보냅니다. 전체 save 대상 key만 h_export에서 열거하면 됩니다.

FCB와 file backend는 현재 최신 value와 달라지는 request만 저장하므로 application이 변경 여부를 미리 비교할 필요가 없습니다. Storage에는 같은 key의 assignment가 여러 개 있을 수 있지만 마지막 record만 현재 value입니다.

Garbage collection

FCB가 가득 차거나 file이 너무 커지면 backend는 최신이 아닌 key-value record와 더 이상 필요 없는 key-delete record를 제거합니다.

Secure domain settings

현재 Settings는 같은 instance에서 secure configuration과 non-secure configuration을 동시에 분리하는 scheme을 제공하지 않습니다. Secure domain은 자체 settings instance를 사용하고, 필요할 때 dedicated interface로 non-secure domain에 data를 제공하는 구성이 권장됩니다.

Example: Device Configuration

다음 예는 h_set과 h_export만 구현합니다. h_set은 storage 복원 또는 initial runtime set 때 foo/bar를 읽고 size를 검증합니다. h_export은 storage_func()으로 현재 value를 저장합니다. 같은 export hook을 shell 출력 같은 다른 용도로 구현할 수도 있습니다.

#define DEFAULT_FOO_VAL_VALUE 1

static int8 foo_val = DEFAULT_FOO_VAL_VALUE;

static int foo_settings_set(const char *name, size_t len,
                            settings_read_cb read_cb, void *cb_arg)
{
    const char *next;
    int rc;

    if (settings_name_steq(name, "bar", &next) && !next) {
        if (len != sizeof(foo_val)) {
            return -EINVAL;
        }

        rc = read_cb(cb_arg, &foo_val, sizeof(foo_val));
        if (rc >= 0) {
            /* key-value pair was properly read.
             * rc contains value length.
             */
            return 0;
        }
        /* read-out error */
        return rc;
    }

    return -ENOENT;
}

static int foo_settings_export(int (*storage_func)(const char *name,
                                                   const void *value,
                                                   size_t val_len))
{
    return storage_func("foo/bar", &foo_val, sizeof(foo_val));
}

struct settings_handler my_conf = {
    .name = "foo",
    .h_set = foo_settings_set,
    .h_export = foo_settings_export
};

Example: Persist Runtime State

이 예는 runtime counter를 재부팅 뒤에도 이어갑니다. Initialization에서 subsystem과 handler를 등록하고 settings_load()로 이전 foo_val을 복원합니다. 값을 증가시켜 settings_save_one()으로 저장한 뒤 cold reboot하므로 다음 boot에서 직전 숫자부터 계속됩니다.

#include <zephyr/kernel.h>
#include <zephyr/sys/reboot.h>
#include <zephyr/settings/settings.h>
#include <zephyr/sys/printk.h>
#include <inttypes.h>

#define DEFAULT_FOO_VAL_VALUE 0

static uint8_t foo_val = DEFAULT_FOO_VAL_VALUE;

static int foo_settings_set(const char *name, size_t len,
                            settings_read_cb read_cb, void *cb_arg)
{
    const char *next;
    int rc;

    if (settings_name_steq(name, "bar", &next) && !next) {
        if (len != sizeof(foo_val)) {
            return -EINVAL;
        }

        rc = read_cb(cb_arg, &foo_val, sizeof(foo_val));
        if (rc >= 0) {
            return 0;
        }

        return rc;
    }


    return -ENOENT;
}

struct settings_handler my_conf = {
    .name = "foo",
    .h_set = foo_settings_set
};

int main(void)
{
    settings_subsys_init();
    settings_register(&my_conf);
    settings_load();

    foo_val++;
    settings_save_one("foo/bar", &foo_val, sizeof(foo_val));

    printk("foo: %d\n", foo_val);

    k_msleep(1000);
    sys_reboot(SYS_REBOOT_COLD);
}

Example: Custom Backend Implementation

CONFIG_SETTINGS_CUSTOM을 사용하면 자체 backend를 등록할 수 있습니다. settings_store_itf에 load·save callback을 넣고 settings_store가 이를 가리키게 한 뒤 source와 destination으로 각각 등록합니다.

static int settings_custom_load(struct settings_store *cs,
                                const struct settings_load_arg *arg)
{
    //...
}

static int settings_custom_save(struct settings_store *cs, const char *name,
                                const char *value, size_t val_len)
{
    //...
}

/* custom backend interface */
static struct settings_store_itf settings_custom_itf = {
    .csi_load = settings_custom_load,
    .csi_save = settings_custom_save,
};

/* custom backend node */
static struct settings_store settings_custom_store = {
    .cs_itf = &settings_custom_itf
};

int settings_backend_init(void)
{
    /* register custom backend */
    settings_dst_register(&settings_custom_store);
    settings_src_register(&settings_custom_store);
    return 0;
}

API Reference

Settings API는 settings.h에서 제공됩니다.

API for general settings usage

Subsystem 초기화, handler 등록, load·save·delete·commit과 handler structure입니다.

API for key-name processing

Slash-separated key element를 비교하고 다음 component를 찾는 helper입니다.

API for runtime settings manipulation

Persistent storage를 거치지 않는 get·set·commit API입니다.

API of backend interface

Custom source·destination backend가 구현하고 등록하는 store contract입니다.

SETTINGS_MAX_DIR_DEPTH
Key를 separator로 나눴을 때 지원하는 최대 subtree depth입니다.
SETTINGS_MAX_NAME_LEN
Settings key name의 최대 길이입니다.
SETTINGS_MAX_VAL_LEN
Convenience buffer가 다루는 setting value의 최대 길이입니다.
SETTINGS_NAME_SEPARATOR
Key subtree element를 나누는 / separator입니다.
SETTINGS_NAME_END
Key parsing에서 name 끝을 나타내는 값입니다.
SETTINGS_EXTRA_LEN
Backend record가 name·value 외에 확보하는 추가 길이입니다.
SETTINGS_STATIC_HANDLER_DEFINE
Link-time에 settings subtree handler를 정적으로 정의합니다.
settings_read_cb
h_set가 backend value를 caller buffer로 읽을 때 사용하는 callback type입니다.
settings_load_direct_cb
Handler에 저장하지 않고 subtree load value를 직접 받는 callback type입니다.
settings_subsys_init
Settings core와 선택된 backend를 초기화합니다.
settings_register
RAM에 있는 subtree handler를 runtime에 등록합니다.
settings_load
등록된 모든 persistence source에서 최신 serialized item을 load합니다.
settings_load_subtree
지정 subtree에 속한 item만 handler로 load합니다.
settings_load_subtree_direct
지정 subtree를 handler 대신 caller callback으로 직접 load합니다.
settings_save
모든 handler의 export를 호출해 현재 persistent item을 저장합니다.
settings_save_subtree
지정 subtree handler의 현재 item만 저장합니다.
settings_save_one
Key 하나의 value가 바뀐 경우 destination backend에 저장합니다.
settings_delete
Persistent storage에서 key 하나를 삭제 record로 표시합니다.
settings_commit
모든 registered handler의 commit callback을 호출합니다.
settings_commit_subtree
지정 subtree에 속한 handler만 commit합니다.
settings_handler
Runtime-registered subtree의 name과 get·set·commit·export callback을 보관합니다.
settings_handler.name
Handler가 소유하는 root subtree name입니다.
settings_handler.h_get
Runtime get 요청에 key value를 제공하는 callback입니다.
settings_handler.h_set
Persistent load 또는 runtime set value를 module state에 반영하는 callback입니다.
settings_handler.h_commit
전체 load 뒤 interdependent setting을 실제 동작에 적용하는 callback입니다.
settings_handler.h_export
현재 setting을 storage function으로 열거하는 callback입니다.
settings_handler.node
Settings core의 handler linked list에 연결하는 internal node입니다.
settings_handler_static
정적 handler에 쓰이는 subtree name과 callback 집합입니다.
settings_handler_static.name
Static handler의 root subtree name입니다.
settings_handler_static.h_get
Static handler의 runtime get callback입니다.
settings_handler_static.h_set
Static handler의 load·runtime set callback입니다.
settings_handler_static.h_commit
Static handler의 post-load commit callback입니다.
settings_handler_static.h_export
Static handler의 current-value export callback입니다.
settings_name_steq
Name 시작 element가 주어진 key와 같은지 비교하고 다음 element pointer를 돌려줍니다.
settings_name_next
첫 separator 전까지의 element 길이와 다음 위치를 계산합니다.
settings_runtime_set
Persistent storage를 거치지 않고 특정 key를 module handler에 설정합니다.
settings_runtime_get
Persistent storage를 거치지 않고 handler의 현재 key value를 읽습니다.
settings_runtime_commit
Runtime에서 module handler의 pending setting을 적용합니다.
settings_src_register
Load 가능한 backend store를 source로 등록합니다.
settings_dst_register
Save할 backend store 하나를 destination으로 등록합니다.
settings_parse_and_lookup
Key를 element 배열로 parse하고 대응하는 module handler를 찾습니다.
settings_call_set_handler
Parsed key와 value reader로 해당 handler의 set callback을 호출합니다.
settings_store
Backend interface와 source list 연결 정보를 가진 store node입니다.
settings_store.cs_next
다음 registered source store를 가리키는 internal link입니다.
settings_store.cs_itf
이 store가 구현한 backend operation table입니다.
settings_load_arg
Backend load에 전달할 subtree, direct callback과 parameter입니다.
settings_load_arg.subtree
Load 범위를 제한하는 subtree name입니다.
settings_load_arg.cb
Direct load 때 key·value를 받을 callback입니다.
settings_load_arg.param
Direct-load callback에 전달할 caller parameter입니다.
settings_store_itf
Backend의 load와 save lifecycle callback table입니다.
settings_store_itf.csi_load
선택한 subtree의 최신 value를 storage에서 load합니다.
settings_store_itf.csi_save_start
전체 export operation 직전에 호출됩니다.
settings_store_itf.csi_save
Key-value pair 하나를 storage에 저장합니다.
settings_store_itf.csi_save_end
전체 export operation이 끝난 뒤 호출됩니다.

Source

출처

영어 원문에는 문단, 문서 지시문, 표, 코드, 코드 심벌, 경로를 그대로 보존했습니다.