Documentation/driver-api/media/dtv-frontend.rst GitHub 원문 ↗

Linux 6.18.37 · Driver API

Digital TV Frontend kABI

DVB demodulator ops, 튜닝 알고리즘, frontend 생명주기, DVBv5 통계와 counter 수집 규칙을 설명하는 전문 번역입니다.

Source pathDocumentation/driver-api/media/dtv-frontend.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약과 해설

dtv-frontend.rst:1-445

이 문서는 demodulator 드라이버가 `dvb_frontend_ops`로 기능과 callback을 선언하는 방법부터 frontend 등록·해제 순서, software·hardware·custom 튜닝 알고리즘, DVBv5 통계의 scale과 가용 조건, hardware counter를 정확히 누적하는 두 가지 수집 전략까지 다룹니다.

핵심은 lock 상태에 맞는 통계만 읽고, 같은 hardware sample을 반복해서 누적하지 않는 것입니다. Ready bit가 있으면 새 sample 여부를 검사하고, 없다면 jiffies 기반 최소 간격을 적용하며, 두 방식 모두 core가 주기적으로 호출하는 `.read_status`에 연결합니다.

문서 구성
원문 줄내용
1-14Frontend kABI 목적과 header
15-97Demodulator용 `dvb_frontend_ops` 예제
98-144주파수 단위·callback·튜닝 알고리즘
145-163등록·전원 관리·제거 생명주기
164-206DVBv5 통계 초기화와 scale
207-276통계 그룹과 lock 조건
277-325단계별 `.read_status` 예제
326-380Ready bit 기반 counter 수집
381-441시간 제한과 추정 기반 counter 수집
442-445Frontend kernel-doc

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 Digital TV Frontend kABI
4 ------------------------
5
6 Digital TV Frontend
7 ~~~~~~~~~~~~~~~~~~~
8
9 The Digital TV Frontend kABI defines a driver-internal interface for
10 registering low-level, hardware specific driver to a hardware independent
11 frontend layer. It is only of interest for Digital TV device driver writers.
12 The header file for this API is named ``dvb_frontend.h`` and located in
13 ``include/media/``.
14
15 Demodulator driver
16 ^^^^^^^^^^^^^^^^^^
17
18 The demodulator driver is responsible for talking with the decoding part of the
19 hardware. Such driver should implement :c:type:`dvb_frontend_ops`, which
20 tells what type of digital TV standards are supported, and points to a
21 series of functions that allow the DVB core to command the hardware via
22 the code under ``include/media/dvb_frontend.c``.
23
24 A typical example of such struct in a driver ``foo`` is::
25
26 static struct dvb_frontend_ops foo_ops = {
27 .delsys = { SYS_DVBT, SYS_DVBT2, SYS_DVBC_ANNEX_A },
28 .info = {
29 .name = "foo DVB-T/T2/C driver",
30 .caps = FE_CAN_FEC_1_2 |
31 FE_CAN_FEC_2_3 |
32 FE_CAN_FEC_3_4 |
33 FE_CAN_FEC_5_6 |
34 FE_CAN_FEC_7_8 |
35 FE_CAN_FEC_AUTO |
36 FE_CAN_QPSK |
37 FE_CAN_QAM_16 |
38 FE_CAN_QAM_32 |
39 FE_CAN_QAM_64 |
40 FE_CAN_QAM_128 |
41 FE_CAN_QAM_256 |
42 FE_CAN_QAM_AUTO |
43 FE_CAN_TRANSMISSION_MODE_AUTO |
44 FE_CAN_GUARD_INTERVAL_AUTO |
45 FE_CAN_HIERARCHY_AUTO |
46 FE_CAN_MUTE_TS |
47 FE_CAN_2G_MODULATION,
48 .frequency_min = 42000000, /* Hz */
49 .frequency_max = 1002000000, /* Hz */
50 .symbol_rate_min = 870000,
51 .symbol_rate_max = 11700000
52 },
53 .init = foo_init,
54 .sleep = foo_sleep,
55 .release = foo_release,
56 .set_frontend = foo_set_frontend,
57 .get_frontend = foo_get_frontend,
58 .read_status = foo_get_status_and_stats,
59 .tune = foo_tune,
60 .i2c_gate_ctrl = foo_i2c_gate_ctrl,
61 .get_frontend_algo = foo_get_algo,
62 };
63
64 A typical example of such struct in a driver ``bar`` meant to be used on
65 Satellite TV reception is::
66
67 static const struct dvb_frontend_ops bar_ops = {
68 .delsys = { SYS_DVBS, SYS_DVBS2 },
69 .info = {
70 .name = "Bar DVB-S/S2 demodulator",
71 .frequency_min = 500000, /* KHz */
72 .frequency_max = 2500000, /* KHz */
73 .frequency_stepsize = 0,
74 .symbol_rate_min = 1000000,
75 .symbol_rate_max = 45000000,
76 .symbol_rate_tolerance = 500,
77 .caps = FE_CAN_INVERSION_AUTO |
78 FE_CAN_FEC_AUTO |
79 FE_CAN_QPSK,
80 },
81 .init = bar_init,
82 .sleep = bar_sleep,
83 .release = bar_release,
84 .set_frontend = bar_set_frontend,
85 .get_frontend = bar_get_frontend,
86 .read_status = bar_get_status_and_stats,
87 .i2c_gate_ctrl = bar_i2c_gate_ctrl,
88 .get_frontend_algo = bar_get_algo,
89 .tune = bar_tune,
90
91 /* Satellite-specific */
92 .diseqc_send_master_cmd = bar_send_diseqc_msg,
93 .diseqc_send_burst = bar_send_burst,
94 .set_tone = bar_set_tone,
95 .set_voltage = bar_set_voltage,
96 };
97
98 .. note::
99
100 #) For satellite digital TV standards (DVB-S, DVB-S2, ISDB-S), the
101 frequencies are specified in kHz, while, for terrestrial and cable
102 standards, they're specified in Hz. Due to that, if the same frontend
103 supports both types, you'll need to have two separate
104 :c:type:`dvb_frontend_ops` structures, one for each standard.
105 #) The ``.i2c_gate_ctrl`` field is present only when the hardware has
106 allows controlling an I2C gate (either directly of via some GPIO pin),
107 in order to remove the tuner from the I2C bus after a channel is
108 tuned.
109 #) All new drivers should implement the
110 :ref:`DVBv5 statistics <dvbv5_stats>` via ``.read_status``.
111 Yet, there are a number of callbacks meant to get statistics for
112 signal strength, S/N and UCB. Those are there to provide backward
113 compatibility with legacy applications that don't support the DVBv5
114 API. Implementing those callbacks are optional. Those callbacks may be
115 removed in the future, after we have all existing drivers supporting
116 DVBv5 stats.
117 #) Other callbacks are required for satellite TV standards, in order to
118 control LNBf and DiSEqC: ``.diseqc_send_master_cmd``,
119 ``.diseqc_send_burst``, ``.set_tone``, ``.set_voltage``.
120
121 .. |delta| unicode:: U+00394
122
123 The ``include/media/dvb_frontend.c`` has a kernel thread which is
124 responsible for tuning the device. It supports multiple algorithms to
125 detect a channel, as defined at enum :c:func:`dvbfe_algo`.
126
127 The algorithm to be used is obtained via ``.get_frontend_algo``. If the driver
128 doesn't fill its field at struct dvb_frontend_ops, it will default to
129 ``DVBFE_ALGO_SW``, meaning that the dvb-core will do a zigzag when tuning,
130 e. g. it will try first to use the specified center frequency ``f``,
131 then, it will do ``f`` + |delta|, ``f`` - |delta|, ``f`` + 2 x |delta|,
132 ``f`` - 2 x |delta| and so on.
133
134 If the hardware has internally a some sort of zigzag algorithm, you should
135 define a ``.get_frontend_algo`` function that would return ``DVBFE_ALGO_HW``.
136
137 .. note::
138
139 The core frontend support also supports
140 a third type (``DVBFE_ALGO_CUSTOM``), in order to allow the driver to
141 define its own hardware-assisted algorithm. Very few hardware need to
142 use it nowadays. Using ``DVBFE_ALGO_CUSTOM`` require to provide other
143 function callbacks at struct dvb_frontend_ops.
144
145 Attaching frontend driver to the bridge driver
146 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
147
148 Before using the Digital TV frontend core, the bridge driver should attach
149 the frontend demod, tuner and SEC devices and call
150 :c:func:`dvb_register_frontend()`,
151 in order to register the new frontend at the subsystem. At device
152 detach/removal, the bridge driver should call
153 :c:func:`dvb_unregister_frontend()` to
154 remove the frontend from the core and then :c:func:`dvb_frontend_detach()`
155 to free the memory allocated by the frontend drivers.
156
157 The drivers should also call :c:func:`dvb_frontend_suspend()` as part of
158 their handler for the :c:type:`device_driver`.\ ``suspend()``, and
159 :c:func:`dvb_frontend_resume()` as
160 part of their handler for :c:type:`device_driver`.\ ``resume()``.
161
162 A few other optional functions are provided to handle some special cases.
163
164 .. _dvbv5_stats:
165
166 Digital TV Frontend statistics
167 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
168
169 Introduction
170 ^^^^^^^^^^^^
171
172 Digital TV frontends provide a range of
173 :ref:`statistics <frontend-stat-properties>` meant to help tuning the device
174 and measuring the quality of service.
175
176 For each statistics measurement, the driver should set the type of scale used,
177 or ``FE_SCALE_NOT_AVAILABLE`` if the statistics is not available on a given
178 time. Drivers should also provide the number of statistics for each type.
179 that's usually 1 for most video standards [#f2]_.
180
181 Drivers should initialize each statistic counters with length and
182 scale at its init code. For example, if the frontend provides signal
183 strength, it should have, on its init code::
184
185 struct dtv_frontend_properties *c = &state->fe.dtv_property_cache;
186
187 c->strength.len = 1;
188 c->strength.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
189
190 And, when the statistics got updated, set the scale::
191
192 c->strength.stat[0].scale = FE_SCALE_DECIBEL;
193 c->strength.stat[0].uvalue = strength;
194
195 .. [#f2] For ISDB-T, it may provide both a global statistics and a per-layer
196 set of statistics. On such cases, len should be equal to 4. The first
197 value corresponds to the global stat; the other ones to each layer, e. g.:
198
199 - c->cnr.stat[0] for global S/N carrier ratio,
200 - c->cnr.stat[1] for Layer A S/N carrier ratio,
201 - c->cnr.stat[2] for layer B S/N carrier ratio,
202 - c->cnr.stat[3] for layer C S/N carrier ratio.
203
204 .. note:: Please prefer to use ``FE_SCALE_DECIBEL`` instead of
205 ``FE_SCALE_RELATIVE`` for signal strength and CNR measurements.
206
207 Groups of statistics
208 ^^^^^^^^^^^^^^^^^^^^
209
210 There are several groups of statistics currently supported:
211
212 Signal strength (:ref:`DTV-STAT-SIGNAL-STRENGTH`)
213 - Measures the signal strength level at the analog part of the tuner or
214 demod.
215
216 - Typically obtained from the gain applied to the tuner and/or frontend
217 in order to detect the carrier. When no carrier is detected, the gain is
218 at the maximum value (so, strength is on its minimal).
219
220 - As the gain is visible through the set of registers that adjust the gain,
221 typically, this statistics is always available [#f3]_.
222
223 - Drivers should try to make it available all the times, as these statistics
224 can be used when adjusting an antenna position and to check for troubles
225 at the cabling.
226
227 .. [#f3] On a few devices, the gain keeps floating if there is no carrier.
228 On such devices, strength report should check first if carrier is
229 detected at the tuner (``FE_HAS_CARRIER``, see :c:type:`fe_status`),
230 and otherwise return the lowest possible value.
231
232 Carrier Signal to Noise ratio (:ref:`DTV-STAT-CNR`)
233 - Signal to Noise ratio for the main carrier.
234
235 - Signal to Noise measurement depends on the device. On some hardware, it is
236 available when the main carrier is detected. On those hardware, CNR
237 measurement usually comes from the tuner (e. g. after ``FE_HAS_CARRIER``,
238 see :c:type:`fe_status`).
239
240 On other devices, it requires inner FEC decoding,
241 as the frontend measures it indirectly from other parameters (e. g. after
242 ``FE_HAS_VITERBI``, see :c:type:`fe_status`).
243
244 Having it available after inner FEC is more common.
245
246 Bit counts post-FEC (:ref:`DTV-STAT-POST-ERROR-BIT-COUNT` and :ref:`DTV-STAT-POST-TOTAL-BIT-COUNT`)
247 - Those counters measure the number of bits and bit errors after
248 the forward error correction (FEC) on the inner coding block
249 (after Viterbi, LDPC or other inner code).
250
251 - Due to its nature, those statistics depend on full coding lock
252 (e. g. after ``FE_HAS_SYNC`` or after ``FE_HAS_LOCK``,
253 see :c:type:`fe_status`).
254
255 Bit counts pre-FEC (:ref:`DTV-STAT-PRE-ERROR-BIT-COUNT` and :ref:`DTV-STAT-PRE-TOTAL-BIT-COUNT`)
256 - Those counters measure the number of bits and bit errors before
257 the forward error correction (FEC) on the inner coding block
258 (before Viterbi, LDPC or other inner code).
259
260 - Not all frontends provide this kind of statistics.
261
262 - Due to its nature, those statistics depend on inner coding lock (e. g.
263 after ``FE_HAS_VITERBI``, see :c:type:`fe_status`).
264
265 Block counts (:ref:`DTV-STAT-ERROR-BLOCK-COUNT` and :ref:`DTV-STAT-TOTAL-BLOCK-COUNT`)
266 - Those counters measure the number of blocks and block errors after
267 the forward error correction (FEC) on the inner coding block
268 (before Viterbi, LDPC or other inner code).
269
270 - Due to its nature, those statistics depend on full coding lock
271 (e. g. after ``FE_HAS_SYNC`` or after
272 ``FE_HAS_LOCK``, see :c:type:`fe_status`).
273
274 .. note:: All counters should be monotonically increased as they're
275 collected from the hardware.
276
277 A typical example of the logic that handle status and statistics is::
278
279 static int foo_get_status_and_stats(struct dvb_frontend *fe)
280 {
281 struct foo_state *state = fe->demodulator_priv;
282 struct dtv_frontend_properties *c = &fe->dtv_property_cache;
283
284 int rc;
285 enum fe_status *status;
286
287 /* Both status and strength are always available */
288 rc = foo_read_status(fe, &status);
289 if (rc < 0)
290 return rc;
291
292 rc = foo_read_strength(fe);
293 if (rc < 0)
294 return rc;
295
296 /* Check if CNR is available */
297 if (!(fe->status & FE_HAS_CARRIER))
298 return 0;
299
300 rc = foo_read_cnr(fe);
301 if (rc < 0)
302 return rc;
303
304 /* Check if pre-BER stats are available */
305 if (!(fe->status & FE_HAS_VITERBI))
306 return 0;
307
308 rc = foo_get_pre_ber(fe);
309 if (rc < 0)
310 return rc;
311
312 /* Check if post-BER stats are available */
313 if (!(fe->status & FE_HAS_SYNC))
314 return 0;
315
316 rc = foo_get_post_ber(fe);
317 if (rc < 0)
318 return rc;
319 }
320
321 static const struct dvb_frontend_ops ops = {
322 /* ... */
323 .read_status = foo_get_status_and_stats,
324 };
325
326 Statistics collection
327 ^^^^^^^^^^^^^^^^^^^^^
328
329 On almost all frontend hardware, the bit and byte counts are stored by
330 the hardware after a certain amount of time or after the total bit/block
331 counter reaches a certain value (usually programmable), for example, on
332 every 1000 ms or after receiving 1,000,000 bits.
333
334 So, if you read the registers too soon, you'll end by reading the same
335 value as in the previous reading, causing the monotonic value to be
336 incremented too often.
337
338 Drivers should take the responsibility to avoid too often reads. That
339 can be done using two approaches:
340
341 if the driver have a bit that indicates when a collected data is ready
342 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
343
344 Driver should check such bit before making the statistics available.
345
346 An example of such behavior can be found at this code snippet (adapted
347 from mb86a20s driver's logic)::
348
349 static int foo_get_pre_ber(struct dvb_frontend *fe)
350 {
351 struct foo_state *state = fe->demodulator_priv;
352 struct dtv_frontend_properties *c = &fe->dtv_property_cache;
353 int rc, bit_error;
354
355 /* Check if the BER measures are already available */
356 rc = foo_read_u8(state, 0x54);
357 if (rc < 0)
358 return rc;
359
360 if (!rc)
361 return 0;
362
363 /* Read Bit Error Count */
364 bit_error = foo_read_u32(state, 0x55);
365 if (bit_error < 0)
366 return bit_error;
367
368 /* Read Total Bit Count */
369 rc = foo_read_u32(state, 0x51);
370 if (rc < 0)
371 return rc;
372
373 c->pre_bit_error.stat[0].scale = FE_SCALE_COUNTER;
374 c->pre_bit_error.stat[0].uvalue += bit_error;
375 c->pre_bit_count.stat[0].scale = FE_SCALE_COUNTER;
376 c->pre_bit_count.stat[0].uvalue += rc;
377
378 return 0;
379 }
380
381 If the driver doesn't provide a statistics available check bit
382 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
383
384 A few devices, however, may not provide a way to check if the stats are
385 available (or the way to check it is unknown). They may not even provide
386 a way to directly read the total number of bits or blocks.
387
388 On those devices, the driver need to ensure that it won't be reading from
389 the register too often and/or estimate the total number of bits/blocks.
390
391 On such drivers, a typical routine to get statistics would be like
392 (adapted from dib8000 driver's logic)::
393
394 struct foo_state {
395 /* ... */
396
397 unsigned long per_jiffies_stats;
398 }
399
400 static int foo_get_pre_ber(struct dvb_frontend *fe)
401 {
402 struct foo_state *state = fe->demodulator_priv;
403 struct dtv_frontend_properties *c = &fe->dtv_property_cache;
404 int rc, bit_error;
405 u64 bits;
406
407 /* Check if time for stats was elapsed */
408 if (!time_after(jiffies, state->per_jiffies_stats))
409 return 0;
410
411 /* Next stat should be collected in 1000 ms */
412 state->per_jiffies_stats = jiffies + msecs_to_jiffies(1000);
413
414 /* Read Bit Error Count */
415 bit_error = foo_read_u32(state, 0x55);
416 if (bit_error < 0)
417 return bit_error;
418
419 /*
420 * On this particular frontend, there's no register that
421 * would provide the number of bits per 1000ms sample. So,
422 * some function would calculate it based on DTV properties
423 */
424 bits = get_number_of_bits_per_1000ms(fe);
425
426 c->pre_bit_error.stat[0].scale = FE_SCALE_COUNTER;
427 c->pre_bit_error.stat[0].uvalue += bit_error;
428 c->pre_bit_count.stat[0].scale = FE_SCALE_COUNTER;
429 c->pre_bit_count.stat[0].uvalue += bits;
430
431 return 0;
432 }
433
434 Please notice that, on both cases, we're getting the statistics using the
435 :c:type:`dvb_frontend_ops` ``.read_status`` callback. The rationale is that
436 the frontend core will automatically call this function periodically
437 (usually, 3 times per second, when the frontend is locked).
438
439 That warrants that we won't miss to collect a counter and increment the
440 monotonic stats at the right time.
441
442 Digital TV Frontend functions and types
443 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
444
445 .. kernel-doc:: include/media/dvb_frontend.h
446

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

Digital TV Frontend kABI

1-14

이 `GPL-2.0` 문서는 Digital TV Frontend kernel ABI를 설명합니다. 이 kABI는 하드웨어별 저수준 드라이버를 하드웨어 독립적인 frontend 계층에 등록하기 위한 드라이버 내부 인터페이스이며, Digital TV 장치 드라이버 작성자를 위한 것입니다.

이 API의 헤더 파일은 `dvb_frontend.h`이고 `include/media/`에 있습니다.

Frontend kABI 범위
항목내용
사용자Digital TV 장치 드라이버 작성자
연결저수준 하드웨어 드라이버 → 하드웨어 독립 frontend 계층
헤더`include/media/dvb_frontend.h`

.. SPDX-License-Identifier: GPL-2.0

Digital TV Frontend kABI
------------------------

Digital TV Frontend
~~~~~~~~~~~~~~~~~~~

The Digital TV Frontend kABI defines a driver-internal interface for
registering low-level, hardware specific driver to a hardware independent
frontend layer. It is only of interest for Digital TV device driver writers.
The header file for this API is named ``dvb_frontend.h`` and located in
``include/media/``.

Demodulator 드라이버와 dvb_frontend_ops

15-97

Demodulator 드라이버는 하드웨어의 디코딩 부분과 통신합니다. 이 드라이버는 지원하는 Digital TV 표준과 DVB core가 `include/media/dvb_frontend.c`의 코드를 통해 하드웨어를 제어할 때 호출할 함수들을 지정하는 `dvb_frontend_ops`를 구현해야 합니다.

예제 `foo_ops`는 지상파·케이블 수신용 드라이버입니다. `.delsys`에 `SYS_DVBT`, `SYS_DVBT2`, `SYS_DVBC_ANNEX_A`를 선언하고, `.info`에 FEC·QPSK·QAM·자동 전송 모드·guard interval·hierarchy 등의 capability와 Hz 단위 주파수 범위 및 symbol rate 범위를 기록합니다. 이어서 초기화, 절전, 해제, frontend 설정·조회, 상태와 통계 읽기, 튜닝, I2C gate 제어, 알고리즘 선택 callback을 연결합니다.

예제 `bar_ops`는 위성 수신용 드라이버입니다. `SYS_DVBS`와 `SYS_DVBS2`, kHz 단위 주파수 범위, symbol rate 범위와 허용 오차, 지원 capability 및 공통 callback을 선언합니다. 또한 위성 전용으로 DiSEqC master 명령·burst 송신, tone 설정, voltage 설정 callback을 제공합니다.

두 dvb_frontend_ops 예제
구분`foo_ops``bar_ops`
수신 방식DVB-T/T2/CDVB-S/S2
주파수 단위HzkHz
공통 동작init·sleep·release·set/get frontend·read_status·tune·I2C gateinit·sleep·release·set/get frontend·read_status·tune·I2C gate
전용 동작지상파·케이블 capabilityDiSEqC·tone·voltage

Demodulator driver
^^^^^^^^^^^^^^^^^^

The demodulator driver is responsible for talking with the decoding part of the
hardware. Such driver should implement :c:type:`dvb_frontend_ops`, which
tells what type of digital TV standards are supported, and points to a
series of functions that allow the DVB core to command the hardware via
the code under ``include/media/dvb_frontend.c``.

A typical example of such struct in a driver ``foo`` is::

        static struct dvb_frontend_ops foo_ops = {
                .delsys = { SYS_DVBT, SYS_DVBT2, SYS_DVBC_ANNEX_A },
                .info = {
                        .name        = "foo DVB-T/T2/C driver",
                        .caps = FE_CAN_FEC_1_2 |
                                FE_CAN_FEC_2_3 |
                                FE_CAN_FEC_3_4 |
                                FE_CAN_FEC_5_6 |
                                FE_CAN_FEC_7_8 |
                                FE_CAN_FEC_AUTO |
                                FE_CAN_QPSK |
                                FE_CAN_QAM_16 |
                                FE_CAN_QAM_32 |
                                FE_CAN_QAM_64 |
                                FE_CAN_QAM_128 |
                                FE_CAN_QAM_256 |
                                FE_CAN_QAM_AUTO |
                                FE_CAN_TRANSMISSION_MODE_AUTO |
                                FE_CAN_GUARD_INTERVAL_AUTO |
                                FE_CAN_HIERARCHY_AUTO |
                                FE_CAN_MUTE_TS |
                                FE_CAN_2G_MODULATION,
                        .frequency_min = 42000000, /* Hz */
                        .frequency_max = 1002000000, /* Hz */
                        .symbol_rate_min = 870000,
                        .symbol_rate_max = 11700000
                },
                .init = foo_init,
                .sleep = foo_sleep,
                .release = foo_release,
                .set_frontend = foo_set_frontend,
                .get_frontend = foo_get_frontend,
                .read_status = foo_get_status_and_stats,
                .tune = foo_tune,
                .i2c_gate_ctrl = foo_i2c_gate_ctrl,
                .get_frontend_algo = foo_get_algo,
        };

A typical example of such struct in a driver ``bar`` meant to be used on
Satellite TV reception is::

        static const struct dvb_frontend_ops bar_ops = {
                .delsys = { SYS_DVBS, SYS_DVBS2 },
                .info = {
                        .name                = "Bar DVB-S/S2 demodulator",
                        .frequency_min        = 500000, /* KHz */
                        .frequency_max        = 2500000, /* KHz */
                        .frequency_stepsize        = 0,
                        .symbol_rate_min = 1000000,
                        .symbol_rate_max = 45000000,
                        .symbol_rate_tolerance = 500,
                        .caps = FE_CAN_INVERSION_AUTO |
                                FE_CAN_FEC_AUTO |
                                FE_CAN_QPSK,
                },
                .init = bar_init,
                .sleep = bar_sleep,
                .release = bar_release,
                .set_frontend = bar_set_frontend,
                .get_frontend = bar_get_frontend,
                .read_status = bar_get_status_and_stats,
                .i2c_gate_ctrl = bar_i2c_gate_ctrl,
                .get_frontend_algo = bar_get_algo,
                .tune = bar_tune,

                /* Satellite-specific */
                .diseqc_send_master_cmd = bar_send_diseqc_msg,
                .diseqc_send_burst = bar_send_burst,
                .set_tone = bar_set_tone,
                .set_voltage = bar_set_voltage,
        };

단위, 통계 callback, 튜닝 알고리즘

98-144

위성 Digital TV 표준인 DVB-S, DVB-S2, ISDB-S는 주파수를 kHz로 지정하지만 지상파와 케이블 표준은 Hz로 지정합니다. 따라서 하나의 frontend가 두 유형을 모두 지원한다면 표준 유형마다 별도의 `dvb_frontend_ops` 구조체가 필요합니다.

`.i2c_gate_ctrl`은 하드웨어가 직접 또는 GPIO pin을 통해 I2C gate를 제어할 수 있을 때만 둡니다. 채널 튜닝을 마친 뒤 tuner를 I2C bus에서 분리하는 데 사용합니다.

새 드라이버는 모두 `.read_status`를 통해 DVBv5 통계를 구현해야 합니다. 신호 세기, S/N, UCB를 얻는 구형 callback은 DVBv5 API를 지원하지 않는 기존 애플리케이션과의 호환성을 위한 선택 항목입니다. 기존 드라이버가 모두 DVBv5 통계를 지원하게 되면 이 callback들은 제거될 수 있습니다.

위성 표준에서 LNBf와 DiSEqC를 제어하려면 `.diseqc_send_master_cmd`, `.diseqc_send_burst`, `.set_tone`, `.set_voltage` callback도 필요합니다.

`include/media/dvb_frontend.c`에는 장치를 튜닝하는 kernel thread가 있으며 `dvbfe_algo` enum에 정의된 여러 채널 탐색 알고리즘을 지원합니다. 사용할 알고리즘은 `.get_frontend_algo`에서 얻습니다.

드라이버가 `dvb_frontend_ops`의 해당 필드를 채우지 않으면 기본값은 `DVBFE_ALGO_SW`입니다. 이때 DVB core는 지정한 중심 주파수 `f`부터 시작하여 `f + Δ`, `f - Δ`, `f + 2 × Δ`, `f - 2 × Δ` 순서로 범위를 넓히는 zigzag 튜닝을 수행합니다.

하드웨어 내부에 자체 zigzag 알고리즘이 있으면 `.get_frontend_algo`가 `DVBFE_ALGO_HW`를 반환하도록 합니다. Core는 드라이버 고유의 하드웨어 보조 알고리즘을 위한 `DVBFE_ALGO_CUSTOM`도 지원하지만 현재 이를 요구하는 하드웨어는 매우 적으며, 사용하려면 `dvb_frontend_ops`에 추가 callback을 제공해야 합니다.

Frontend 튜닝 알고리즘 선택
`.get_frontend_algo` 없음`DVBFE_ALGO_SW` 기본값DVB core zigzag: `f`, `f+Δ`, `f-Δ`, ...
하드웨어 zigzag 지원`DVBFE_ALGO_HW`하드웨어가 탐색
드라이버 고유 보조 알고리즘`DVBFE_ALGO_CUSTOM`추가 ops callback 필요

get_frontend_algo의 구현 여부와 반환값에 따라 탐색 주체가 달라집니다.

.. note::

   #) For satellite digital TV standards (DVB-S, DVB-S2, ISDB-S), the
      frequencies are specified in kHz, while, for terrestrial and cable
      standards, they're specified in Hz. Due to that, if the same frontend
      supports both types, you'll need to have two separate
      :c:type:`dvb_frontend_ops` structures, one for each standard.
   #) The ``.i2c_gate_ctrl`` field is present only when the hardware has
      allows controlling an I2C gate (either directly of via some GPIO pin),
      in order to remove the tuner from the I2C bus after a channel is
      tuned.
   #) All new drivers should implement the
      :ref:`DVBv5 statistics <dvbv5_stats>` via ``.read_status``.
      Yet, there are a number of callbacks meant to get statistics for
      signal strength, S/N and UCB. Those are there to provide backward
      compatibility with legacy applications that don't support the DVBv5
      API. Implementing those callbacks are optional. Those callbacks may be
      removed in the future, after we have all existing drivers supporting
      DVBv5 stats.
   #) Other callbacks are required for satellite TV standards, in order to
      control LNBf and DiSEqC: ``.diseqc_send_master_cmd``,
      ``.diseqc_send_burst``, ``.set_tone``, ``.set_voltage``.

.. |delta|   unicode:: U+00394

The ``include/media/dvb_frontend.c`` has a kernel thread which is
responsible for tuning the device. It supports multiple algorithms to
detect a channel, as defined at enum :c:func:`dvbfe_algo`.

The algorithm to be used is obtained via ``.get_frontend_algo``. If the driver
doesn't fill its field at struct dvb_frontend_ops, it will default to
``DVBFE_ALGO_SW``, meaning that the dvb-core will do a zigzag when tuning,
e. g. it will try first to use the specified center frequency ``f``,
then, it will do ``f`` + |delta|, ``f`` - |delta|, ``f`` + 2 x |delta|,
``f`` - 2 x |delta| and so on.

If the hardware has internally a some sort of zigzag algorithm, you should
define a ``.get_frontend_algo`` function that would return ``DVBFE_ALGO_HW``.

.. note::

   The core frontend support also supports
   a third type (``DVBFE_ALGO_CUSTOM``), in order to allow the driver to
   define its own hardware-assisted algorithm. Very few hardware need to
   use it nowadays. Using ``DVBFE_ALGO_CUSTOM`` require to provide other
   function callbacks at struct dvb_frontend_ops.

Bridge 드라이버 연결과 생명주기

145-163

Digital TV frontend core를 사용하기 전에 bridge 드라이버는 frontend demodulator, tuner, SEC 장치를 attach한 뒤 `dvb_register_frontend()`를 호출하여 새 frontend를 subsystem에 등록해야 합니다.

장치를 detach하거나 제거할 때는 `dvb_unregister_frontend()`로 core에서 frontend를 제거한 다음 `dvb_frontend_detach()`로 frontend 드라이버가 할당한 메모리를 해제해야 합니다.

드라이버는 `device_driver.suspend()` 처리 과정에서 `dvb_frontend_suspend()`를 호출하고, `device_driver.resume()` 처리 과정에서 `dvb_frontend_resume()`을 호출해야 합니다. 일부 특수 사례를 처리하는 선택 함수도 제공됩니다.

Frontend 등록·전원 관리·제거 순서
Demod·tuner·SEC attach`dvb_register_frontend()`Frontend 사용
`device_driver.suspend()``dvb_frontend_suspend()`
`device_driver.resume()``dvb_frontend_resume()`
장치 제거`dvb_unregister_frontend()``dvb_frontend_detach()`

등록 전 attach와 제거 후 메모리 해제 순서를 보존해야 합니다.

Attaching frontend driver to the bridge driver
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Before using the Digital TV frontend core, the bridge driver should attach
the frontend demod, tuner and SEC devices and call
:c:func:`dvb_register_frontend()`,
in order to register the new frontend at the subsystem. At device
detach/removal, the bridge driver should call
:c:func:`dvb_unregister_frontend()` to
remove the frontend from the core and then :c:func:`dvb_frontend_detach()`
to free the memory allocated by the frontend drivers.

The drivers should also call :c:func:`dvb_frontend_suspend()` as part of
their handler for the :c:type:`device_driver`.\ ``suspend()``, and
:c:func:`dvb_frontend_resume()` as
part of their handler for :c:type:`device_driver`.\ ``resume()``.

A few other optional functions are provided to handle some special cases.

Frontend 통계 초기화와 scale

164-206

Digital TV frontend는 장치 튜닝을 돕고 서비스 품질을 측정하기 위한 여러 통계를 제공합니다. 각 측정값마다 드라이버는 사용한 scale을 지정해야 하며, 해당 시점에 값을 제공할 수 없으면 `FE_SCALE_NOT_AVAILABLE`을 설정해야 합니다. 또한 통계 종류마다 값의 개수인 `len`을 제공해야 하며 대부분의 영상 표준에서는 보통 1입니다.

드라이버는 초기화 코드에서 각 통계 counter의 길이와 scale을 설정해야 합니다. 예제는 `dtv_property_cache`의 `strength.len`을 1로 두고 첫 항목의 scale을 `FE_SCALE_NOT_AVAILABLE`로 초기화합니다. 통계가 갱신되면 scale을 `FE_SCALE_DECIBEL`로 바꾸고 측정값 `strength`를 `uvalue`에 저장합니다.

ISDB-T는 전체 통계와 layer별 통계를 함께 제공할 수 있습니다. 이 경우 `len`은 4이며 `stat[0]`은 전체 S/N carrier ratio, `stat[1]`·`stat[2]`·`stat[3]`은 각각 Layer A·B·C의 S/N carrier ratio입니다.

신호 세기와 CNR 측정에는 `FE_SCALE_RELATIVE`보다 `FE_SCALE_DECIBEL`을 우선 사용해야 합니다.

통계 배열과 scale 초기화
상황`len`초기 scale갱신 scale
일반 표준대개 1`FE_SCALE_NOT_AVAILABLE`측정 단위에 맞는 scale
ISDB-T 전체 + A/B/C4`FE_SCALE_NOT_AVAILABLE`각 항목별 scale
신호 세기·CNR장치별미가용 시 `FE_SCALE_NOT_AVAILABLE``FE_SCALE_DECIBEL` 권장

.. _dvbv5_stats:

Digital TV Frontend statistics
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Introduction
^^^^^^^^^^^^

Digital TV frontends provide a range of
:ref:`statistics <frontend-stat-properties>` meant to help tuning the device
and measuring the quality of service.

For each statistics measurement, the driver should set the type of scale used,
or ``FE_SCALE_NOT_AVAILABLE`` if the statistics is not available on a given
time. Drivers should also provide the number of statistics for each type.
that's usually 1 for most video standards [#f2]_.

Drivers should initialize each statistic counters with length and
scale at its init code. For example, if the frontend provides signal
strength, it should have, on its init code::

        struct dtv_frontend_properties *c = &state->fe.dtv_property_cache;

        c->strength.len = 1;
        c->strength.stat[0].scale = FE_SCALE_NOT_AVAILABLE;

And, when the statistics got updated, set the scale::

        c->strength.stat[0].scale = FE_SCALE_DECIBEL;
        c->strength.stat[0].uvalue = strength;

.. [#f2] For ISDB-T, it may provide both a global statistics and a per-layer
   set of statistics. On such cases, len should be equal to 4. The first
   value corresponds to the global stat; the other ones to each layer, e. g.:

   - c->cnr.stat[0] for global S/N carrier ratio,
   - c->cnr.stat[1] for Layer A S/N carrier ratio,
   - c->cnr.stat[2] for layer B S/N carrier ratio,
   - c->cnr.stat[3] for layer C S/N carrier ratio.

.. note:: Please prefer to use ``FE_SCALE_DECIBEL`` instead of
   ``FE_SCALE_RELATIVE`` for signal strength and CNR measurements.

지원하는 통계 그룹과 가용 조건

207-276

Signal strength는 tuner 또는 demodulator의 analog 부분에서 신호 세기 수준을 측정합니다. 보통 carrier를 검출하기 위해 tuner나 frontend에 적용한 gain에서 값을 얻습니다. Carrier가 없으면 gain이 최대가 되므로 strength는 최소가 됩니다.

Gain 조정 register를 읽을 수 있으므로 대개 signal strength는 항상 제공할 수 있습니다. 안테나 위치 조정과 케이블 문제 확인에 사용할 수 있도록 드라이버는 가능한 한 항상 값을 제공해야 합니다. 다만 carrier가 없을 때 gain이 계속 흔들리는 장치는 먼저 tuner의 `FE_HAS_CARRIER`를 검사하고, 검출되지 않았다면 가능한 최솟값을 반환해야 합니다.

Carrier Signal to Noise ratio, 즉 CNR은 주 carrier의 S/N을 측정합니다. 일부 하드웨어에서는 `FE_HAS_CARRIER` 뒤에 tuner에서 값을 얻을 수 있지만, 다른 하드웨어에서는 frontend가 다른 매개변수로 간접 측정하므로 `FE_HAS_VITERBI`로 표시되는 inner FEC decoding이 필요합니다. Inner FEC 뒤에 CNR을 제공하는 경우가 더 일반적입니다.

Post-FEC bit count는 Viterbi, LDPC 또는 다른 inner code의 forward error correction 뒤에 측정한 전체 bit 수와 bit error 수입니다. 특성상 `FE_HAS_SYNC` 또는 `FE_HAS_LOCK`과 같은 전체 coding lock이 필요합니다.

Pre-FEC bit count는 inner coding block의 forward error correction 전에 측정한 전체 bit 수와 bit error 수입니다. 모든 frontend가 이 통계를 제공하지는 않으며 `FE_HAS_VITERBI`와 같은 inner coding lock에 의존합니다.

Block count는 inner coding block의 forward error correction 뒤에서 전체 block 수와 block error 수를 측정합니다. 원문 괄호는 이 지점을 `before Viterbi, LDPC or other inner code`라고 명시합니다. 이 통계도 `FE_HAS_SYNC` 또는 `FE_HAS_LOCK`과 같은 전체 coding lock에 의존합니다.

하드웨어에서 값을 수집할 때 모든 counter는 단조 증가해야 합니다.

Frontend 통계 가용 조건
통계측정 위치대표 가용 조건
Signal strengthTuner/demod analog gain가능하면 항상; 불안정한 장치는 `FE_HAS_CARRIER` 검사
CNR주 carrier S/N`FE_HAS_CARRIER` 또는 더 흔하게 `FE_HAS_VITERBI`
Pre-FEC bit/errorInner FEC 이전`FE_HAS_VITERBI`
Post-FEC bit/errorInner FEC 이후`FE_HAS_SYNC` 또는 `FE_HAS_LOCK`
Block/errorFEC 관련 block counter`FE_HAS_SYNC` 또는 `FE_HAS_LOCK`

Groups of statistics
^^^^^^^^^^^^^^^^^^^^

There are several groups of statistics currently supported:

Signal strength (:ref:`DTV-STAT-SIGNAL-STRENGTH`)
  - Measures the signal strength level at the analog part of the tuner or
    demod.

  - Typically obtained from the gain applied to the tuner and/or frontend
    in order to detect the carrier. When no carrier is detected, the gain is
    at the maximum value (so, strength is on its minimal).

  - As the gain is visible through the set of registers that adjust the gain,
    typically, this statistics is always available [#f3]_.

  - Drivers should try to make it available all the times, as these statistics
    can be used when adjusting an antenna position and to check for troubles
    at the cabling.

  .. [#f3] On a few devices, the gain keeps floating if there is no carrier.
     On such devices, strength report should check first if carrier is
     detected at the tuner (``FE_HAS_CARRIER``, see :c:type:`fe_status`),
     and otherwise return the lowest possible value.

Carrier Signal to Noise ratio (:ref:`DTV-STAT-CNR`)
  - Signal to Noise ratio for the main carrier.

  - Signal to Noise measurement depends on the device. On some hardware, it is
    available when the main carrier is detected. On those hardware, CNR
    measurement usually comes from the tuner (e. g. after ``FE_HAS_CARRIER``,
    see :c:type:`fe_status`).

    On other devices, it requires inner FEC decoding,
    as the frontend measures it indirectly from other parameters (e. g. after
    ``FE_HAS_VITERBI``, see :c:type:`fe_status`).

    Having it available after inner FEC is more common.

Bit counts post-FEC (:ref:`DTV-STAT-POST-ERROR-BIT-COUNT` and :ref:`DTV-STAT-POST-TOTAL-BIT-COUNT`)
  - Those counters measure the number of bits and bit errors after
    the forward error correction (FEC) on the inner coding block
    (after Viterbi, LDPC or other inner code).

  - Due to its nature, those statistics depend on full coding lock
    (e. g. after ``FE_HAS_SYNC`` or after ``FE_HAS_LOCK``,
    see :c:type:`fe_status`).

Bit counts pre-FEC (:ref:`DTV-STAT-PRE-ERROR-BIT-COUNT` and :ref:`DTV-STAT-PRE-TOTAL-BIT-COUNT`)
  - Those counters measure the number of bits and bit errors before
    the forward error correction (FEC) on the inner coding block
    (before Viterbi, LDPC or other inner code).

  - Not all frontends provide this kind of statistics.

  - Due to its nature, those statistics depend on inner coding lock (e. g.
    after ``FE_HAS_VITERBI``, see :c:type:`fe_status`).

Block counts (:ref:`DTV-STAT-ERROR-BLOCK-COUNT` and :ref:`DTV-STAT-TOTAL-BLOCK-COUNT`)
  - Those counters measure the number of blocks and block errors after
    the forward error correction (FEC) on the inner coding block
    (before Viterbi, LDPC or other inner code).

  - Due to its nature, those statistics depend on full coding lock
    (e. g. after ``FE_HAS_SYNC`` or after
    ``FE_HAS_LOCK``, see :c:type:`fe_status`).

.. note:: All counters should be monotonically increased as they're
   collected from the hardware.

상태와 통계를 단계적으로 읽는 예제

277-325

전형적인 `.read_status` 구현은 lock 진행 단계에 따라 읽을 수 있는 통계를 차례로 늘립니다. 먼저 항상 제공되는 status와 strength를 읽고, 각 helper가 음수를 반환하면 그 오류를 즉시 전달합니다.

`FE_HAS_CARRIER`가 없으면 CNR을 읽지 않고 성공으로 반환합니다. Carrier가 있으면 CNR을 읽은 뒤 `FE_HAS_VITERBI`를 검사하여 pre-BER 통계의 가용 여부를 결정합니다. 마지막으로 `FE_HAS_SYNC`가 있을 때만 post-BER 통계를 읽습니다.

완성된 함수는 `dvb_frontend_ops.read_status`에 `foo_get_status_and_stats`로 연결됩니다.

read_status 통계 확장 순서
항상`foo_read_status()``foo_read_strength()`
`FE_HAS_CARRIER``foo_read_cnr()`
`FE_HAS_VITERBI``foo_get_pre_ber()`
`FE_HAS_SYNC``foo_get_post_ber()`
각 helper 오류음수 `rc` 즉시 반환

Frontend lock 단계가 진행될수록 비용이 더 큰 통계를 추가로 읽습니다.

A typical example of the logic that handle status and statistics is::

        static int foo_get_status_and_stats(struct dvb_frontend *fe)
        {
                struct foo_state *state = fe->demodulator_priv;
                struct dtv_frontend_properties *c = &fe->dtv_property_cache;

                int rc;
                enum fe_status *status;

                /* Both status and strength are always available */
                rc = foo_read_status(fe, &status);
                if (rc < 0)
                        return rc;

                rc = foo_read_strength(fe);
                if (rc < 0)
                        return rc;

                /* Check if CNR is available */
                if (!(fe->status & FE_HAS_CARRIER))
                        return 0;

                rc = foo_read_cnr(fe);
                if (rc < 0)
                        return rc;

                /* Check if pre-BER stats are available */
                if (!(fe->status & FE_HAS_VITERBI))
                        return 0;

                rc = foo_get_pre_ber(fe);
                if (rc < 0)
                        return rc;

                /* Check if post-BER stats are available */
                if (!(fe->status & FE_HAS_SYNC))
                        return 0;

                rc = foo_get_post_ber(fe);
                if (rc < 0)
                        return rc;
        }

        static const struct dvb_frontend_ops ops = {
                /* ... */
                .read_status = foo_get_status_and_stats,
        };

통계 수집과 ready bit 방식

326-380

거의 모든 frontend 하드웨어에서 bit·byte count는 일정 시간이 지난 뒤 또는 전체 bit/block counter가 설정 가능한 임계값에 도달한 뒤 register에 저장됩니다. 예를 들면 1,000ms마다 또는 1,000,000bit를 받을 때마다 갱신됩니다.

Register를 너무 일찍 다시 읽으면 이전과 같은 값을 읽게 되고, 드라이버가 그 값을 누적 통계에 반복해서 더하여 단조 증가 값을 지나치게 많이 증가시킬 수 있습니다. 따라서 드라이버는 너무 잦은 읽기를 막아야 합니다.

첫 번째 방법은 수집된 데이터가 준비되었음을 나타내는 bit를 확인하는 것입니다. mb86a20s 논리에서 가져온 예제는 register `0x54`를 읽고 오류면 반환하며, 값이 0이면 아직 준비되지 않았으므로 아무 통계도 더하지 않고 성공으로 반환합니다.

Ready 상태이면 `0x55`에서 Bit Error Count를, `0x51`에서 Total Bit Count를 읽습니다. 두 값을 각각 `pre_bit_error`와 `pre_bit_count`의 `uvalue`에 더하고 scale을 `FE_SCALE_COUNTER`로 지정합니다.

Ready bit 기반 counter 수집
Ready register `0x54` 읽기오류오류 반환
Ready = 0갱신 없이 반환
Ready ≠ 0`0x55` error count`0x51` total count
`FE_SCALE_COUNTER` 설정`uvalue += sample`

새 sample이 준비된 경우에만 hardware counter를 누적값에 반영합니다.

Statistics collection
^^^^^^^^^^^^^^^^^^^^^

On almost all frontend hardware, the bit and byte counts are stored by
the hardware after a certain amount of time or after the total bit/block
counter reaches a certain value (usually programmable), for example, on
every 1000 ms or after receiving 1,000,000 bits.

So, if you read the registers too soon, you'll end by reading the same
value as in the previous reading, causing the monotonic value to be
incremented too often.

Drivers should take the responsibility to avoid too often reads. That
can be done using two approaches:

if the driver have a bit that indicates when a collected data is ready
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Driver should check such bit before making the statistics available.

An example of such behavior can be found at this code snippet (adapted
from mb86a20s driver's logic)::

        static int foo_get_pre_ber(struct dvb_frontend *fe)
        {
                struct foo_state *state = fe->demodulator_priv;
                struct dtv_frontend_properties *c = &fe->dtv_property_cache;
                int rc, bit_error;

                /* Check if the BER measures are already available */
                rc = foo_read_u8(state, 0x54);
                if (rc < 0)
                        return rc;

                if (!rc)
                        return 0;

                /* Read Bit Error Count */
                bit_error = foo_read_u32(state, 0x55);
                if (bit_error < 0)
                        return bit_error;

                /* Read Total Bit Count */
                rc = foo_read_u32(state, 0x51);
                if (rc < 0)
                        return rc;

                c->pre_bit_error.stat[0].scale = FE_SCALE_COUNTER;
                c->pre_bit_error.stat[0].uvalue += bit_error;
                c->pre_bit_count.stat[0].scale = FE_SCALE_COUNTER;
                c->pre_bit_count.stat[0].uvalue += rc;

                return 0;
        }

가용 bit가 없을 때의 시간 제한 방식

381-441

일부 장치는 통계가 준비되었는지 확인할 방법을 제공하지 않거나 그 방법이 알려져 있지 않습니다. 전체 bit 또는 block 수를 직접 읽는 방법조차 없을 수 있습니다. 이런 장치의 드라이버는 register를 너무 자주 읽지 않도록 제한하고 필요하면 전체 bit/block 수를 추정해야 합니다.

dib8000 논리에서 가져온 예제는 상태 구조체에 다음 수집 시각인 `per_jiffies_stats`를 저장합니다. `time_after(jiffies, state->per_jiffies_stats)`가 참이 아니면 아직 시간이 지나지 않았으므로 갱신 없이 반환합니다.

수집 시각이 되면 다음 시각을 `jiffies + msecs_to_jiffies(1000)`으로 설정하고 `0x55`에서 Bit Error Count를 읽습니다. 이 frontend에는 1,000ms sample의 전체 bit 수를 제공하는 register가 없으므로 `get_number_of_bits_per_1000ms(fe)`가 DTV property를 바탕으로 값을 계산합니다.

오류 bit 수와 추정한 전체 bit 수는 scale을 `FE_SCALE_COUNTER`로 지정한 뒤 각각 기존 `uvalue`에 누적합니다.

Ready bit 방식과 시간 제한 방식 모두 `.read_status` callback에서 통계를 수집합니다. Frontend가 lock된 동안 core가 이 함수를 보통 초당 세 번 자동 호출하므로, 드라이버는 hardware counter sample을 놓치지 않고 알맞은 시점에 단조 증가 통계에 더할 수 있습니다.

시간 제한 기반 counter 수집
현재 `jiffies``per_jiffies_stats` 이전갱신 없이 반환
수집 시각 도달다음 시각 = 현재 + 1000ms
Error count register 읽기전체 bit 수를 DTV property로 계산
각 `uvalue`에 누적Core의 주기적 `.read_status` 호출

준비 상태를 알 수 없을 때 jiffies로 register 읽기 빈도를 제한합니다.

If the driver doesn't provide a statistics available check bit
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

A few devices, however, may not provide a way to check if the stats are
available (or the way to check it is unknown). They may not even provide
a way to directly read the total number of bits or blocks.

On those devices, the driver need to ensure that it won't be reading from
the register too often and/or estimate the total number of bits/blocks.

On such drivers, a typical routine to get statistics would be like
(adapted from dib8000 driver's logic)::

        struct foo_state {
                /* ... */

                unsigned long per_jiffies_stats;
        }

        static int foo_get_pre_ber(struct dvb_frontend *fe)
        {
                struct foo_state *state = fe->demodulator_priv;
                struct dtv_frontend_properties *c = &fe->dtv_property_cache;
                int rc, bit_error;
                u64 bits;

                /* Check if time for stats was elapsed */
                if (!time_after(jiffies, state->per_jiffies_stats))
                        return 0;

                /* Next stat should be collected in 1000 ms */
                state->per_jiffies_stats = jiffies + msecs_to_jiffies(1000);

                /* Read Bit Error Count */
                bit_error = foo_read_u32(state, 0x55);
                if (bit_error < 0)
                        return bit_error;

                /*
                 * On this particular frontend, there's no register that
                 * would provide the number of bits per 1000ms sample. So,
                 * some function would calculate it based on DTV properties
                 */
                bits = get_number_of_bits_per_1000ms(fe);

                c->pre_bit_error.stat[0].scale = FE_SCALE_COUNTER;
                c->pre_bit_error.stat[0].uvalue += bit_error;
                c->pre_bit_count.stat[0].scale = FE_SCALE_COUNTER;
                c->pre_bit_count.stat[0].uvalue += bits;

                return 0;
        }

Please notice that, on both cases, we're getting the statistics using the
:c:type:`dvb_frontend_ops` ``.read_status`` callback. The rationale is that
the frontend core will automatically call this function periodically
(usually, 3 times per second, when the frontend is locked).

That warrants that we won't miss to collect a counter and increment the
monotonic stats at the right time.

Frontend 함수와 자료형

442-445

Digital TV Frontend의 함수와 자료형에 대한 상세 정의는 `include/media/dvb_frontend.h`의 kernel-doc에서 가져옵니다.

Frontend kernel-doc source
Source path내용
`include/media/dvb_frontend.h`Digital TV Frontend 함수와 자료형

Digital TV Frontend functions and types
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. kernel-doc:: include/media/dvb_frontend.h