Coverage Report

Created: 2026-09-13 06:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/lvm2/libdm/libdevmapper.h
Line
Count
Source
1
/*
2
 * Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved.
3
 * Copyright (C) 2004-2026 Red Hat, Inc. All rights reserved.
4
 * Copyright (C) 2006 Rackable Systems All rights reserved.
5
 *
6
 * This file is part of the device-mapper userspace tools.
7
 *
8
 * This copyrighted material is made available to anyone wishing to use,
9
 * modify, copy, or redistribute it subject to the terms and conditions
10
 * of the GNU Lesser General Public License v.2.1.
11
 *
12
 * You should have received a copy of the GNU Lesser General Public License
13
 * along with this program; if not, write to the Free Software Foundation,
14
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
15
 */
16
17
#ifndef LIB_DEVICE_MAPPER_H
18
#define LIB_DEVICE_MAPPER_H
19
20
#include <inttypes.h>
21
#include <stdarg.h>
22
#include <sys/types.h>
23
#include <sys/stat.h>
24
25
#ifdef __linux__
26
#  include <linux/types.h>
27
#endif
28
29
#include <limits.h>
30
#include <string.h>
31
#include <stdlib.h>
32
#include <stdio.h>
33
#include <stddef.h> /* offsetof */
34
35
#ifndef __GNUC__
36
# define __typeof__ typeof
37
#endif
38
39
/* Macros to make string defines */
40
#define DM_TO_STRING_EXP(A) #A
41
#define DM_TO_STRING(A) DM_TO_STRING_EXP(A)
42
43
0
#define DM_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
44
45
#ifdef __cplusplus
46
extern "C" {
47
#endif
48
49
/*****************************************************************
50
 * The first section of this file provides direct access to the
51
 * individual device-mapper ioctls.  Since it is quite laborious to
52
 * build the ioctl arguments for the device-mapper, people are
53
 * encouraged to use this library.
54
 ****************************************************************/
55
56
/*
57
 * The library user may wish to register their own
58
 * logging function.  By default errors go to stderr.
59
 * Use dm_log_with_errno_init(NULL) to restore the default log fn.
60
 * Error messages may have a non-zero errno.
61
 * Debug messages may have a non-zero class.
62
 * Aborts on internal error when env DM_ABORT_ON_INTERNAL_ERRORS is 1
63
 */
64
65
typedef void (*dm_log_with_errno_fn) (int level, const char *file, int line,
66
              int dm_errno_or_class, const char *f, ...)
67
    __attribute__ ((format(printf, 5, 6)));
68
69
void dm_log_with_errno_init(dm_log_with_errno_fn fn);
70
void dm_log_init_verbose(int level);
71
72
/*
73
 * Original version of this function.
74
 * dm_errno is set to 0.
75
 *
76
 * Deprecated: Use the _with_errno_ versions above instead.
77
 */
78
typedef void (*dm_log_fn) (int level, const char *file, int line,
79
         const char *f, ...)
80
    __attribute__ ((format(printf, 4, 5)));
81
82
void dm_log_init(dm_log_fn fn);
83
/*
84
 * For backward-compatibility, indicate that dm_log_init() was used
85
 * to set a non-default value of dm_log().
86
 */
87
int dm_log_is_non_default(void);
88
89
/*
90
 * Number of devices currently in suspended state (via the library).
91
 */
92
int dm_get_suspended_counter(void);
93
94
enum {
95
  DM_DEVICE_CREATE,
96
  DM_DEVICE_RELOAD,
97
  DM_DEVICE_REMOVE,
98
  DM_DEVICE_REMOVE_ALL,
99
100
  DM_DEVICE_SUSPEND,
101
  DM_DEVICE_RESUME,
102
103
  DM_DEVICE_INFO,
104
  DM_DEVICE_DEPS,
105
  DM_DEVICE_RENAME,
106
107
  DM_DEVICE_VERSION,
108
109
  DM_DEVICE_STATUS,
110
  DM_DEVICE_TABLE,
111
  DM_DEVICE_WAITEVENT,
112
113
  DM_DEVICE_LIST,
114
115
  DM_DEVICE_CLEAR,
116
117
  DM_DEVICE_MKNODES,
118
119
  DM_DEVICE_LIST_VERSIONS,
120
121
  DM_DEVICE_TARGET_MSG,
122
123
  DM_DEVICE_SET_GEOMETRY,
124
125
  DM_DEVICE_ARM_POLL,
126
127
  DM_DEVICE_GET_TARGET_VERSION
128
};
129
130
/*
131
 * You will need to build a struct dm_task for
132
 * each ioctl command you want to execute.
133
 */
134
135
struct dm_pool;
136
struct dm_task;
137
struct dm_timestamp;
138
139
struct dm_task *dm_task_create(int type);
140
void dm_task_destroy(struct dm_task *dmt);
141
142
int dm_task_set_name(struct dm_task *dmt, const char *name);
143
int dm_task_set_uuid(struct dm_task *dmt, const char *uuid);
144
145
/*
146
 * Retrieve attributes after an info.
147
 */
148
struct dm_info {
149
  int exists;
150
  int suspended;
151
  int live_table;
152
  int inactive_table;
153
  int32_t open_count;
154
  uint32_t event_nr;
155
  uint32_t major;
156
  uint32_t minor;   /* minor device number */
157
  int read_only;    /* 0:read-write; 1:read-only */
158
159
  int32_t target_count;
160
161
  int deferred_remove;
162
  int internal_suspend;
163
};
164
165
struct dm_deps {
166
  uint32_t count;
167
  uint32_t filler;
168
  uint64_t device[];
169
};
170
171
struct dm_names {
172
  uint64_t dev;
173
  uint32_t next;    /* Offset to next struct from start of this struct */
174
  char name[];
175
};
176
177
struct dm_versions {
178
  uint32_t next;    /* Offset to next struct from start of this struct */
179
  uint32_t version[3];
180
181
  char name[];
182
};
183
184
int dm_get_library_version(char *version, size_t size);
185
int dm_task_get_driver_version(struct dm_task *dmt, char *version, size_t size);
186
int dm_task_get_info(struct dm_task *dmt, struct dm_info *info);
187
188
/*
189
 * This function returns dm device's UUID based on the value
190
 * of the mangling mode set during preceding dm_task_run call:
191
 *   - unmangled UUID for DM_STRING_MANGLING_{AUTO, HEX},
192
 *   - UUID without any changes for DM_STRING_MANGLING_NONE.
193
 *
194
 * To get mangled or unmangled form of the UUID directly, use
195
 * dm_task_get_uuid_mangled or dm_task_get_uuid_unmangled function.
196
 */
197
const char *dm_task_get_uuid(const struct dm_task *dmt);
198
199
struct dm_deps *dm_task_get_deps(struct dm_task *dmt);
200
struct dm_versions *dm_task_get_versions(struct dm_task *dmt);
201
const char *dm_task_get_message_response(struct dm_task *dmt);
202
203
/*
204
 * These functions return device-mapper names based on the value
205
 * of the mangling mode set during preceding dm_task_run call:
206
 *   - unmangled name for DM_STRING_MANGLING_{AUTO, HEX},
207
 *   - name without any changes for DM_STRING_MANGLING_NONE.
208
 *
209
 * To get mangled or unmangled form of the name directly, use
210
 * dm_task_get_name_mangled or dm_task_get_name_unmangled function.
211
 */
212
const char *dm_task_get_name(const struct dm_task *dmt);
213
struct dm_names *dm_task_get_names(struct dm_task *dmt);
214
215
int dm_task_set_ro(struct dm_task *dmt);
216
int dm_task_set_newname(struct dm_task *dmt, const char *newname);
217
int dm_task_set_newuuid(struct dm_task *dmt, const char *newuuid);
218
int dm_task_set_minor(struct dm_task *dmt, int minor);
219
int dm_task_set_major(struct dm_task *dmt, int major);
220
int dm_task_set_major_minor(struct dm_task *dmt, int major, int minor, int allow_default_major_fallback);
221
int dm_task_set_uid(struct dm_task *dmt, uid_t uid);
222
int dm_task_set_gid(struct dm_task *dmt, gid_t gid);
223
int dm_task_set_mode(struct dm_task *dmt, mode_t mode);
224
/* See also description for DM_UDEV_DISABLE_LIBRARY_FALLBACK flag! */
225
int dm_task_set_cookie(struct dm_task *dmt, uint32_t *cookie, uint16_t flags);
226
int dm_task_set_event_nr(struct dm_task *dmt, uint32_t event_nr);
227
int dm_task_set_geometry(struct dm_task *dmt, const char *cylinders, const char *heads, const char *sectors, const char *start);
228
int dm_task_set_message(struct dm_task *dmt, const char *message);
229
int dm_task_set_sector(struct dm_task *dmt, uint64_t sector);
230
int dm_task_no_flush(struct dm_task *dmt);
231
int dm_task_no_open_count(struct dm_task *dmt);
232
int dm_task_skip_lockfs(struct dm_task *dmt);
233
int dm_task_query_inactive_table(struct dm_task *dmt);
234
int dm_task_suppress_identical_reload(struct dm_task *dmt);
235
int dm_task_secure_data(struct dm_task *dmt);
236
int dm_task_retry_remove(struct dm_task *dmt);
237
int dm_task_deferred_remove(struct dm_task *dmt);
238
int dm_task_ima_measurement(struct dm_task *dmt);
239
240
/*
241
 * Record timestamp immediately after the ioctl returns.
242
 */
243
int dm_task_set_record_timestamp(struct dm_task *dmt);
244
struct dm_timestamp *dm_task_get_ioctl_timestamp(struct dm_task *dmt);
245
246
/*
247
 * Enable checks for common mistakes such as issuing ioctls in an unsafe order.
248
 */
249
int dm_task_enable_checks(struct dm_task *dmt);
250
251
typedef enum dm_add_node_e {
252
  DM_ADD_NODE_ON_RESUME, /* add /dev/mapper node with dmsetup resume */
253
  DM_ADD_NODE_ON_CREATE  /* add /dev/mapper node with dmsetup create */
254
} dm_add_node_t;
255
int dm_task_set_add_node(struct dm_task *dmt, dm_add_node_t add_node);
256
257
/*
258
 * Control read_ahead.
259
 */
260
0
#define DM_READ_AHEAD_AUTO UINT32_MAX  /* Use kernel default readahead */
261
0
#define DM_READ_AHEAD_NONE 0    /* Disable readahead */
262
263
0
#define DM_READ_AHEAD_MINIMUM_FLAG  0x1  /* Value supplied is minimum */
264
265
/*
266
 * Read ahead is set with DM_DEVICE_CREATE with a table or DM_DEVICE_RESUME.
267
 */
268
int dm_task_set_read_ahead(struct dm_task *dmt, uint32_t read_ahead,
269
         uint32_t read_ahead_flags);
270
uint32_t dm_task_get_read_ahead(const struct dm_task *dmt,
271
        uint32_t *read_ahead);
272
273
/*
274
 * Use these to prepare for a create or reload.
275
 */
276
int dm_task_add_target(struct dm_task *dmt,
277
           uint64_t start,
278
           uint64_t size, const char *ttype, const char *params);
279
280
/*
281
 * Format major/minor numbers correctly for input to driver.
282
 */
283
#define DM_FORMAT_DEV_BUFSIZE 13  /* Minimum bufsize to handle worst case. */
284
int dm_format_dev(char *buf, int bufsize, uint32_t dev_major, uint32_t dev_minor);
285
286
/* Use this to retrieve target information returned from a STATUS call */
287
void *dm_get_next_target(struct dm_task *dmt,
288
       void *next, uint64_t *start, uint64_t *length,
289
       char **target_type, char **params);
290
291
/*
292
 * Following dm_get_status_* functions will allocate appropriate status structure
293
 * from passed mempool together with the necessary character arrays.
294
 * Destroying the mempool will release all associated allocation.
295
 */
296
297
/* Parse params from STATUS call for mirror target */
298
typedef enum dm_status_mirror_health_e {
299
  DM_STATUS_MIRROR_ALIVE        = 'A',/* No failures */
300
  DM_STATUS_MIRROR_FLUSH_FAILED = 'F',/* Mirror out-of-sync */
301
  DM_STATUS_MIRROR_WRITE_FAILED = 'D',/* Mirror out-of-sync */
302
  DM_STATUS_MIRROR_SYNC_FAILED  = 'S',/* Mirror out-of-sync */
303
  DM_STATUS_MIRROR_READ_FAILED  = 'R',/* Mirror data unaffected */
304
  DM_STATUS_MIRROR_UNCLASSIFIED = 'U' /* Bug */
305
} dm_status_mirror_health_t;
306
307
struct dm_status_mirror {
308
  uint64_t total_regions;
309
  uint64_t insync_regions;
310
  uint32_t dev_count;             /* # of devs[] elements (<= 8) */
311
  struct dm_dev_leg_health_s {
312
    dm_status_mirror_health_t health;
313
    uint32_t major;
314
    uint32_t minor;
315
  } *devs;                        /* array with individual legs */
316
  const char *log_type;           /* core, disk,.... */
317
  uint32_t log_count;   /* # of logs[] elements */
318
  struct dm_dev_log_health_s {
319
    dm_status_mirror_health_t health;
320
    uint32_t major;
321
    uint32_t minor;
322
  } *logs;      /* array with individual logs */
323
};
324
325
int dm_get_status_mirror(struct dm_pool *mem, const char *params,
326
       struct dm_status_mirror **status);
327
328
/* Parse params from STATUS call for raid target */
329
struct dm_status_raid {
330
  uint64_t reserved;
331
  uint64_t total_regions;   /* sectors */
332
  uint64_t insync_regions;  /* sectors */
333
  uint64_t mismatch_count;
334
  uint32_t dev_count;
335
  char *raid_type;
336
  /* A - alive,  a - alive not in-sync,  D - dead/failed */
337
  char *dev_health;
338
  /* idle, frozen, resync, recover, check, repair */
339
  char *sync_action;
340
  uint64_t data_offset; /* RAID out-of-place reshaping */
341
};
342
343
int dm_get_status_raid(struct dm_pool *mem, const char *params,
344
           struct dm_status_raid **status);
345
346
/* Parse params from STATUS call for cache target */
347
struct dm_status_cache {
348
  uint64_t version;  /* zero for now */
349
350
  uint32_t metadata_block_size;   /* in 512B sectors */
351
  uint32_t block_size;            /* AKA 'chunk_size' */
352
353
  uint64_t metadata_used_blocks;
354
  uint64_t metadata_total_blocks;
355
356
  uint64_t used_blocks;
357
  uint64_t dirty_blocks;
358
  uint64_t total_blocks;
359
360
  uint64_t read_hits;
361
  uint64_t read_misses;
362
  uint64_t write_hits;
363
  uint64_t write_misses;
364
365
  uint64_t demotions;
366
  uint64_t promotions;
367
368
  uint64_t feature_flags;   /* DM_CACHE_FEATURE_? */
369
370
  int core_argc;
371
  char **core_argv;
372
373
  char *policy_name;
374
  int policy_argc;
375
  char **policy_argv;
376
377
  unsigned error : 1;   /* detected error (switches to fail soon) */
378
  unsigned fail : 1;    /* all I/O fails */
379
  unsigned needs_check : 1; /* metadata needs check */
380
  unsigned read_only : 1;   /* metadata may not be changed */
381
  uint32_t reserved : 28;
382
};
383
384
int dm_get_status_cache(struct dm_pool *mem, const char *params,
385
      struct dm_status_cache **status);
386
387
struct dm_status_writecache {
388
  uint64_t error;
389
  uint64_t total_blocks;
390
  uint64_t free_blocks;
391
  uint64_t writeback_blocks;
392
};
393
394
int dm_get_status_writecache(struct dm_pool *mem, const char *params,
395
           struct dm_status_writecache **status);
396
397
struct dm_status_integrity {
398
  uint64_t number_of_mismatches;
399
  uint64_t provided_data_sectors;
400
  uint64_t recalc_sector;
401
};
402
403
int dm_get_status_integrity(struct dm_pool *mem, const char *params,
404
          struct dm_status_integrity **status);
405
406
/*
407
 * RAID target support
408
 */
409
int dm_raid_count_failed_devices(const char *dev_path, uint32_t *nr_failed);
410
int dm_raid_clear_failed_devices(const char *dev_path, uint32_t *nr_failed);
411
412
/*
413
 * Parse params from STATUS call for snapshot target
414
 *
415
 * Snapshot target's format:
416
 * <= 1.7.0: <used_sectors>/<total_sectors>
417
 * >= 1.8.0: <used_sectors>/<total_sectors> <metadata_sectors>
418
 */
419
struct dm_status_snapshot {
420
  uint64_t used_sectors;          /* in 512b units */
421
  uint64_t total_sectors;
422
  uint64_t metadata_sectors;
423
  unsigned has_metadata_sectors : 1; /* set when metadata_sectors is present */
424
  unsigned invalid : 1;   /* set when snapshot is invalidated */
425
  unsigned merge_failed : 1;  /* set when snapshot merge failed */
426
  unsigned overflow : 1;    /* set when snapshot overflows */
427
};
428
429
int dm_get_status_snapshot(struct dm_pool *mem, const char *params,
430
         struct dm_status_snapshot **status);
431
432
/* Parse params from STATUS call for thin_pool target */
433
typedef enum dm_thin_discards_e {
434
  DM_THIN_DISCARDS_IGNORE,
435
  DM_THIN_DISCARDS_NO_PASSDOWN,
436
  DM_THIN_DISCARDS_PASSDOWN
437
} dm_thin_discards_t;
438
439
struct dm_status_thin_pool {
440
  uint64_t transaction_id;
441
  uint64_t used_metadata_blocks;
442
  uint64_t total_metadata_blocks;
443
  uint64_t used_data_blocks;
444
  uint64_t total_data_blocks;
445
  uint64_t held_metadata_root;
446
  uint32_t read_only;   /* metadata may not be changed */
447
  dm_thin_discards_t discards;
448
  uint32_t fail : 1;    /* all I/O fails */
449
  uint32_t error_if_no_space : 1; /* otherwise queue_if_no_space */
450
  uint32_t out_of_data_space : 1; /* metadata may be changed, but data may not be allocated (no rw) */
451
  uint32_t needs_check : 1; /* metadata needs check */
452
  uint32_t error : 1;   /* detected error (switches to fail soon) */
453
  uint32_t reserved : 27;
454
};
455
456
int dm_get_status_thin_pool(struct dm_pool *mem, const char *params,
457
          struct dm_status_thin_pool **status);
458
459
/* Parse params from STATUS call for thin target */
460
struct dm_status_thin {
461
  uint64_t mapped_sectors;
462
  uint64_t highest_mapped_sector;
463
  uint32_t fail : 1;              /* Thin volume fails I/O */
464
  uint32_t reserved : 31;
465
};
466
467
int dm_get_status_thin(struct dm_pool *mem, const char *params,
468
           struct dm_status_thin **status);
469
470
/*
471
 * device-mapper statistics support
472
 */
473
474
/*
475
 * Statistics handle.
476
 *
477
 * Operations on dm_stats objects include managing statistics regions
478
 * and obtaining and manipulating current counter values from the
479
 * kernel. Methods are provided to return basic count values and to
480
 * derive time-based metrics when a suitable interval estimate is
481
 * provided.
482
 *
483
 * Internally the dm_stats handle contains a pointer to a table of one
484
 * or more dm_stats_region objects representing the regions registered
485
 * with the dm_stats_create_region() method. These in turn point to a
486
 * table of one or more dm_stats_counters objects containing the
487
 * counter sets for each defined area within the region:
488
 *
489
 * dm_stats->dm_stats_region[nr_regions]->dm_stats_counters[nr_areas]
490
 *
491
 * This structure is private to the library and may change in future
492
 * versions: all users should make use of the public interface and treat
493
 * the dm_stats type as an opaque handle.
494
 *
495
 * Regions and counter sets are stored in order of increasing region_id.
496
 * Depending on region specifications and the sequence of create and
497
 * delete operations this may not correspond to increasing sector
498
 * number: users of the library should not assume that this is the case
499
 * unless region creation is deliberately managed to ensure this (by
500
 * always creating regions in strict order of ascending sector address).
501
 *
502
 * Regions may also overlap so the same sector range may be included in
503
 * more than one region or area: applications should be prepared to deal
504
 * with this or manage regions such that it does not occur.
505
 */
506
struct dm_stats;
507
508
/*
509
 * Histogram handle.
510
 *
511
 * A histogram object represents the latency histogram values and bin
512
 * boundaries of the histogram associated with a particular area.
513
 *
514
 * Operations on the handle allow the number of bins, bin boundaries,
515
 * counts and relative proportions to be obtained as well as the
516
 * conversion of a histogram or its bounds to a compact string
517
 * representation.
518
 */
519
struct dm_histogram;
520
521
/*
522
 * Allocate a dm_stats handle to use for subsequent device-mapper
523
 * statistics operations. A program_id may be specified and will be
524
 * used by default for subsequent operations on this handle.
525
 *
526
 * If program_id is NULL or the empty string a program_id will be
527
 * automatically set to the value contained in /proc/self/comm.
528
 */
529
struct dm_stats *dm_stats_create(const char *program_id);
530
531
/*
532
 * Bind a dm_stats handle to the specified device major and minor
533
 * values. Any previous binding is cleared and any preexisting counter
534
 * data contained in the handle is released.
535
 */
536
int dm_stats_bind_devno(struct dm_stats *dms, int major, int minor);
537
538
/*
539
 * Bind a dm_stats handle to the specified device name.
540
 * Any previous binding is cleared and any preexisting counter
541
 * data contained in the handle is released.
542
 */
543
int dm_stats_bind_name(struct dm_stats *dms, const char *name);
544
545
/*
546
 * Bind a dm_stats handle to the specified device UUID.
547
 * Any previous binding is cleared and any preexisting counter
548
 * data contained in the handle is released.
549
 */
550
int dm_stats_bind_uuid(struct dm_stats *dms, const char *uuid);
551
552
/*
553
 * Bind a dm_stats handle to the device backing the file referenced
554
 * by the specified file descriptor.
555
 *
556
 * File descriptor fd must reference a regular file, open for reading,
557
 * in a local file system, backed by a device-mapper device, that
558
 * supports the FIEMAP ioctl, and that returns data describing the
559
 * physical location of extents.
560
 */
561
int dm_stats_bind_from_fd(struct dm_stats *dms, int fd);
562
/*
563
 * Test whether the running kernel supports the precise_timestamps
564
 * feature. Presence of this feature also implies histogram support.
565
 * The library will check this call internally and fails any attempt
566
 * to use nanosecond counters or histograms on kernels that fail to
567
 * meet this check.
568
 */
569
int dm_message_supports_precise_timestamps(void);
570
571
/*
572
 * Precise timestamps and histogram support.
573
 *
574
 * Test for the presence of precise_timestamps and histogram support.
575
 */
576
int dm_stats_driver_supports_precise(void);
577
int dm_stats_driver_supports_histogram(void);
578
579
/*
580
 * Returns 1 if the specified region has the precise_timestamps feature
581
 * enabled (i.e. produces nanosecond-precision counter values) or 0 for
582
 * a region using the default millisecond precision.
583
 */
584
int dm_stats_get_region_precise_timestamps(const struct dm_stats *dms,
585
             uint64_t region_id);
586
587
/*
588
 * Returns 1 if the region at the current cursor location has the
589
 * precise_timestamps feature enabled (i.e. produces
590
 * nanosecond-precision counter values) or 0 for a region using the
591
 * default millisecond precision.
592
 */
593
int dm_stats_get_current_region_precise_timestamps(const struct dm_stats *dms);
594
595
#define DM_STATS_ALL_PROGRAMS ""
596
/*
597
 * Parse the response from a @stats_list message. dm_stats_list will
598
 * allocate the necessary dm_stats and dm_stats region structures from
599
 * the embedded dm_pool. No counter data will be obtained (the counters
600
 * members of dm_stats_region objects are set to NULL).
601
 *
602
 * A program_id may optionally be supplied; if the argument is non-NULL
603
 * only regions with a matching program_id value will be considered. If
604
 * the argument is NULL then the default program_id associated with the
605
 * dm_stats handle will be used. Passing the special value
606
 * DM_STATS_ALL_PROGRAMS will cause all regions to be queried
607
 * regardless of region program_id.
608
 */
609
int dm_stats_list(struct dm_stats *dms, const char *program_id);
610
611
#define DM_STATS_REGIONS_ALL UINT64_MAX
612
/*
613
 * Populate a dm_stats object with statistics for one or more regions of
614
 * the specified device.
615
 *
616
 * A program_id may optionally be supplied; if the argument is non-NULL
617
 * only regions with a matching program_id value will be considered. If
618
 * the argument is NULL then the default program_id associated with the
619
 * dm_stats handle will be used. Passing the special value
620
 * DM_STATS_ALL_PROGRAMS will cause all regions to be queried
621
 * regardless of region program_id.
622
 *
623
 * Passing the special value DM_STATS_REGIONS_ALL as the region_id
624
 * argument will attempt to retrieve all regions selected by the
625
 * program_id argument.
626
 *
627
 * If region_id is used to request a single region_id to be populated
628
 * the program_id is ignored.
629
 */
630
int dm_stats_populate(struct dm_stats *dms, const char *program_id,
631
          uint64_t region_id);
632
633
/*
634
 * Create a new statistics region on the device bound to dms.
635
 *
636
 * start and len specify the region start and length in 512b sectors.
637
 * Passing zero for both start and len will create a region spanning
638
 * the entire device.
639
 *
640
 * Step determines how to subdivide the region into discrete counter
641
 * sets: a positive value specifies the size of areas into which the
642
 * region should be split while a negative value will split the region
643
 * into a number of areas equal to the absolute value of step:
644
 *
645
 * - a region with one area spanning the entire device:
646
 *
647
 *   dm_stats_create_region(dms, 0, 0, -1, p, a);
648
 *
649
 * - a region with areas of 1MiB:
650
 *
651
 *   dm_stats_create_region(dms, 0, 0, 1 << 11, p, a);
652
 *
653
 * - one 1MiB region starting at 1024 sectors with two areas:
654
 *
655
 *   dm_stats_create_region(dms, 1024, 1 << 11, -2, p, a);
656
 *
657
 * If precise is non-zero attempt to create a region with nanosecond
658
 * precision counters using the kernel precise_timestamps feature.
659
 *
660
 * precise - A flag to request nanosecond precision counters
661
 * to be used for this region.
662
 *
663
 * histogram_bounds - specify the boundaries of a latency histogram to
664
 * be tracked for the region. The values are expressed as an array of
665
 * uint64_t terminated with a zero. Values must be in order of ascending
666
 * magnitude and specify the upper bounds of successive histogram bins
667
 * in nanoseconds (with an implicit lower bound of zero on the first bin
668
 * and an implicit upper bound of infinity on the final bin). For
669
 * example:
670
 *
671
 *   uint64_t bounds_ary[] = { 1000, 2000, 3000, 0 };
672
 *
673
 * Specifies a histogram with four bins: 0-1000ns, 1000-2000ns,
674
 * 2000-3000ns and >3000ns.
675
 *
676
 * The smallest latency value that can be tracked for a region not using
677
 * precise_timestamps is 1ms: attempting to create a region with
678
 * histogram boundaries < 1ms will cause the precise_timestamps feature
679
 * to be enabled for that region automatically if it was not requested
680
 * explicitly.
681
 *
682
 * program_id is an optional string argument that identifies the
683
 * program creating the region. If program_id is NULL or the empty
684
 * string the default program_id stored in the handle will be used.
685
 *
686
 * user_data is an optional string argument that is added to the
687
 * content of the aux_data field stored with the statistics region by
688
 * the kernel.
689
 *
690
 * The library may also use this space internally, for example, to
691
 * store a group descriptor or other metadata: in this case the
692
 * library will strip any internal data fields from the value before
693
 * it is returned via a call to dm_stats_get_region_aux_data().
694
 *
695
 * The user data stored is not accessed by the library or kernel and
696
 * may be used to store an arbitrary data word (embedded whitespace is
697
 * not permitted).
698
 *
699
 * An application using both the library and direct access to the
700
 * @stats_list device-mapper message may see the internal values stored
701
 * in this field by the library. In such cases any string up to and
702
 * including the first '#' in the field must be treated as an opaque
703
 * value and preserved across any external modification of aux_data.
704
 *
705
 * The region_id of the newly-created region is returned in *region_id
706
 * if it is non-NULL.
707
 */
708
int dm_stats_create_region(struct dm_stats *dms, uint64_t *region_id,
709
         uint64_t start, uint64_t len, int64_t step,
710
         int precise, struct dm_histogram *bounds,
711
         const char *program_id, const char *user_data);
712
713
/*
714
 * Delete the specified statistics region. This will also mark the
715
 * region as not-present and discard any existing statistics data.
716
 */
717
int dm_stats_delete_region(struct dm_stats *dms, uint64_t region_id);
718
719
/*
720
 * Clear the specified statistics region. This requests the kernel to
721
 * zero all counter values (except in-flight I/O). Note that this
722
 * operation is not atomic with respect to reads of the counters; any IO
723
 * events occurring between the last print operation and the clear will
724
 * be lost. This can be avoided by using the atomic print-and-clear
725
 * function of the dm_stats_print_region() call or by using the higher
726
 * level dm_stats_populate() interface.
727
 */
728
int dm_stats_clear_region(struct dm_stats *dms, uint64_t region_id);
729
730
/*
731
 * Print the current counter values for the specified statistics region
732
 * and return them as a string. The memory for the string buffer will
733
 * be allocated from the dm_stats handle's private pool and should be
734
 * returned by calling dm_stats_buffer_destroy() when no longer
735
 * required. The pointer will become invalid following any call that
736
 * clears or reinitializes the handle (destroy, list, populate, bind).
737
 *
738
 * This allows applications that wish to access the raw message response
739
 * to obtain it via a dm_stats handle; no parsing of the textual counter
740
 * data is carried out by this function.
741
 *
742
 * Most users are recommended to use the dm_stats_populate() call
743
 * instead since this will automatically parse the statistics data into
744
 * numeric form accessible via the dm_stats_get_*() counter access
745
 * methods.
746
 *
747
 * A subset of the data lines may be requested by setting the
748
 * start_line and num_lines parameters. If both are zero all data
749
 * lines are returned.
750
 *
751
 * If the clear parameter is non-zero the operation will also
752
 * atomically reset all counter values to zero (except in-flight IO).
753
 */
754
char *dm_stats_print_region(struct dm_stats *dms, uint64_t region_id,
755
          unsigned start_line, unsigned num_lines,
756
          unsigned clear);
757
758
/*
759
 * Destroy a statistics response buffer obtained from a call to
760
 * dm_stats_print_region().
761
 */
762
void dm_stats_buffer_destroy(struct dm_stats *dms, char *buffer);
763
764
/*
765
 * Determine the number of regions contained in a dm_stats handle
766
 * following a dm_stats_list() or dm_stats_populate() call.
767
 *
768
 * The value returned is the number of registered regions visible with the
769
 * program_id value used for the list or populate operation and may not be
770
 * equal to the highest present region_id (either due to program_id
771
 * filtering or gaps in the sequence of region_id values).
772
 *
773
 * Always returns zero on an empty handle.
774
 */
775
uint64_t dm_stats_get_nr_regions(const struct dm_stats *dms);
776
777
/*
778
 * Determine the number of groups contained in a dm_stats handle
779
 * following a dm_stats_list() or dm_stats_populate() call.
780
 *
781
 * The value returned is the number of registered groups visible with the
782
 * program_id value used for the list or populate operation and may not be
783
 * equal to the highest present group_id (either due to program_id
784
 * filtering or gaps in the sequence of group_id values).
785
 *
786
 * Always returns zero on an empty handle.
787
 */
788
uint64_t dm_stats_get_nr_groups(const struct dm_stats *dms);
789
790
/*
791
 * Test whether region_id is present in this dm_stats handle.
792
 */
793
int dm_stats_region_present(const struct dm_stats *dms, uint64_t region_id);
794
795
/*
796
 * Returns the number of areas (counter sets) contained in the specified
797
 * region_id of the supplied dm_stats handle.
798
 */
799
uint64_t dm_stats_get_region_nr_areas(const struct dm_stats *dms,
800
              uint64_t region_id);
801
802
/*
803
 * Returns the total number of areas (counter sets) in all regions of the
804
 * given dm_stats object.
805
 */
806
uint64_t dm_stats_get_nr_areas(const struct dm_stats *dms);
807
808
/*
809
 * Test whether group_id is present in this dm_stats handle.
810
 */
811
int dm_stats_group_present(const struct dm_stats *dms, uint64_t group_id);
812
813
/*
814
 * Return the number of bins in the histogram configuration for the
815
 * specified region or zero if no histogram specification is configured.
816
 * Valid following a dm_stats_list() or dm_stats_populate() operation.
817
 */
818
int dm_stats_get_region_nr_histogram_bins(const struct dm_stats *dms,
819
            uint64_t region_id);
820
821
/*
822
 * Parse a histogram string with optional unit suffixes into a
823
 * dm_histogram bounds description.
824
 *
825
 * A histogram string is a string of numbers "n1,n2,n3,..." that
826
 * represent the boundaries of a histogram. The first and final bins
827
 * have implicit lower and upper bounds of zero and infinity
828
 * respectively and boundary values must occur in order of ascending
829
 * magnitude.  Unless a unit suffix is given all values are specified in
830
 * nanoseconds.
831
 *
832
 * For example, if bounds_str="300,600,900", the region will be created
833
 * with a histogram containing four bins. Each report will include four
834
 * numbers a:b:c:d. a is the number of requests that took between 0 and
835
 * 300ns to complete, b is the number of requests that took 300-600ns to
836
 * complete, c is the number of requests that took 600-900ns to complete
837
 * and d is the number of requests that took more than 900ns to
838
 * complete.
839
 *
840
 * An optional unit suffix of 's', 'ms', 'us', or 'ns' may be used to
841
 * specify units of seconds, milliseconds, microseconds, or nanoseconds:
842
 *
843
 *   bounds_str="1ns,1us,1ms,1s"
844
 *   bounds_str="500us,1ms,1500us,2ms"
845
 *   bounds_str="200ms,400ms,600ms,800ms,1s"
846
 *
847
 * The smallest valid unit of time for a histogram specification depends
848
 * on whether the region uses precise timestamps: for a region with the
849
 * default millisecond precision the smallest possible histogram boundary
850
 * magnitude is one millisecond: attempting to use a histogram with a
851
 * boundary less than one millisecond when creating a region will cause
852
 * the region to be created with the precise_timestamps feature enabled.
853
 *
854
 * On success a pointer to the struct dm_histogram representing the
855
 * bounds values is returned, or NULL in the case of error. The returned
856
 * pointer should be freed using dm_free() when no longer required.
857
 */
858
struct dm_histogram *dm_histogram_bounds_from_string(const char *bounds_str);
859
860
/*
861
 * Parse a zero terminated array of uint64_t into a dm_histogram bounds
862
 * description.
863
 *
864
 * Each value in the array specifies the upper bound of a bin in the
865
 * latency histogram in nanoseconds. Values must appear in ascending
866
 * order of magnitude.
867
 *
868
 * The smallest valid unit of time for a histogram specification depends
869
 * on whether the region uses precise timestamps: for a region with the
870
 * default millisecond precision the smallest possible histogram boundary
871
 * magnitude is one millisecond: attempting to use a histogram with a
872
 * boundary less than one millisecond when creating a region will cause
873
 * the region to be created with the precise_timestamps feature enabled.
874
 */
875
struct dm_histogram *dm_histogram_bounds_from_uint64(const uint64_t *bounds);
876
877
/*
878
 * Destroy the histogram bounds array obtained from a call to
879
 * dm_histogram_bounds_from_string().
880
 */
881
void dm_histogram_bounds_destroy(struct dm_histogram *bounds);
882
883
/*
884
 * Destroy a dm_stats object and all associated regions, counter
885
 * sets and histograms.
886
 */
887
void dm_stats_destroy(struct dm_stats *dms);
888
889
/*
890
 * Counter sampling interval
891
 */
892
893
/*
894
 * Set the sampling interval for counter data to the specified value in
895
 * either nanoseconds or milliseconds.
896
 *
897
 * The interval is used to calculate time-based metrics from the basic
898
 * counter data: an interval must be set before calling any of the
899
 * metric methods.
900
 *
901
 * For best accuracy the duration should be measured and updated at the
902
 * end of each interval.
903
 *
904
 * All values are stored internally with nanosecond precision and are
905
 * converted to or from ms when the millisecond interfaces are used.
906
 */
907
void dm_stats_set_sampling_interval_ns(struct dm_stats *dms,
908
               uint64_t interval_ns);
909
910
void dm_stats_set_sampling_interval_ms(struct dm_stats *dms,
911
               uint64_t interval_ms);
912
913
/*
914
 * Retrieve the configured sampling interval in either nanoseconds or
915
 * milliseconds.
916
 */
917
uint64_t dm_stats_get_sampling_interval_ns(const struct dm_stats *dms);
918
uint64_t dm_stats_get_sampling_interval_ms(const struct dm_stats *dms);
919
920
/*
921
 * Override program_id. This may be used to change the default
922
 * program_id value for an existing handle. If the allow_empty argument
923
 * is non-zero a NULL or empty program_id is permitted.
924
 *
925
 * Use with caution! Most users of the library should set a valid,
926
 * non-NULL program_id for every statistics region created. Failing to
927
 * do so may result in confusing state when multiple programs are
928
 * creating and managing statistics regions.
929
 *
930
 * All users of the library are encouraged to choose an unambiguous,
931
 * unique program_id: this could be based on PID (for programs that
932
 * create, report, and delete regions in a single process), session id,
933
 * executable name, or some other distinguishing string.
934
 *
935
 * Use of the empty string as a program_id does not simplify use of the
936
 * library or the command line tools and use of this value is strongly
937
 * discouraged.
938
 */
939
int dm_stats_set_program_id(struct dm_stats *dms, int allow_empty,
940
          const char *program_id);
941
942
/*
943
 * Region properties: size, length & area_len.
944
 *
945
 * Region start and length are returned in units of 512b as specified
946
 * at region creation time. The area_len value gives the size of areas
947
 * into which the region has been subdivided. For regions with a single
948
 * area spanning the range this value is equal to the region length.
949
 *
950
 * For regions created with a specified number of areas the value
951
 * represents the size of the areas into which the kernel divided the
952
 * region excluding any rounding of the last area size. The number of
953
 * areas may be obtained using the dm_stats_nr_areas_region() call.
954
 *
955
 * All values are returned in units of 512b sectors.
956
 */
957
int dm_stats_get_region_start(const struct dm_stats *dms, uint64_t *start,
958
            uint64_t region_id);
959
960
int dm_stats_get_region_len(const struct dm_stats *dms, uint64_t *len,
961
          uint64_t region_id);
962
963
int dm_stats_get_region_area_len(const struct dm_stats *dms,
964
         uint64_t *len, uint64_t region_id);
965
966
/*
967
 * Area properties: start, offset and length.
968
 *
969
 * The area length is always equal to the area length of the region
970
 * that contains it and is obtained from dm_stats_get_region_area_len().
971
 *
972
 * The start of an area is a function of the area_id and the containing
973
 * region's start and area length: it gives the absolute offset into the
974
 * containing device of the beginning of the area.
975
 *
976
 * The offset expresses the area's relative offset into the current
977
 * region. I.e. the area start minus the start offset of the containing
978
 * region.
979
 *
980
 * All values are returned in units of 512b sectors.
981
 */
982
int dm_stats_get_area_start(const struct dm_stats *dms, uint64_t *start,
983
          uint64_t region_id, uint64_t area_id);
984
985
int dm_stats_get_area_offset(const struct dm_stats *dms, uint64_t *offset,
986
           uint64_t region_id, uint64_t area_id);
987
988
/*
989
 * Retrieve program_id and user aux_data for a specific region.
990
 *
991
 * Only valid following a call to dm_stats_list().
992
 */
993
994
/*
995
 * Retrieve program_id for the specified region.
996
 *
997
 * The returned pointer does not need to be freed separately from the
998
 * dm_stats handle but will become invalid after a dm_stats_destroy(),
999
 * dm_stats_list(), dm_stats_populate(), or dm_stats_bind*() of the
1000
 * handle from which it was obtained.
1001
 */
1002
const char *dm_stats_get_region_program_id(const struct dm_stats *dms,
1003
             uint64_t region_id);
1004
1005
/*
1006
 * Retrieve user aux_data set for the specified region. This function
1007
 * will return any stored user aux_data as a string in the memory
1008
 * pointed to by the aux_data argument.
1009
 *
1010
 * Any library internal aux_data fields, such as DMS_GROUP descriptors,
1011
 * are stripped before the value is returned.
1012
 *
1013
 * The returned pointer does not need to be freed separately from the
1014
 * dm_stats handle but will become invalid after a dm_stats_destroy(),
1015
 * dm_stats_list(), dm_stats_populate(), or dm_stats_bind*() of the
1016
 * handle from which it was obtained.
1017
 */
1018
const char *dm_stats_get_region_aux_data(const struct dm_stats *dms,
1019
           uint64_t region_id);
1020
1021
typedef enum dm_stats_obj_type_e {
1022
  DM_STATS_OBJECT_TYPE_NONE,
1023
  DM_STATS_OBJECT_TYPE_AREA,
1024
  DM_STATS_OBJECT_TYPE_REGION,
1025
  DM_STATS_OBJECT_TYPE_GROUP
1026
} dm_stats_obj_type_t;
1027
1028
/*
1029
 * Statistics cursor
1030
 *
1031
 * A dm_stats handle maintains an optional cursor into the statistics
1032
 * tables that it stores. Iterators are provided to visit each region,
1033
 * area, or group in a handle and accessor methods are provided to
1034
 * obtain properties and values for the object at the current cursor
1035
 * position.
1036
 *
1037
 * Using the cursor simplifies walking all regions or groups when
1038
 * the tables are sparse (i.e. contains some present and some
1039
 * non-present region_id or group_id values either due to program_id
1040
 * filtering or the ordering of region and group creation and deletion).
1041
 *
1042
 * Simple macros are provided to visit each area, region, or group,
1043
 * contained in a handle and applications are encouraged to use these
1044
 * where possible.
1045
 */
1046
1047
/*
1048
 * Walk flags are used to initialise a dm_stats handle's cursor control
1049
 * and to select region or group aggregation when calling a metric or
1050
 * counter property method with immediate group, region, and area ID
1051
 * values.
1052
 *
1053
 * Walk flags are stored in the uppermost word of a uint64_t so that
1054
 * a region_id or group_id may be encoded in the lower bits. This
1055
 * allows an aggregate region_id or group_id to be specified when
1056
 * retrieving counter or metric values.
1057
 *
1058
 * Flags may be ORred together when used to initialise a dm_stats_walk:
1059
 * the resulting walk will visit instance of each type specified by
1060
 * the flag combination.
1061
 */
1062
#define DM_STATS_WALK_AREA   0x1000000000000ULL
1063
#define DM_STATS_WALK_REGION 0x2000000000000ULL
1064
#define DM_STATS_WALK_GROUP  0x4000000000000ULL
1065
1066
#define DM_STATS_WALK_ALL    0x7000000000000ULL
1067
#define DM_STATS_WALK_DEFAULT (DM_STATS_WALK_AREA | DM_STATS_WALK_REGION)
1068
1069
/*
1070
 * Skip regions from a DM_STATS_WALK_REGION that contain only a single
1071
 * area: in this case the region's aggregate values are identical to
1072
 * the values of the single contained area. Setting this flag will
1073
 * suppress these duplicate entries during a dm_stats_walk_* with the
1074
 * DM_STATS_WALK_REGION flag set.
1075
 */
1076
#define DM_STATS_WALK_SKIP_SINGLE_AREA   0x8000000000000ULL
1077
1078
/*
1079
 * Initialise the cursor control of a dm_stats handle for the specified
1080
 * walk type(s). Including a walk flag in the flags argument will cause
1081
 * any subsequent walk to visit that type of object (until the next
1082
 * call to dm_stats_walk_init()).
1083
 */
1084
int dm_stats_walk_init(struct dm_stats *dms, uint64_t flags);
1085
1086
/*
1087
 * Set the cursor of a dm_stats handle to address the first present
1088
 * group, region, or area of the currently configured walk. It is
1089
 * valid to attempt to walk a NULL stats handle or a handle containing
1090
 * no present regions; in this case any call to dm_stats_walk_next()
1091
 * becomes a no-op and all calls to dm_stats_walk_end() return true.
1092
 */
1093
void dm_stats_walk_start(struct dm_stats *dms);
1094
1095
/*
1096
 * Advance the statistics cursor to the next area, or to the next
1097
 * present region if at the end of the current region. If the end of
1098
 * the region, area, or group tables is reached a subsequent call to
1099
 * dm_stats_walk_end() will return 1 and dm_stats_object_type() called
1100
 * on the location will return DM_STATS_OBJECT_TYPE_NONE,
1101
 */
1102
void dm_stats_walk_next(struct dm_stats *dms);
1103
1104
/*
1105
 * Force the statistics cursor to advance to the next region. This will
1106
 * stop any in-progress area walk (by clearing DM_STATS_WALK_AREA) and
1107
 * advance the cursor to the next present region, the first present
1108
 * group (if DM_STATS_GROUP_WALK is set), or to the end. In this case a
1109
 * subsequent call to dm_stats_walk_end() will return 1 and a call to
1110
 * dm_stats_object_type() for the location will return
1111
 * DM_STATS_OBJECT_TYPE_NONE.
1112
 */
1113
void dm_stats_walk_next_region(struct dm_stats *dms);
1114
1115
/*
1116
 * Test whether the end of a statistics walk has been reached.
1117
 */
1118
int dm_stats_walk_end(struct dm_stats *dms);
1119
1120
/*
1121
 * Return the type of object at the location specified by region_id
1122
 * and area_id. If either region_id or area_id uses one of the special
1123
 * values DM_STATS_REGION_CURRENT or DM_STATS_AREA_CURRENT the
1124
 * corresponding region or area identifier will be taken from the
1125
 * current cursor location. If the cursor location or the value encoded
1126
 * by region_id and area_id indicates an aggregate region or group,
1127
 * this will be reflected in the value returned.
1128
 */
1129
dm_stats_obj_type_t dm_stats_object_type(const struct dm_stats *dms,
1130
           uint64_t region_id,
1131
           uint64_t area_id);
1132
1133
/*
1134
 * Return the type of object at the current stats cursor location.
1135
 */
1136
dm_stats_obj_type_t dm_stats_current_object_type(const struct dm_stats *dms);
1137
1138
/*
1139
 * Stats iterators
1140
 *
1141
 * C 'for' and 'do'/'while' style iterators for dm_stats data.
1142
 *
1143
 * It is not safe to call any function that modifies the region table
1144
 * within the loop body (i.e. dm_stats_list(), dm_stats_populate(),
1145
 * dm_stats_init(), or dm_stats_destroy()).
1146
 *
1147
 * All counter and property (dm_stats_get_*) access methods, as well as
1148
 * dm_stats_populate_region() can be safely called from loops.
1149
 *
1150
 */
1151
1152
/*
1153
 * Iterate over the regions table visiting each region.
1154
 *
1155
 * If the region table is empty or unpopulated the loop body will not be
1156
 * executed.
1157
 */
1158
#define dm_stats_foreach_region(dms)        \
1159
for (dm_stats_walk_init((dms), DM_STATS_WALK_REGION),   \
1160
     dm_stats_walk_start((dms));        \
1161
     !dm_stats_walk_end((dms)); dm_stats_walk_next_region((dms)))
1162
1163
/*
1164
 * Iterate over the regions table visiting each area.
1165
 *
1166
 * If the region table is empty or unpopulated the loop body will not
1167
 * be executed.
1168
 */
1169
#define dm_stats_foreach_area(dms)        \
1170
for (dm_stats_walk_init((dms), DM_STATS_WALK_AREA),   \
1171
     dm_stats_walk_start((dms));        \
1172
     !dm_stats_walk_end((dms)); dm_stats_walk_next((dms)))
1173
1174
/*
1175
 * Iterate over the regions table visiting each group. Metric and
1176
 * counter methods will return values for the group.
1177
 *
1178
 * If the group table is empty or unpopulated the loop body will not
1179
 * be executed.
1180
 */
1181
#define dm_stats_foreach_group(dms)       \
1182
for (dm_stats_walk_init((dms), DM_STATS_WALK_GROUP),    \
1183
     dm_stats_walk_start((dms));        \
1184
     !dm_stats_walk_end((dms));         \
1185
     dm_stats_walk_next((dms)))
1186
1187
/*
1188
 * Start a walk iterating over the regions contained in dm_stats handle
1189
 * 'dms'.
1190
 *
1191
 * The body of the loop should call dm_stats_walk_next() or
1192
 * dm_stats_walk_next_region() to advance to the next element.
1193
 *
1194
 * The loop body is executed at least once even if the stats handle is
1195
 * empty.
1196
 */
1197
#define dm_stats_walk_do(dms)         \
1198
do {                \
1199
  dm_stats_walk_start((dms));       \
1200
  do
1201
1202
/*
1203
 * Start a 'while' style loop or end a 'do..while' loop iterating over the
1204
 * regions contained in dm_stats handle 'dms'.
1205
 */
1206
#define dm_stats_walk_while(dms)        \
1207
  while(!dm_stats_walk_end((dms)));     \
1208
} while (0)
1209
1210
/*
1211
 * Cursor relative property methods
1212
 *
1213
 * Calls with the prefix dm_stats_get_current_* operate relative to the
1214
 * current cursor location, returning properties for the current region
1215
 * or area of the supplied dm_stats handle.
1216
 *
1217
 */
1218
1219
/*
1220
 * Returns the number of areas (counter sets) contained in the current
1221
 * region of the supplied dm_stats handle.
1222
 */
1223
uint64_t dm_stats_get_current_nr_areas(const struct dm_stats *dms);
1224
1225
/*
1226
 * Retrieve the current values of the stats cursor.
1227
 */
1228
uint64_t dm_stats_get_current_region(const struct dm_stats *dms);
1229
uint64_t dm_stats_get_current_area(const struct dm_stats *dms);
1230
1231
/*
1232
 * Current region properties: size, length & area_len.
1233
 *
1234
 * See the comments for the equivalent dm_stats_get_* versions for a
1235
 * complete description of these methods.
1236
 *
1237
 * All values are returned in units of 512b sectors.
1238
 */
1239
int dm_stats_get_current_region_start(const struct dm_stats *dms,
1240
              uint64_t *start);
1241
1242
int dm_stats_get_current_region_len(const struct dm_stats *dms,
1243
            uint64_t *len);
1244
1245
int dm_stats_get_current_region_area_len(const struct dm_stats *dms,
1246
           uint64_t *area_len);
1247
1248
/*
1249
 * Current area properties: start and length.
1250
 *
1251
 * See the comments for the equivalent dm_stats_get_* versions for a
1252
 * complete description of these methods.
1253
 *
1254
 * All values are returned in units of 512b sectors.
1255
 */
1256
int dm_stats_get_current_area_start(const struct dm_stats *dms,
1257
            uint64_t *start);
1258
1259
int dm_stats_get_current_area_offset(const struct dm_stats *dms,
1260
             uint64_t *offset);
1261
1262
int dm_stats_get_current_area_len(const struct dm_stats *dms,
1263
               uint64_t *len);
1264
1265
/*
1266
 * Return a pointer to the program_id string for region at the current
1267
 * cursor location.
1268
 */
1269
const char *dm_stats_get_current_region_program_id(const struct dm_stats *dms);
1270
1271
/*
1272
 * Return a pointer to the user aux_data string for the region at the
1273
 * current cursor location.
1274
 */
1275
const char *dm_stats_get_current_region_aux_data(const struct dm_stats *dms);
1276
1277
/*
1278
 * Statistics groups and data aggregation.
1279
 */
1280
1281
/*
1282
 * Create a new group in stats handle dms from the group descriptor
1283
 * passed in group. The group descriptor is a string containing a list
1284
 * of region_id values that will be included in the group. The first
1285
 * region_id found will be the group leader. Ranges of identifiers may
1286
 * be expressed as "M-N", where M and N are the start and end region_id
1287
 * values for the range.
1288
 */
1289
int dm_stats_create_group(struct dm_stats *dms, const char *members,
1290
        const char *alias, uint64_t *group_id);
1291
1292
/*
1293
 * Remove the specified group_id. If the remove argument is zero the
1294
 * group will be removed but the regions that it contained will remain.
1295
 * If remove is non-zero then all regions that belong to the group will
1296
 * also be removed.
1297
 */
1298
int dm_stats_delete_group(struct dm_stats *dms, uint64_t group_id, int remove_regions);
1299
1300
/*
1301
 * Set an alias for this group or region. The alias will be returned
1302
 * instead of the normal dm-stats name for this region or group.
1303
 */
1304
int dm_stats_set_alias(struct dm_stats *dms, uint64_t group_id,
1305
           const char *alias);
1306
1307
/*
1308
 * Returns a pointer to the currently configured alias for id, or the
1309
 * name of the dm device the handle is bound to if no alias has been
1310
 * set. The pointer will be freed automatically when a new alias is set
1311
 * or when the stats handle is cleared.
1312
 */
1313
const char *dm_stats_get_alias(const struct dm_stats *dms, uint64_t id);
1314
1315
#define DM_STATS_GROUP_NONE UINT64_MAX
1316
/*
1317
 * Return the group_id that the specified region_id belongs to, or the
1318
 * special value DM_STATS_GROUP_NONE if the region does not belong
1319
 * to any group.
1320
 */
1321
uint64_t dm_stats_get_group_id(const struct dm_stats *dms, uint64_t region_id);
1322
1323
/*
1324
 * Store a pointer to a string describing the regions that are members
1325
 * of the group specified by group_id in the memory pointed to by buf.
1326
 * The string is in the same format as the 'group' argument to
1327
 * dm_stats_create_group().
1328
 *
1329
 * The pointer does not need to be freed explicitly by the caller: it
1330
 * will become invalid following a subsequent dm_stats_list(),
1331
 * dm_stats_populate() or dm_stats_destroy() of the corresponding
1332
 * dm_stats handle.
1333
 */
1334
int dm_stats_get_group_descriptor(const struct dm_stats *dms,
1335
          uint64_t group_id, char **buf);
1336
1337
/*
1338
 * Create regions that correspond to the extents of a file in the
1339
 * filesystem and optionally place them into a group.
1340
 *
1341
 * File descriptor fd must reference a regular file, open for reading,
1342
 * in a local file system that supports the FIEMAP ioctl, and that
1343
 * returns data describing the physical location of extents.
1344
 *
1345
 * The file descriptor can be closed by the caller following the call
1346
 * to dm_stats_create_regions_from_fd().
1347
 *
1348
 * Unless nogroup is non-zero the regions will be placed into a group
1349
 * and the group alias set to the value supplied (if alias is NULL no
1350
 * group alias will be assigned).
1351
 *
1352
 * On success the function returns a pointer to an array of uint64_t
1353
 * containing the IDs of the newly created regions. The region_id
1354
 * array is terminated by the value DM_STATS_REGION_NOT_PRESENT and
1355
 * should be freed using dm_free() when no longer required.
1356
 *
1357
 * On error NULL is returned.
1358
 *
1359
 * Following a call to dm_stats_create_regions_from_fd() the handle
1360
 * is guaranteed to be in a listed state, and to contain any region
1361
 * and group identifiers created by the operation.
1362
 *
1363
 * The group_id for the new group is equal to the region_id value in
1364
 * the first array element.
1365
 */
1366
uint64_t *dm_stats_create_regions_from_fd(struct dm_stats *dms, int fd,
1367
            int group, int precise,
1368
            struct dm_histogram *bounds,
1369
            const char *alias);
1370
/*
1371
 * Update a group of regions that correspond to the extents of a file
1372
 * in the filesystem, adding and removing regions to account for
1373
 * allocation changes in the underlying file.
1374
 *
1375
 * File descriptor fd must reference a regular file, open for reading,
1376
 * in a local file system that supports the FIEMAP ioctl, and that
1377
 * returns data describing the physical location of extents.
1378
 *
1379
 * The file descriptor can be closed by the caller following the call
1380
 * to dm_stats_update_regions_from_fd().
1381
 *
1382
 * On success the function returns a pointer to an array of uint64_t
1383
 * containing the IDs of the updated regions (including any existing
1384
 * regions that were not modified by the call).
1385
 *
1386
 * The region_id array is terminated by the special value
1387
 * DM_STATS_REGION_NOT_PRESENT and should be freed using dm_free()
1388
 * when no longer required.
1389
 *
1390
 * On error NULL is returned.
1391
 *
1392
 * Following a call to dm_stats_update_regions_from_fd() the handle
1393
 * is guaranteed to be in a listed state, and to contain any region
1394
 * and group identifiers created by the operation.
1395
 *
1396
 * This function cannot be used with file mapped regions that are
1397
 * not members of a group: either group the regions, or remove them
1398
 * and re-map them with dm_stats_create_regions_from_fd().
1399
 */
1400
uint64_t *dm_stats_update_regions_from_fd(struct dm_stats *dms, int fd,
1401
            uint64_t group_id);
1402
1403
1404
/*
1405
 * The file map monitoring daemon can monitor files in two distinct
1406
 * ways: the mode affects the behaviour of the daemon when a file
1407
 * under monitoring is renamed or unlinked, and the conditions which
1408
 * cause the daemon to terminate.
1409
 *
1410
 * In both modes, the daemon will always shut down when the group
1411
 * being monitored is deleted.
1412
 *
1413
 * Follow inode:
1414
 * The daemon follows the inode of the file, as it was at the time the
1415
 * daemon started. The file descriptor referencing the file is kept
1416
 * open at all times, and the daemon will exit when it detects that
1417
 * the file has been unlinked and it is the last holder of a reference
1418
 * to the file.
1419
 *
1420
 * This mode is useful if the file is expected to be renamed, or moved
1421
 * within the file system, while it is being monitored.
1422
 *
1423
 * Follow path:
1424
 * The daemon follows the path that was given on the daemon command
1425
 * line. The file descriptor referencing the file is re-opened on each
1426
 * iteration of the daemon, and the daemon will exit if no file exists
1427
 * at this location (a tolerance is allowed so that a brief delay
1428
 * between unlink() and creat() is permitted).
1429
 *
1430
 * This mode is useful if the file is updated by unlinking the original
1431
 * and placing a new file at the same path.
1432
 */
1433
1434
typedef enum dm_filemapd_mode_e {
1435
  DM_FILEMAPD_FOLLOW_INODE,
1436
  DM_FILEMAPD_FOLLOW_PATH,
1437
  DM_FILEMAPD_FOLLOW_NONE
1438
} dm_filemapd_mode_t;
1439
1440
/*
1441
 * Parse a string representation of a dmfilemapd mode.
1442
 *
1443
 * Returns a valid dm_filemapd_mode_t value on success, or
1444
 * DM_FILEMAPD_FOLLOW_NONE on error.
1445
 */
1446
dm_filemapd_mode_t dm_filemapd_mode_from_string(const char *mode_str);
1447
1448
/*
1449
 * Start the dmfilemapd filemap monitoring daemon for the specified
1450
 * file descriptor, group, and file system path. The daemon will
1451
 * monitor the file for allocation changes, and when a change is
1452
 * detected, call dm_stats_update_regions_from_fd() to update the
1453
 * mapped regions for the file.
1454
 *
1455
 * The path provided to dm_stats_start_filemapd() must be an absolute
1456
 * path, and should reflect the path of 'fd' at the time that it was
1457
 * opened.
1458
 *
1459
 * The mode parameter controls the behaviour of the daemon when the
1460
 * file being monitored is unlinked or moved: see the comments for
1461
 * dm_filemapd_mode_t for a full description and possible values.
1462
 *
1463
 * The daemon can be stopped at any time by sending SIGTERM to the
1464
 * daemon pid.
1465
 */
1466
int dm_stats_start_filemapd(int fd, uint64_t group_id, const char *path,
1467
          dm_filemapd_mode_t mode, unsigned foreground,
1468
          unsigned verbose);
1469
1470
/*
1471
 * Call this to actually run the ioctl.
1472
 */
1473
int dm_task_run(struct dm_task *dmt);
1474
1475
/*
1476
 * The errno from the last device-mapper ioctl performed by dm_task_run.
1477
 */
1478
int dm_task_get_errno(struct dm_task *dmt);
1479
1480
/*
1481
 * Call this to make or remove the device nodes associated with previously
1482
 * issued commands.
1483
 */
1484
void dm_task_update_nodes(void);
1485
1486
/*
1487
 * Mangling support
1488
 *
1489
 * Character whitelist: 0-9, A-Z, a-z, #+-.:=@_
1490
 * HEX mangling format: \xNN, NN being the hex value of the character.
1491
 * (whitelist and format supported by udev)
1492
*/
1493
typedef enum dm_string_mangling_e {
1494
  DM_STRING_MANGLING_NONE, /* do not mangle at all */
1495
  DM_STRING_MANGLING_AUTO, /* mangle only if not already mangled with hex, error when mixed */
1496
  DM_STRING_MANGLING_HEX   /* always mangle with hex encoding, no matter what the input is */
1497
} dm_string_mangling_t;
1498
1499
/*
1500
 * Set/get mangling mode used for device-mapper names and uuids.
1501
 */
1502
int dm_set_name_mangling_mode(dm_string_mangling_t name_mangling_mode);
1503
dm_string_mangling_t dm_get_name_mangling_mode(void);
1504
1505
/*
1506
 * Get mangled/unmangled form of the device-mapper name or uuid
1507
 * irrespective of the global setting (set by dm_set_name_mangling_mode).
1508
 * The name or uuid returned needs to be freed after use by calling dm_free!
1509
 */
1510
char *dm_task_get_name_mangled(const struct dm_task *dmt);
1511
char *dm_task_get_name_unmangled(const struct dm_task *dmt);
1512
char *dm_task_get_uuid_mangled(const struct dm_task *dmt);
1513
char *dm_task_get_uuid_unmangled(const struct dm_task *dmt);
1514
1515
/*
1516
 * Configure the device-mapper directory
1517
 */
1518
int dm_set_dev_dir(const char *dev_dir);
1519
const char *dm_dir(void);
1520
1521
/*
1522
 * Configure sysfs directory, /sys by default
1523
 */
1524
int dm_set_sysfs_dir(const char *sysfs_dir);
1525
const char *dm_sysfs_dir(void);
1526
1527
/*
1528
 * Configure default UUID prefix string.
1529
 * Conventionally this is a short capitalized prefix indicating the subsystem
1530
 * that is managing the devices, e.g. "LVM-" or "MPATH-".
1531
 * To support stacks of devices from different subsystems, recursive functions
1532
 * stop recursing if they reach a device with a different prefix.
1533
 */
1534
int dm_set_uuid_prefix(const char *uuid_prefix);
1535
const char *dm_uuid_prefix(void);
1536
1537
/*
1538
 * Determine whether a major number belongs to device-mapper or not.
1539
 */
1540
int dm_is_dm_major(uint32_t major);
1541
1542
/*
1543
 * Get associated device name for given major and minor number by reading
1544
 * the sysfs content. If this is a dm device, get associated dm name, the one
1545
 * that appears in /dev/mapper. DM names could be resolved this way only if
1546
 * kernel used >= 2.6.29, kernel name is found otherwise (e.g. dm-0).
1547
 * If prefer_kernel_name is set, the kernel name is always preferred over
1548
 * device-mapper name for dm devices no matter what the kernel version is.
1549
 * For non-dm devices, we always get associated kernel name, e.g sda, md0 etc.
1550
 * Returns 0 on error or if sysfs is not used (or configured incorrectly),
1551
 * otherwise returns 1 and the supplied buffer holds the device name.
1552
 */
1553
int dm_device_get_name(uint32_t major, uint32_t minor,
1554
           int prefer_kernel_name,
1555
           char *buf, size_t buf_size);
1556
1557
/*
1558
 * Determine whether a device has any holders (devices
1559
 * using this device). If sysfs is not used (or configured
1560
 * incorrectly), returns 0.
1561
 */
1562
int dm_device_has_holders(uint32_t major, uint32_t minor);
1563
1564
/*
1565
 * Determine whether a device contains mounted filesystem.
1566
 * If sysfs is not used (or configured incorrectly), returns 0.
1567
 */
1568
int dm_device_has_mounted_fs(uint32_t major, uint32_t minor);
1569
1570
1571
/*
1572
 * Callback is invoked for individual mountinfo lines,
1573
 * minor, major and mount target are parsed and unmangled.
1574
 */
1575
typedef int (*dm_mountinfo_line_callback_fn) (char *line, unsigned maj, unsigned min,
1576
                char *target, void *cb_data);
1577
1578
/*
1579
 * Read all lines from /proc/self/mountinfo,
1580
 * for each line calls read_fn callback.
1581
 */
1582
int dm_mountinfo_read(dm_mountinfo_line_callback_fn read_fn, void *cb_data);
1583
1584
/*
1585
 * Initialise library.  This is normally done automatically when the
1586
 * library is loaded.
1587
 */
1588
void dm_lib_init(void);
1589
1590
/* Release reusable library resources. */
1591
void dm_lib_release(void);
1592
1593
/*
1594
 * Compatibility wrapper for dm_lib_release().  Final library teardown is
1595
 * performed automatically when the library is unloaded.
1596
 */
1597
void dm_lib_exit(void);
1598
1599
/* An optimisation for clients making repeated calls involving dm ioctls */
1600
void dm_hold_control_dev(int hold_open);
1601
1602
/*
1603
 * Use NULL for all devices.
1604
 */
1605
int dm_mknodes(const char *name);
1606
int dm_driver_version(char *version, size_t size);
1607
1608
/******************************************************
1609
 * Functions to build and manipulate trees of devices *
1610
 ******************************************************/
1611
struct dm_tree;
1612
struct dm_tree_node;
1613
1614
/*
1615
 * Initialise an empty dependency tree.
1616
 *
1617
 * The tree consists of a root node together with one node for each mapped
1618
 * device which has child nodes for each device referenced in its table.
1619
 *
1620
 * Every node in the tree has one or more children and one or more parents.
1621
 *
1622
 * The root node is the parent/child of every node that doesn't have other
1623
 * parents/children.
1624
 */
1625
struct dm_tree *dm_tree_create(void);
1626
void dm_tree_free(struct dm_tree *dtree);
1627
1628
/*
1629
 * List of suffixes to be ignored when matching uuids against existing devices.
1630
 */
1631
void dm_tree_set_optional_uuid_suffixes(struct dm_tree *dtree, const char **optional_uuid_suffixes);
1632
1633
/*
1634
 * Add nodes to the tree for a given device and all the devices it uses.
1635
 */
1636
int dm_tree_add_dev(struct dm_tree *dtree, uint32_t major, uint32_t minor);
1637
int dm_tree_add_dev_with_udev_flags(struct dm_tree *dtree, uint32_t major,
1638
            uint32_t minor, uint16_t udev_flags);
1639
1640
/*
1641
 * Add a new node to the tree if it doesn't already exist.
1642
 */
1643
struct dm_tree_node *dm_tree_add_new_dev(struct dm_tree *dtree,
1644
           const char *name,
1645
           const char *uuid,
1646
           uint32_t major, uint32_t minor,
1647
           int read_only,
1648
           int clear_inactive,
1649
           void *context);
1650
struct dm_tree_node *dm_tree_add_new_dev_with_udev_flags(struct dm_tree *dtree,
1651
               const char *name,
1652
               const char *uuid,
1653
               uint32_t major,
1654
               uint32_t minor,
1655
               int read_only,
1656
               int clear_inactive,
1657
               void *context,
1658
               uint16_t udev_flags);
1659
1660
/*
1661
 * Search for a node in the tree.
1662
 * Set major and minor to 0 or uuid to NULL to get the root node.
1663
 */
1664
struct dm_tree_node *dm_tree_find_node(struct dm_tree *dtree,
1665
               uint32_t major,
1666
               uint32_t minor);
1667
struct dm_tree_node *dm_tree_find_node_by_uuid(struct dm_tree *dtree,
1668
                 const char *uuid);
1669
1670
/*
1671
 * Use this to walk through all children of a given node.
1672
 * Set handle to NULL in first call.
1673
 * Returns NULL after the last child.
1674
 * Set inverted to use inverted tree.
1675
 */
1676
struct dm_tree_node *dm_tree_next_child(void **handle,
1677
          const struct dm_tree_node *parent,
1678
          uint32_t inverted);
1679
1680
/*
1681
 * Get properties of a node.
1682
 */
1683
const char *dm_tree_node_get_name(const struct dm_tree_node *node);
1684
const char *dm_tree_node_get_uuid(const struct dm_tree_node *node);
1685
const struct dm_info *dm_tree_node_get_info(const struct dm_tree_node *node);
1686
void *dm_tree_node_get_context(const struct dm_tree_node *node);
1687
/*
1688
 * Returns  0 when node size and its children is unchanged.
1689
 * Returns  1 when node or any of its children has increased size.
1690
 * Returns -1 when node or any of its children has reduced size.
1691
 */
1692
int dm_tree_node_size_changed(const struct dm_tree_node *dnode);
1693
1694
/*
1695
 * Returns the number of children of the given node (excluding the root node).
1696
 * Set inverted for the number of parents.
1697
 */
1698
int dm_tree_node_num_children(const struct dm_tree_node *node, uint32_t inverted);
1699
1700
/*
1701
 * Deactivate a device plus all dependencies.
1702
 * Ignores devices that don't have a uuid starting with uuid_prefix.
1703
 */
1704
int dm_tree_deactivate_children(struct dm_tree_node *dnode,
1705
        const char *uuid_prefix,
1706
        size_t uuid_prefix_len);
1707
/*
1708
 * Preload/create a device plus all dependencies.
1709
 * Ignores devices that don't have a uuid starting with uuid_prefix.
1710
 */
1711
int dm_tree_preload_children(struct dm_tree_node *dnode,
1712
           const char *uuid_prefix,
1713
           size_t uuid_prefix_len);
1714
1715
/*
1716
 * Resume a device plus all dependencies.
1717
 * Ignores devices that don't have a uuid starting with uuid_prefix.
1718
 */
1719
int dm_tree_activate_children(struct dm_tree_node *dnode,
1720
            const char *uuid_prefix,
1721
            size_t uuid_prefix_len);
1722
1723
/*
1724
 * Suspend a device plus all dependencies.
1725
 * Ignores devices that don't have a uuid starting with uuid_prefix.
1726
 */
1727
int dm_tree_suspend_children(struct dm_tree_node *dnode,
1728
           const char *uuid_prefix,
1729
           size_t uuid_prefix_len);
1730
1731
/*
1732
 * Skip the filesystem sync when suspending.
1733
 * Does nothing with other functions.
1734
 * Use this when no snapshots are involved.
1735
 */
1736
void dm_tree_skip_lockfs(struct dm_tree_node *dnode);
1737
1738
/*
1739
 * Set the 'noflush' flag when suspending devices.
1740
 * If the kernel supports it, instead of erroring outstanding I/O that
1741
 * cannot be completed, the I/O is queued and resubmitted when the
1742
 * device is resumed.  This affects multipath devices when all paths
1743
 * have failed and queue_if_no_path is set, and mirror devices when
1744
 * block_on_error is set and the mirror log has failed.
1745
 */
1746
void dm_tree_use_no_flush_suspend(struct dm_tree_node *dnode);
1747
1748
/*
1749
 * Retry removal of each device if not successful.
1750
 */
1751
void dm_tree_retry_remove(struct dm_tree_node *dnode);
1752
1753
/*
1754
 * Is the uuid prefix present in the tree?
1755
 * Only returns 0 if every node was checked successfully.
1756
 * Returns 1 if the tree walk has to be aborted.
1757
 */
1758
int dm_tree_children_use_uuid(struct dm_tree_node *dnode,
1759
            const char *uuid_prefix,
1760
            size_t uuid_prefix_len);
1761
1762
/*
1763
 * Construct tables for new nodes before activating them.
1764
 */
1765
int dm_tree_node_add_snapshot_origin_target(struct dm_tree_node *dnode,
1766
              uint64_t size,
1767
              const char *origin_uuid);
1768
int dm_tree_node_add_snapshot_target(struct dm_tree_node *node,
1769
             uint64_t size,
1770
             const char *origin_uuid,
1771
             const char *cow_uuid,
1772
             int persistent,
1773
             uint32_t chunk_size);
1774
int dm_tree_node_add_snapshot_merge_target(struct dm_tree_node *node,
1775
             uint64_t size,
1776
             const char *origin_uuid,
1777
             const char *cow_uuid,
1778
             const char *merge_uuid,
1779
             uint32_t chunk_size);
1780
int dm_tree_node_add_error_target(struct dm_tree_node *node,
1781
          uint64_t size);
1782
int dm_tree_node_add_zero_target(struct dm_tree_node *node,
1783
         uint64_t size);
1784
int dm_tree_node_add_linear_target(struct dm_tree_node *node,
1785
           uint64_t size);
1786
int dm_tree_node_add_striped_target(struct dm_tree_node *node,
1787
            uint64_t size,
1788
            uint32_t stripe_size);
1789
1790
#define DM_CRYPT_IV_DEFAULT UINT64_C(-1)  /* iv_offset == seg offset */
1791
/*
1792
 * Function accepts one string in cipher specification
1793
 * (chainmode and iv should be NULL because included in cipher string)
1794
 *   or
1795
 * separate arguments which will be joined to "cipher-chainmode-iv"
1796
 */
1797
int dm_tree_node_add_crypt_target(struct dm_tree_node *node,
1798
          uint64_t size,
1799
          const char *cipher,
1800
          const char *chainmode,
1801
          const char *iv,
1802
          uint64_t iv_offset,
1803
          const char *key);
1804
int dm_tree_node_add_mirror_target(struct dm_tree_node *node,
1805
           uint64_t size);
1806
1807
/* Mirror log flags */
1808
#define DM_NOSYNC   0x00000001  /* Known already in sync */
1809
#define DM_FORCESYNC    0x00000002  /* Force resync */
1810
#define DM_BLOCK_ON_ERROR 0x00000004  /* On error, suspend I/O */
1811
#define DM_CORELOG    0x00000008  /* In-memory log */
1812
1813
int dm_tree_node_add_mirror_target_log(struct dm_tree_node *node,
1814
               uint32_t region_size,
1815
               const char *log_uuid,
1816
               unsigned area_count,
1817
               uint32_t flags);
1818
1819
int dm_tree_node_add_raid_target(struct dm_tree_node *node,
1820
         uint64_t size,
1821
         const char *raid_type,
1822
         uint32_t region_size,
1823
         uint32_t stripe_size,
1824
         uint64_t rebuilds,
1825
         uint64_t flags);
1826
1827
/*
1828
 * Defines below are based on kernel's dm-cache.c defines
1829
 * DM_CACHE_MIN_DATA_BLOCK_SIZE (32 * 1024 >> SECTOR_SHIFT)
1830
 * DM_CACHE_MAX_DATA_BLOCK_SIZE (1024 * 1024 * 1024 >> SECTOR_SHIFT)
1831
 */
1832
#define DM_CACHE_MIN_DATA_BLOCK_SIZE (UINT32_C(64))
1833
#define DM_CACHE_MAX_DATA_BLOCK_SIZE (UINT32_C(2097152))
1834
/*
1835
 * Max supported size for cache pool metadata device.
1836
 * Limitation is hardcoded into the kernel and bigger device sizes
1837
 * are not accepted.
1838
 *
1839
 * Limit defined in drivers/md/dm-cache-metadata.h
1840
 */
1841
#define DM_CACHE_METADATA_MAX_SECTORS DM_THIN_METADATA_MAX_SECTORS
1842
1843
/*
1844
 * Define number of elements in rebuild and writemostly arrays
1845
 * 'of struct dm_tree_node_raid_params'.
1846
 */
1847
1848
struct dm_tree_node_raid_params {
1849
  const char *raid_type;
1850
1851
  uint32_t stripes;
1852
  uint32_t mirrors;
1853
  uint32_t region_size;
1854
  uint32_t stripe_size;
1855
1856
  /*
1857
   * 'rebuilds' and 'writemostly' are bitfields that signify
1858
   * which devices in the array are to be rebuilt or marked
1859
   * writemostly.  The kernel supports up to 253 legs.
1860
   * We limit ourselves by choosing a lower value
1861
   * for DEFAULT_RAID{1}_MAX_IMAGES in defaults.h.
1862
   */
1863
  uint64_t rebuilds;
1864
  uint64_t writemostly;
1865
  uint32_t writebehind;     /* I/Os (kernel default COUNTER_MAX / 2) */
1866
  uint32_t sync_daemon_sleep; /* ms (kernel default = 5sec) */
1867
  uint32_t max_recovery_rate; /* kB/sec/disk */
1868
  uint32_t min_recovery_rate; /* kB/sec/disk */
1869
  uint32_t stripe_cache;      /* sectors */
1870
1871
  uint64_t flags;             /* [no]sync */
1872
  uint32_t reserved2;
1873
};
1874
1875
/*
1876
 * Version 2 of above node raid params struct to keep API compatibility.
1877
 *
1878
 * Extended for more than 64 legs (max 253 in the MD kernel runtime!),
1879
 * delta_disks for disk add/remove reshaping,
1880
 * data_offset for out-of-place reshaping
1881
 * and data_copies for odd number of raid10 legs.
1882
 */
1883
#define RAID_BITMAP_SIZE 4 /* 4 * 64 bit elements in rebuilds/writemostly arrays */
1884
struct dm_tree_node_raid_params_v2 {
1885
  const char *raid_type;
1886
1887
  uint32_t stripes;
1888
  uint32_t mirrors;
1889
  uint32_t region_size;
1890
  uint32_t stripe_size;
1891
1892
  int delta_disks; /* +/- number of disks to add/remove (reshaping) */
1893
  int data_offset; /* data offset to set (out-of-place reshaping) */
1894
1895
  /*
1896
   * 'rebuilds' and 'writemostly' are bitfields that signify
1897
   * which devices in the array are to be rebuilt or marked
1898
   * writemostly.  The kernel supports up to 253 legs.
1899
   * We limit ourselves by choosing a lower value
1900
   * for DEFAULT_RAID_MAX_IMAGES.
1901
   */
1902
  uint64_t rebuilds[RAID_BITMAP_SIZE];
1903
  uint64_t writemostly[RAID_BITMAP_SIZE];
1904
  uint32_t writebehind;     /* I/Os (kernel default COUNTER_MAX / 2) */
1905
  uint32_t data_copies;     /* RAID # of data copies */
1906
  uint32_t sync_daemon_sleep; /* ms (kernel default = 5sec) */
1907
  uint32_t max_recovery_rate; /* kB/sec/disk */
1908
  uint32_t min_recovery_rate; /* kB/sec/disk */
1909
  uint32_t stripe_cache;      /* sectors */
1910
1911
  uint64_t flags;             /* [no]sync */
1912
};
1913
1914
int dm_tree_node_add_raid_target_with_params(struct dm_tree_node *node,
1915
               uint64_t size,
1916
               const struct dm_tree_node_raid_params *p);
1917
1918
/* Version 2 API function taking dm_tree_node_raid_params_v2 for aforementioned extensions. */
1919
int dm_tree_node_add_raid_target_with_params_v2(struct dm_tree_node *node,
1920
            uint64_t size,
1921
            const struct dm_tree_node_raid_params_v2 *p);
1922
1923
/* Cache feature_flags */
1924
#define DM_CACHE_FEATURE_WRITEBACK    0x00000001
1925
#define DM_CACHE_FEATURE_WRITETHROUGH 0x00000002
1926
#define DM_CACHE_FEATURE_PASSTHROUGH  0x00000004
1927
#define DM_CACHE_FEATURE_METADATA2    0x00000008 /* cache v1.10 */
1928
#define DM_CACHE_FEATURE_NO_DISCARD_PASSDOWN 0x00000010
1929
1930
struct dm_config_node;
1931
/*
1932
 * Use for passing cache policy and all its args e.g.:
1933
 *
1934
 * policy_settings {
1935
 *    migration_threshold=2048
1936
 *    sequential_threshold=100
1937
 *    ...
1938
 * }
1939
 *
1940
 * For policy without any parameters use NULL.
1941
 */
1942
int dm_tree_node_add_cache_target(struct dm_tree_node *node,
1943
          uint64_t size,
1944
          uint64_t feature_flags, /* DM_CACHE_FEATURE_* */
1945
          const char *metadata_uuid,
1946
          const char *data_uuid,
1947
          const char *origin_uuid,
1948
          const char *policy_name,
1949
          const struct dm_config_node *policy_settings,
1950
          uint32_t data_block_size);
1951
1952
/*
1953
 * Add a cache target using a cachevol (single LV with metadata and data).
1954
 * The cachevol_uuid refers to a single device containing both metadata and data,
1955
 * with metadata_start/metadata_len and data_start/data_len specifying the regions.
1956
 */
1957
int dm_tree_node_add_cachevol_target(struct dm_tree_node *node,
1958
             uint64_t size,
1959
             uint64_t feature_flags, /* DM_CACHE_FEATURE_* */
1960
             const char *metadata_uuid,
1961
             const char *data_uuid,
1962
             const char *cachevol_uuid,
1963
             const char *origin_uuid,
1964
             const char *policy_name,
1965
             const struct dm_config_node *policy_settings,
1966
             uint64_t metadata_start,
1967
             uint64_t metadata_len,
1968
             uint64_t data_start,
1969
             uint64_t data_len,
1970
             uint32_t data_block_size);
1971
1972
struct dm_writecache_settings {
1973
  /*
1974
   * Allow an unrecognized key and its val to be passed to the kernel for
1975
   * cases where a new kernel setting is added but lvm doesn't know about
1976
   * it yet.
1977
   */
1978
  char *new_key;
1979
  char *new_val;
1980
1981
  /*
1982
   * Flag is 1 if a value has been set.
1983
   */
1984
  unsigned high_watermark_set:1;
1985
  unsigned low_watermark_set:1;
1986
  unsigned writeback_jobs_set:1;
1987
  unsigned autocommit_blocks_set:1;
1988
  unsigned autocommit_time_set:1;
1989
  unsigned fua_set:1;
1990
  unsigned nofua_set:1;
1991
  unsigned cleaner_set:1;
1992
  unsigned max_age_set:1;
1993
  unsigned metadata_only_set:1;
1994
  unsigned pause_writeback_set:1;
1995
  uint32_t reserved : 21;
1996
1997
  uint64_t high_watermark;
1998
  uint64_t low_watermark;
1999
  uint64_t writeback_jobs;
2000
  uint64_t autocommit_blocks;
2001
  uint64_t autocommit_time; /* in milliseconds */
2002
  uint32_t fua;
2003
  uint32_t nofua;
2004
  uint32_t cleaner;
2005
  uint32_t max_age;         /* in milliseconds */
2006
  uint32_t metadata_only;
2007
  uint32_t pause_writeback; /* in milliseconds */
2008
};
2009
2010
int dm_tree_node_add_writecache_target(struct dm_tree_node *node,
2011
        uint64_t size,
2012
        const char *origin_uuid,
2013
        const char *cache_uuid,
2014
        int pmem,
2015
        uint32_t writecache_block_size,
2016
        struct dm_writecache_settings *settings);
2017
2018
struct dm_integrity_settings {
2019
  char mode[8];
2020
  uint32_t tag_size;
2021
  uint32_t block_size;       /* optional table param always set by lvm */
2022
  const char *internal_hash; /* optional table param always set by lvm */
2023
2024
  uint32_t journal_sectors;
2025
  uint32_t interleave_sectors;
2026
  uint32_t buffer_sectors;
2027
  uint32_t journal_watermark;
2028
  uint32_t commit_time;
2029
  uint32_t bitmap_flush_interval;
2030
  uint64_t sectors_per_bit;
2031
  uint32_t allow_discards;
2032
2033
  unsigned journal_sectors_set:1;
2034
  unsigned interleave_sectors_set:1;
2035
  unsigned buffer_sectors_set:1;
2036
  unsigned journal_watermark_set:1;
2037
  unsigned commit_time_set:1;
2038
  unsigned bitmap_flush_interval_set:1;
2039
  unsigned sectors_per_bit_set:1;
2040
  unsigned allow_discards_set:1;
2041
};
2042
2043
int dm_tree_node_add_integrity_target(struct dm_tree_node *node,
2044
        uint64_t size,
2045
        const char *origin_uuid,
2046
        const char *meta_uuid,
2047
        struct dm_integrity_settings *settings,
2048
        int recalculate);
2049
2050
/*
2051
 * VDO target support
2052
 */
2053
2054
#define DM_SECTOR_SHIFT 9L
2055
2056
#define DM_VDO_BLOCK_SIZE     UINT64_C(8)   // 4KiB in sectors
2057
#define DM_VDO_BLOCK_SIZE_KB      (DM_VDO_BLOCK_SIZE << DM_SECTOR_SHIFT)
2058
2059
#define DM_VDO_BLOCK_MAP_CACHE_SIZE_MINIMUM_MB  (128)     // 128MiB
2060
#define DM_VDO_BLOCK_MAP_CACHE_SIZE_MAXIMUM_MB  (16 * 1024 * 1024 - 1)  /* 16TiB - 1MiB */
2061
#define DM_VDO_BLOCK_MAP_CACHE_SIZE_MINIMUM_PER_LOGICAL_THREAD  (4096 * DM_VDO_BLOCK_SIZE_KB)
2062
2063
#define DM_VDO_BLOCK_MAP_ERA_LENGTH_MINIMUM 1
2064
#define DM_VDO_BLOCK_MAP_ERA_LENGTH_MAXIMUM 16380
2065
2066
#define DM_VDO_INDEX_MEMORY_SIZE_MINIMUM_MB 256     // 0.25 GiB
2067
#define DM_VDO_INDEX_MEMORY_SIZE_MAXIMUM_MB (1024 * 1024)   // 1TiB
2068
2069
#define DM_VDO_SLAB_SIZE_MINIMUM_MB   128     // 128MiB
2070
#define DM_VDO_SLAB_SIZE_MAXIMUM_MB   (32 * 1024)   // 32GiB
2071
#define DM_VDO_SLABS_MAXIMUM      8192
2072
2073
#define DM_VDO_LOGICAL_SIZE_MAXIMUM (UINT64_C(4) * 1024 * 1024 * 1024 * 1024 * 1024 >> DM_SECTOR_SHIFT) // 4PiB
2074
#define DM_VDO_PHYSICAL_SIZE_MAXIMUM  (UINT64_C(64) * DM_VDO_BLOCK_SIZE_KB * 1024 * 1024 * 1024 >> DM_SECTOR_SHIFT) // 256TiB
2075
2076
#define DM_VDO_ACK_THREADS_MINIMUM    0
2077
#define DM_VDO_ACK_THREADS_MAXIMUM    100
2078
2079
#define DM_VDO_BIO_THREADS_MINIMUM    1
2080
#define DM_VDO_BIO_THREADS_MAXIMUM    100
2081
2082
#define DM_VDO_BIO_ROTATION_MINIMUM   1
2083
#define DM_VDO_BIO_ROTATION_MAXIMUM   1024
2084
2085
#define DM_VDO_CPU_THREADS_MINIMUM    1
2086
#define DM_VDO_CPU_THREADS_MAXIMUM    100
2087
2088
#define DM_VDO_HASH_ZONE_THREADS_MINIMUM  0
2089
#define DM_VDO_HASH_ZONE_THREADS_MAXIMUM  100
2090
2091
#define DM_VDO_LOGICAL_THREADS_MINIMUM    0
2092
#define DM_VDO_LOGICAL_THREADS_MAXIMUM    60
2093
2094
#define DM_VDO_PHYSICAL_THREADS_MINIMUM   0
2095
#define DM_VDO_PHYSICAL_THREADS_MAXIMUM   16
2096
2097
#define DM_VDO_MAX_DISCARD_MINIMUM    1
2098
#define DM_VDO_MAX_DISCARD_MAXIMUM    (UINT32_MAX / (uint32_t)(DM_VDO_BLOCK_SIZE_KB))
2099
2100
enum dm_vdo_operating_mode {
2101
  DM_VDO_MODE_RECOVERING,
2102
  DM_VDO_MODE_READ_ONLY,
2103
  DM_VDO_MODE_NORMAL
2104
};
2105
2106
enum dm_vdo_compression_state {
2107
  DM_VDO_COMPRESSION_ONLINE,
2108
  DM_VDO_COMPRESSION_OFFLINE
2109
};
2110
2111
enum dm_vdo_index_state {
2112
  DM_VDO_INDEX_ERROR,
2113
  DM_VDO_INDEX_CLOSED,
2114
  DM_VDO_INDEX_OPENING,
2115
  DM_VDO_INDEX_CLOSING,
2116
  DM_VDO_INDEX_OFFLINE,
2117
  DM_VDO_INDEX_ONLINE,
2118
  DM_VDO_INDEX_UNKNOWN
2119
};
2120
2121
struct dm_vdo_status {
2122
  char *device;
2123
  enum dm_vdo_operating_mode operating_mode;
2124
  int recovering;
2125
  enum dm_vdo_index_state index_state;
2126
  enum dm_vdo_compression_state compression_state;
2127
  uint64_t used_blocks;
2128
  uint64_t total_blocks;
2129
};
2130
2131
#define DM_VDO_MAX_ERROR 256
2132
2133
struct dm_vdo_status_parse_result {
2134
  char error[DM_VDO_MAX_ERROR];
2135
  struct dm_vdo_status *status;
2136
};
2137
2138
enum dm_vdo_write_policy {
2139
  DM_VDO_WRITE_POLICY_AUTO = 0,
2140
  DM_VDO_WRITE_POLICY_SYNC,
2141
  DM_VDO_WRITE_POLICY_ASYNC,
2142
  DM_VDO_WRITE_POLICY_ASYNC_UNSAFE
2143
};
2144
2145
struct dm_vdo_target_params {
2146
  uint32_t minimum_io_size;       /* in sectors */
2147
  uint32_t block_map_cache_size_mb;
2148
  union {
2149
    uint32_t block_map_era_length;  /* format period */
2150
    uint32_t block_map_period;      /* supported alias */
2151
  };
2152
  uint32_t index_memory_size_mb;  /* format */
2153
2154
  uint32_t slab_size_mb;          /* format */
2155
2156
  uint32_t max_discard;
2157
  /* threads */
2158
  uint32_t ack_threads;
2159
  uint32_t bio_threads;
2160
  uint32_t bio_rotation;
2161
  uint32_t cpu_threads;
2162
  uint32_t hash_zone_threads;
2163
  uint32_t logical_threads;
2164
  uint32_t physical_threads;
2165
2166
  int use_compression;
2167
  int use_deduplication;
2168
  int use_metadata_hints;
2169
  int use_sparse_index;          /* format */
2170
2171
  /* write policy */
2172
  enum dm_vdo_write_policy write_policy;
2173
2174
  int use_kernel_format;         /* kernel direct format (added last for ABI compat) */
2175
};
2176
2177
int dm_vdo_validate_target_params(const struct dm_vdo_target_params *vtp,
2178
          uint64_t vdo_size);
2179
2180
int dm_tree_node_add_vdo_target(struct dm_tree_node *node,
2181
        uint64_t size,
2182
        uint32_t vdo_version,
2183
        const char *vdo_pool_name,
2184
        const char *data_uuid,
2185
        uint64_t data_size,
2186
        const struct dm_vdo_target_params *vtp);
2187
2188
int dm_vdo_parse_logical_size(const char *vdo_path, uint64_t *logical_blocks);
2189
2190
int dm_vdo_status_parse(struct dm_pool *mem, const char *input,
2191
      struct dm_vdo_status_parse_result *result);
2192
2193
struct dm_vdo_stats {
2194
  uint64_t physical_blocks;
2195
  uint64_t logical_blocks;
2196
  uint64_t bytes_per_physical_block;
2197
  uint64_t bytes_per_logical_block;
2198
  uint64_t data_blocks_used;
2199
  uint64_t overhead_blocks_used;
2200
  uint64_t logical_blocks_used;
2201
  uint64_t bios_in; /* write bios only (kernel: biosIn.write) */
2202
  uint64_t bios_out;  /* write bios only (kernel: biosOut.write) */
2203
  uint64_t bios_meta; /* write bios only (kernel: biosMeta.write) */
2204
  enum dm_vdo_operating_mode operating_mode;
2205
};
2206
2207
#define DM_VDO_STAT_FIELD_LEN 80
2208
2209
struct dm_vdo_stats_field {
2210
  char label[DM_VDO_STAT_FIELD_LEN];
2211
  char value[DM_VDO_STAT_FIELD_LEN];
2212
};
2213
2214
struct dm_vdo_stats_full {
2215
  struct dm_vdo_stats *stats;
2216
  unsigned field_count;
2217
  struct dm_vdo_stats_field fields[];
2218
};
2219
2220
#define DM_VDO_STATS_BASIC 0x0
2221
#define DM_VDO_STATS_FULL  0x1
2222
2223
struct dm_vdo_stats_full *dm_vdo_stats_parse(struct dm_pool *mem,
2224
               const char *stats_str,
2225
               unsigned flags);
2226
2227
/*
2228
 * FIXME Add individual cache policy pairs  <key> = value, like:
2229
 * int dm_tree_node_add_cache_policy_arg(struct dm_tree_node *dnode,
2230
 *              const char *key, uint64_t value);
2231
 */
2232
2233
/*
2234
 * Replicator operation mode
2235
 * Note: API for Replicator is not yet stable
2236
 */
2237
typedef enum dm_replicator_mode_e {
2238
  DM_REPLICATOR_SYNC,     /* Synchronous replication */
2239
  DM_REPLICATOR_ASYNC_WARN,   /* Warn if async replicator is slow */
2240
  DM_REPLICATOR_ASYNC_STALL,    /* Stall replicator if not fast enough */
2241
  DM_REPLICATOR_ASYNC_DROP,   /* Drop sites out of sync */
2242
  DM_REPLICATOR_ASYNC_FAIL,   /* Fail replicator if slow */
2243
  NUM_DM_REPLICATOR_MODES
2244
} dm_replicator_mode_t;
2245
2246
int dm_tree_node_add_replicator_target(struct dm_tree_node *node,
2247
               uint64_t size,
2248
               const char *rlog_uuid,
2249
               const char *rlog_type,
2250
               unsigned rsite_index,
2251
               dm_replicator_mode_t mode,
2252
               uint32_t async_timeout,
2253
               uint64_t fall_behind_data,
2254
               uint32_t fall_behind_ios);
2255
2256
int dm_tree_node_add_replicator_dev_target(struct dm_tree_node *node,
2257
             uint64_t size,
2258
             const char *replicator_uuid, /* Replicator control device */
2259
             uint64_t rdevice_index,
2260
             const char *rdev_uuid, /* Rimage device name/uuid */
2261
             unsigned rsite_index,
2262
             const char *slog_uuid,
2263
             uint32_t slog_flags,   /* Mirror log flags */
2264
             uint32_t slog_region_size);
2265
/* End of Replicator API */
2266
2267
/*
2268
 * FIXME: Defines below are based on kernel's dm-thin.c defines
2269
 * DATA_DEV_BLOCK_SIZE_MIN_SECTORS (64 * 1024 >> SECTOR_SHIFT)
2270
 * DATA_DEV_BLOCK_SIZE_MAX_SECTORS (1024 * 1024 * 1024 >> SECTOR_SHIFT)
2271
 */
2272
#define DM_THIN_MIN_DATA_BLOCK_SIZE (UINT32_C(128))
2273
#define DM_THIN_MAX_DATA_BLOCK_SIZE (UINT32_C(2097152))
2274
/*
2275
 * This does not match kernel THIN_METADATA_MAX_SECTORS (33292800 sectors).
2276
 * The correct formula is (UINT64_C(255) * ((1 << 14) - 64) * (4096 / (1 << 9)))
2277
 * but this older incorrect value (33161216) is used by crop_metadata logic
2278
 * (DEFAULT_THIN_POOL_MAX_METADATA_SIZE in defaults.h) and cannot be changed
2279
 * without breaking existing thin pool metadata cropping behavior.
2280
 */
2281
#define DM_THIN_MAX_METADATA_SIZE   (UINT64_C(255) * (1 << 14) * (4096 / (1 << 9)) - 256 * 1024)
2282
2283
int dm_tree_node_add_thin_pool_target(struct dm_tree_node *node,
2284
              uint64_t size,
2285
              uint64_t transaction_id,
2286
              const char *metadata_uuid,
2287
              const char *pool_uuid,
2288
              uint32_t data_block_size,
2289
              uint64_t low_water_mark,
2290
              unsigned skip_block_zeroing);
2291
2292
int dm_tree_node_add_thin_pool_target_v1(struct dm_tree_node *node,
2293
           uint64_t size,
2294
           uint64_t transaction_id,
2295
           const char *metadata_uuid,
2296
           const char *pool_uuid,
2297
           uint32_t data_block_size,
2298
           uint64_t low_water_mark,
2299
           unsigned skip_block_zeroing,
2300
           unsigned crop_metadata);
2301
2302
/* Supported messages for thin provision target */
2303
typedef enum dm_thin_message_e {
2304
  DM_THIN_MESSAGE_CREATE_SNAP,    /* device_id, origin_id */
2305
  DM_THIN_MESSAGE_CREATE_THIN,    /* device_id */
2306
  DM_THIN_MESSAGE_DELETE,     /* device_id */
2307
  DM_THIN_MESSAGE_SET_TRANSACTION_ID, /* current_id, new_id */
2308
  DM_THIN_MESSAGE_RESERVE_METADATA_SNAP,  /* target version >= 1.1 */
2309
  DM_THIN_MESSAGE_RELEASE_METADATA_SNAP,  /* target version >= 1.1 */
2310
} dm_thin_message_t;
2311
2312
int dm_tree_node_add_thin_pool_message(struct dm_tree_node *node,
2313
               dm_thin_message_t type,
2314
               uint64_t id1, uint64_t id2);
2315
2316
/*
2317
 * Set thin pool discard features
2318
 *   ignore      - Disable support for discards
2319
 *   no_passdown - Don't pass discards down to underlying data device,
2320
 *                 just remove the mapping
2321
 * Feature is available since version 1.1 of the thin target.
2322
 */
2323
int dm_tree_node_set_thin_pool_discard(struct dm_tree_node *node,
2324
               unsigned ignore,
2325
               unsigned no_passdown);
2326
/*
2327
 * Set error if no space, instead of queueing for thin pool.
2328
 */
2329
int dm_tree_node_set_thin_pool_error_if_no_space(struct dm_tree_node *node,
2330
             unsigned error_if_no_space);
2331
/* Start thin pool with metadata in read-only mode */
2332
int dm_tree_node_set_thin_pool_read_only(struct dm_tree_node *node,
2333
           unsigned read_only);
2334
/*
2335
 * Based on kernel's dm-thin.c MAX_DEV_ID ((1 << 24) - 1)
2336
 */
2337
#define DM_THIN_MAX_DEVICE_ID ((UINT32_C(1) << 24) - 1)
2338
int dm_tree_node_add_thin_target(struct dm_tree_node *node,
2339
         uint64_t size,
2340
         const char *pool_uuid,
2341
         uint32_t device_id);
2342
2343
int dm_tree_node_set_thin_external_origin(struct dm_tree_node *node,
2344
            const char *external_uuid);
2345
2346
void dm_tree_node_set_udev_flags(struct dm_tree_node *dnode, uint16_t udev_flags);
2347
2348
void dm_tree_node_set_presuspend_node(struct dm_tree_node *node,
2349
              struct dm_tree_node *presuspend_node);
2350
2351
int dm_tree_node_add_target_area(struct dm_tree_node *node,
2352
         const char *dev_name,
2353
         const char *uuid,
2354
         uint64_t offset);
2355
2356
/*
2357
 * Only for temporarily-missing raid devices where changes are tracked.
2358
 */
2359
int dm_tree_node_add_null_area(struct dm_tree_node *node, uint64_t offset);
2360
2361
/*
2362
 * Set readahead (in sectors) after loading the node.
2363
 */
2364
void dm_tree_node_set_read_ahead(struct dm_tree_node *dnode,
2365
         uint32_t read_ahead,
2366
         uint32_t read_ahead_flags);
2367
2368
/*
2369
 * Set node callback hook before de/activation.
2370
 * Callback is called before 'activation' of node for activation tree,
2371
 * or 'deactivation' of node for deactivation tree.
2372
 */
2373
typedef enum dm_node_callback_e {
2374
  DM_NODE_CALLBACK_PRELOADED,   /* Node has preload deps */
2375
  DM_NODE_CALLBACK_DEACTIVATED, /* Node is deactivated */
2376
} dm_node_callback_t;
2377
typedef int (*dm_node_callback_fn) (struct dm_tree_node *node,
2378
            dm_node_callback_t type, void *cb_data);
2379
void dm_tree_node_set_callback(struct dm_tree_node *dnode,
2380
             dm_node_callback_fn cb, void *cb_data);
2381
2382
void dm_tree_set_cookie(struct dm_tree_node *node, uint32_t cookie);
2383
uint32_t dm_tree_get_cookie(struct dm_tree_node *node);
2384
2385
/*****************************************************************************
2386
 * Library functions
2387
 *****************************************************************************/
2388
2389
/*******************
2390
 * Memory management
2391
 *******************/
2392
2393
/*
2394
 * Never use these functions directly - use the macros following instead.
2395
 */
2396
void *dm_malloc_wrapper(size_t s, const char *file, int line)
2397
  __attribute__((__malloc__)) __attribute__((__warn_unused_result__));
2398
void *dm_malloc_aligned_wrapper(size_t s, size_t a, const char *file, int line)
2399
  __attribute__((__malloc__)) __attribute__((__warn_unused_result__));
2400
void *dm_zalloc_wrapper(size_t s, const char *file, int line)
2401
  __attribute__((__malloc__)) __attribute__((__warn_unused_result__));
2402
void *dm_realloc_wrapper(void *p, unsigned int s, const char *file, int line)
2403
  __attribute__((__warn_unused_result__));
2404
void dm_free_wrapper(void *ptr);
2405
char *dm_strdup_wrapper(const char *str, const char *file, int line)
2406
  __attribute__((__warn_unused_result__));
2407
int dm_dump_memory_wrapper(void);
2408
void dm_bounds_check_wrapper(void);
2409
2410
0
#define dm_malloc(s) dm_malloc_wrapper((s), __FILE__, __LINE__)
2411
#define dm_malloc_aligned(s, a) dm_malloc_aligned_wrapper((s), (a),  __FILE__, __LINE__)
2412
1
#define dm_zalloc(s) dm_zalloc_wrapper((s), __FILE__, __LINE__)
2413
0
#define dm_strdup(s) dm_strdup_wrapper((s), __FILE__, __LINE__)
2414
0
#define dm_free(p) dm_free_wrapper(p)
2415
#define dm_realloc(p, s) dm_realloc_wrapper((p), (s), __FILE__, __LINE__)
2416
0
#define dm_dump_memory() dm_dump_memory_wrapper()
2417
0
#define dm_bounds_check() dm_bounds_check_wrapper()
2418
2419
/*
2420
 * The pool allocator is useful when you are going to allocate
2421
 * lots of memory, use the memory for a bit, and then free the
2422
 * memory in one go.  A surprising amount of code has this usage
2423
 * profile.
2424
 *
2425
 * You should think of the pool as an infinite, contiguous chunk
2426
 * of memory.  The front of this chunk of memory contains
2427
 * allocated objects, the second half is free.  dm_pool_alloc grabs
2428
 * the next 'size' bytes from the free half, in effect moving it
2429
 * into the allocated half.  This operation is very efficient.
2430
 *
2431
 * dm_pool_free frees the allocated object *and* all objects
2432
 * allocated after it.  It is important to note this semantic
2433
 * difference from malloc/free.  This is also extremely
2434
 * efficient, since a single dm_pool_free can dispose of a large
2435
 * complex object.
2436
 *
2437
 * dm_pool_destroy frees all allocated memory.
2438
 *
2439
 * eg, If you are building a binary tree in your program, and
2440
 * know that you are only ever going to insert into your tree,
2441
 * and not delete (eg, maintaining a symbol table for a
2442
 * compiler).  You can create yourself a pool, allocate the nodes
2443
 * from it, and when the tree becomes redundant call dm_pool_destroy
2444
 * (no nasty iterating through the tree to free nodes).
2445
 *
2446
 * eg, On the other hand if you wanted to repeatedly insert and
2447
 * remove objects into the tree, you would be better off
2448
 * allocating the nodes from a free list; you cannot free a
2449
 * single arbitrary node with pool.
2450
 */
2451
2452
struct dm_pool;
2453
2454
/* constructor and destructor */
2455
struct dm_pool *dm_pool_create(const char *name, size_t chunk_hint)
2456
  __attribute__((__warn_unused_result__));
2457
void dm_pool_destroy(struct dm_pool *p);
2458
2459
/* simple allocation/free routines */
2460
void *dm_pool_alloc(struct dm_pool *p, size_t s)
2461
  __attribute__((__warn_unused_result__));
2462
void *dm_pool_alloc_aligned(struct dm_pool *p, size_t s, unsigned alignment)
2463
  __attribute__((__warn_unused_result__));
2464
void dm_pool_empty(struct dm_pool *p);
2465
void dm_pool_free(struct dm_pool *p, void *ptr);
2466
2467
/*
2468
 * To aid debugging, a pool can be locked. Any modifications made
2469
 * to the content of the pool while it is locked can be detected.
2470
 * Default compilation is using a crc checksum to notice modifications.
2471
 * The pool locking is using the mprotect with the compilation flag
2472
 * DEBUG_ENFORCE_POOL_LOCKING to enforce the memory protection.
2473
 */
2474
/* query pool lock status */
2475
int dm_pool_locked(struct dm_pool *p);
2476
/* mark pool as locked */
2477
int dm_pool_lock(struct dm_pool *p, int crc)
2478
  __attribute__((__warn_unused_result__));
2479
/* mark pool as unlocked */
2480
int dm_pool_unlock(struct dm_pool *p, int crc)
2481
  __attribute__((__warn_unused_result__));
2482
2483
/*
2484
 * Object building routines:
2485
 *
2486
 * These allow you to 'grow' an object, useful for
2487
 * building strings, or filling in dynamic
2488
 * arrays.
2489
 *
2490
 * It's probably best explained with an example:
2491
 *
2492
 * char *build_string(struct dm_pool *mem)
2493
 * {
2494
 *      int i;
2495
 *      char buffer[16];
2496
 *
2497
 *      if (!dm_pool_begin_object(mem, 128))
2498
 *              return NULL;
2499
 *
2500
 *      for (i = 0; i < 50; i++) {
2501
 *              snprintf(buffer, sizeof(buffer), "%d, ", i);
2502
 *              if (!dm_pool_grow_object(mem, buffer, 0))
2503
 *                      goto bad;
2504
 *      }
2505
 *
2506
 *  // add null
2507
 *      if (!dm_pool_grow_object(mem, "\0", 1))
2508
 *              goto bad;
2509
 *
2510
 *      return dm_pool_end_object(mem);
2511
 *
2512
 * bad:
2513
 *
2514
 *      dm_pool_abandon_object(mem);
2515
 *      return NULL;
2516
 *}
2517
 *
2518
 * So start an object by calling dm_pool_begin_object
2519
 * with a guess at the final object size - if in
2520
 * doubt make the guess too small.
2521
 *
2522
 * Then append chunks of data to your object with
2523
 * dm_pool_grow_object.  Finally get your object with
2524
 * a call to dm_pool_end_object.
2525
 *
2526
 * Setting delta to 0 means it will use strlen(extra).
2527
 */
2528
int dm_pool_begin_object(struct dm_pool *p, size_t hint);
2529
int dm_pool_grow_object(struct dm_pool *p, const void *extra, size_t delta);
2530
void *dm_pool_end_object(struct dm_pool *p);
2531
void dm_pool_abandon_object(struct dm_pool *p);
2532
2533
/* utilities */
2534
char *dm_pool_strdup(struct dm_pool *p, const char *str)
2535
  __attribute__((__warn_unused_result__));
2536
char *dm_pool_strndup(struct dm_pool *p, const char *str, size_t n)
2537
  __attribute__((__warn_unused_result__));
2538
void *dm_pool_zalloc(struct dm_pool *p, size_t s)
2539
  __attribute__((__warn_unused_result__));
2540
2541
/******************
2542
 * bitset functions
2543
 ******************/
2544
2545
typedef uint32_t *dm_bitset_t;
2546
2547
dm_bitset_t dm_bitset_create(struct dm_pool *mem, unsigned num_bits);
2548
void dm_bitset_destroy(dm_bitset_t bs);
2549
2550
int dm_bitset_equal(dm_bitset_t in1, dm_bitset_t in2);
2551
2552
void dm_bit_and(dm_bitset_t out, dm_bitset_t in1, dm_bitset_t in2);
2553
void dm_bit_union(dm_bitset_t out, dm_bitset_t in1, dm_bitset_t in2);
2554
int dm_bit_get_first(dm_bitset_t bs);
2555
int dm_bit_get_next(dm_bitset_t bs, int last_bit);
2556
int dm_bit_get_last(dm_bitset_t bs);
2557
int dm_bit_get_prev(dm_bitset_t bs, int last_bit);
2558
2559
0
#define DM_BITS_PER_INT ((unsigned)sizeof(int) * CHAR_BIT)
2560
2561
#define dm_bit(bs, i) \
2562
0
   ((bs)[((i) / DM_BITS_PER_INT) + 1] & (0x1U << ((i) & (DM_BITS_PER_INT - 1))))
2563
2564
#define dm_bit_set(bs, i) \
2565
0
   ((bs)[((i) / DM_BITS_PER_INT) + 1] |= (0x1U << ((i) & (DM_BITS_PER_INT - 1))))
2566
2567
#define dm_bit_clear(bs, i) \
2568
   ((bs)[((i) / DM_BITS_PER_INT) + 1] &= ~(0x1U << ((i) & (DM_BITS_PER_INT - 1))))
2569
2570
#define dm_bit_set_all(bs) \
2571
   memset((bs) + 1, -1, ((*(bs) / DM_BITS_PER_INT) + 1) * sizeof(int))
2572
2573
#define dm_bit_clear_all(bs) \
2574
   memset((bs) + 1, 0, ((*(bs) / DM_BITS_PER_INT) + 1) * sizeof(int))
2575
2576
#define dm_bit_copy(bs1, bs2) \
2577
   memcpy((bs1) + 1, (bs2) + 1, ((*(bs2) / DM_BITS_PER_INT) + 1) * sizeof(int))
2578
2579
/*
2580
 * Parse a string representation of a bitset into a dm_bitset_t. The
2581
 * notation used is identical to the kernel bitmap parser (cpuset etc.)
2582
 * and supports both lists ("1,2,3") and ranges ("1-2,5-8"). If the mem
2583
 * parameter is NULL memory for the bitset will be allocated using
2584
 * dm_malloc(). Otherwise the bitset will be allocated using the supplied
2585
 * dm_pool.
2586
 */
2587
dm_bitset_t dm_bitset_parse_list(const char *str, struct dm_pool *mem,
2588
         size_t min_num_bits);
2589
2590
/* Returns number of set bits */
2591
static inline unsigned hweight32(uint32_t i)
2592
0
{
2593
0
  unsigned r = (i & 0x55555555) + ((i >> 1) & 0x55555555);
2594
0
2595
0
  r =    (r & 0x33333333) + ((r >>  2) & 0x33333333);
2596
0
  r =    (r & 0x0F0F0F0F) + ((r >>  4) & 0x0F0F0F0F);
2597
0
  r =    (r & 0x00FF00FF) + ((r >>  8) & 0x00FF00FF);
2598
0
  return (r & 0x0000FFFF) + ((r >> 16) & 0x0000FFFF);
2599
0
}
Unexecuted instantiation: libdm-common.c:hweight32
Unexecuted instantiation: libdm-file.c:hweight32
Unexecuted instantiation: libdm-string.c:hweight32
Unexecuted instantiation: dbg_malloc.c:hweight32
Unexecuted instantiation: pool.c:hweight32
Unexecuted instantiation: libdm-iface.c:hweight32
Unexecuted instantiation: bitset.c:hweight32
Unexecuted instantiation: list.c:hweight32
Unexecuted instantiation: libdm-timestamp.c:hweight32
2600
2601
/****************
2602
 * hash functions
2603
 ****************/
2604
2605
struct dm_hash_table;
2606
struct dm_hash_node;
2607
2608
typedef void (*dm_hash_iterate_fn) (void *data);
2609
2610
struct dm_hash_table *dm_hash_create(unsigned size_hint)
2611
  __attribute__((__warn_unused_result__));
2612
void dm_hash_destroy(struct dm_hash_table *t);
2613
void dm_hash_wipe(struct dm_hash_table *t);
2614
2615
void *dm_hash_lookup(struct dm_hash_table *t, const char *key);
2616
int dm_hash_insert(struct dm_hash_table *t, const char *key, void *data);
2617
void dm_hash_remove(struct dm_hash_table *t, const char *key);
2618
2619
void *dm_hash_lookup_binary(struct dm_hash_table *t, const void *key, uint32_t len);
2620
int dm_hash_insert_binary(struct dm_hash_table *t, const void *key, uint32_t len,
2621
        void *data);
2622
void dm_hash_remove_binary(struct dm_hash_table *t, const void *key, uint32_t len);
2623
2624
unsigned dm_hash_get_num_entries(struct dm_hash_table *t);
2625
void dm_hash_iter(struct dm_hash_table *t, dm_hash_iterate_fn f);
2626
2627
char *dm_hash_get_key(struct dm_hash_table *t, struct dm_hash_node *n);
2628
void *dm_hash_get_data(struct dm_hash_table *t, struct dm_hash_node *n);
2629
struct dm_hash_node *dm_hash_get_first(struct dm_hash_table *t);
2630
struct dm_hash_node *dm_hash_get_next(struct dm_hash_table *t, struct dm_hash_node *n);
2631
2632
/*
2633
 * dm_hash_insert() replaces the value of an existing
2634
 * entry with a matching key if one exists.  Otherwise
2635
 * it adds a new entry.
2636
 *
2637
 * dm_hash_insert_with_val() inserts a new entry if
2638
 * another entry with the same key already exists.
2639
 * val_len is the size of the data being inserted.
2640
 *
2641
 * If two entries with the same key exist,
2642
 * (added using dm_hash_insert_allow_multiple), then:
2643
 * . dm_hash_lookup() returns the first one it finds, and
2644
 *   dm_hash_lookup_with_val() returns the one with a matching
2645
 *   val_len/val.
2646
 * . dm_hash_remove() removes the first one it finds, and
2647
 *   dm_hash_remove_with_val() removes the one with a matching
2648
 *   val_len/val.
2649
 *
2650
 * If a single entry with a given key exists, and it has
2651
 * zero val_len, then:
2652
 * . dm_hash_lookup() returns it
2653
 * . dm_hash_lookup_with_val(val_len=0) returns it
2654
 * . dm_hash_remove() removes it
2655
 * . dm_hash_remove_with_val(val_len=0) removes it
2656
 *
2657
 * dm_hash_lookup_with_count() is a single call that will
2658
 * both lookup a key's value and check if there is more
2659
 * than one entry with the given key.
2660
 *
2661
 * (It is not meant to retrieve all the entries with the
2662
 * given key.  In the common case where a single entry exists
2663
 * for the key, it is useful to have a single call that will
2664
 * both look up the value and indicate if multiple values
2665
 * exist for the key.)
2666
 *
2667
 * dm_hash_lookup_with_count:
2668
 * . If no entries exist, the function returns NULL, and
2669
 *   the count is set to 0.
2670
 * . If only one entry exists, the value of that entry is
2671
 *   returned and count is set to 1.
2672
 * . If N entries exists, the value of the first entry is
2673
 *   returned and count is set to N.
2674
 */
2675
2676
void *dm_hash_lookup_with_val(struct dm_hash_table *t, const char *key,
2677
            const void *val, uint32_t val_len);
2678
void dm_hash_remove_with_val(struct dm_hash_table *t, const char *key,
2679
           const void *val, uint32_t val_len);
2680
int dm_hash_insert_allow_multiple(struct dm_hash_table *t, const char *key,
2681
          const void *val, uint32_t val_len);
2682
void *dm_hash_lookup_with_count(struct dm_hash_table *t, const char *key, int *count);
2683
2684
2685
#define dm_hash_iterate(v, h) \
2686
  for (v = dm_hash_get_first((h)); v; \
2687
       v = dm_hash_get_next((h), v))
2688
2689
/****************
2690
 * list functions
2691
 ****************/
2692
2693
/*
2694
 * A list consists of a list head plus elements.
2695
 * Each element has 'next' and 'previous' pointers.
2696
 * The list head's pointers point to the first and the last element.
2697
 */
2698
2699
struct dm_list {
2700
  struct dm_list *n, *p;
2701
};
2702
2703
/*
2704
 * String list.
2705
 */
2706
struct dm_str_list {
2707
  struct dm_list list;
2708
  const char *str;
2709
};
2710
2711
/*
2712
 * Active device element returned dm_task_get_device_list()
2713
 * Only for accessing structure members.
2714
 * Do NOT allocate this structure locally.
2715
 * More elements can be added later (with DM_DEVICE_LIST_HAS_FLAG).
2716
 */
2717
struct dm_active_device {
2718
  struct dm_list list;
2719
  dev_t devno;
2720
  const char *name; /* device name */
2721
2722
  uint32_t event_nr;  /* valid when DM_DEVICE_LIST_HAS_EVENT_NR is set */
2723
  const char *uuid; /* valid uuid when DM_DEVICE_LIST_HAS_UUID is set */
2724
};
2725
2726
/*
2727
 * Initialise a list before use.
2728
 * The list head's next and previous pointers point back to itself.
2729
 */
2730
#define DM_LIST_HEAD_INIT(name)  { &(name), &(name) }
2731
#define DM_LIST_INIT(name)  struct dm_list name = DM_LIST_HEAD_INIT(name)
2732
void dm_list_init(struct dm_list *head);
2733
2734
/*
2735
 * Insert an element before 'head'.
2736
 * If 'head' is the list head, this adds an element to the end of the list.
2737
 */
2738
void dm_list_add(struct dm_list *head, struct dm_list *elem);
2739
2740
/*
2741
 * Insert an element after 'head'.
2742
 * If 'head' is the list head, this adds an element to the front of the list.
2743
 */
2744
void dm_list_add_h(struct dm_list *head, struct dm_list *elem);
2745
2746
/*
2747
 * Delete an element from its list.
2748
 * Note that this doesn't change the element itself - it may still be safe
2749
 * to follow its pointers.
2750
 */
2751
void dm_list_del(struct dm_list *elem);
2752
2753
/*
2754
 * Remove an element from existing list and insert before 'head'.
2755
 */
2756
void dm_list_move(struct dm_list *head, struct dm_list *elem);
2757
2758
/*
2759
 * Join 'head1' to the end of 'head'.
2760
 */
2761
void dm_list_splice(struct dm_list *head, struct dm_list *head1);
2762
2763
/*
2764
 * Is the list empty?
2765
 */
2766
int dm_list_empty(const struct dm_list *head);
2767
2768
/*
2769
 * Is this the first element of the list?
2770
 */
2771
int dm_list_start(const struct dm_list *head, const struct dm_list *elem);
2772
2773
/*
2774
 * Is this the last element of the list?
2775
 */
2776
int dm_list_end(const struct dm_list *head, const struct dm_list *elem);
2777
2778
/*
2779
 * Return first element of the list or NULL if empty
2780
 */
2781
struct dm_list *dm_list_first(const struct dm_list *head);
2782
2783
/*
2784
 * Return last element of the list or NULL if empty
2785
 */
2786
struct dm_list *dm_list_last(const struct dm_list *head);
2787
2788
/*
2789
 * Return the previous element of the list, or NULL if we've reached the start.
2790
 */
2791
struct dm_list *dm_list_prev(const struct dm_list *head, const struct dm_list *elem);
2792
2793
/*
2794
 * Return the next element of the list, or NULL if we've reached the end.
2795
 */
2796
struct dm_list *dm_list_next(const struct dm_list *head, const struct dm_list *elem);
2797
2798
/*
2799
 * Given the address v of an instance of 'struct dm_list' called 'head'
2800
 * contained in a structure of type t, return the containing structure.
2801
 */
2802
#define dm_list_struct_base(v, t, head) \
2803
0
    ((t *)((char *)(v) - offsetof(t, head)))
2804
2805
/*
2806
 * Given the address v of an instance of 'struct dm_list list' contained in
2807
 * a structure of type t, return the containing structure.
2808
 */
2809
0
#define dm_list_item(v, t) dm_list_struct_base((v), t, list)
2810
2811
/*
2812
 * Given the address v of one known element e in a known structure of type t,
2813
 * return another element f.
2814
 */
2815
#define dm_struct_field(v, t, e, f) \
2816
    (((t *)((uintptr_t)(v) - offsetof(t, e)))->f)
2817
2818
/*
2819
 * Given the address v of a known element e in a known structure of type t,
2820
 * return the list head 'list'
2821
 */
2822
#define dm_list_head(v, t, e) dm_struct_field(v, t, e, list)
2823
2824
/*
2825
 * Set v to each element of a list in turn.
2826
 */
2827
#define dm_list_iterate(v, head) \
2828
0
  for (v = (head)->n; v != head; v = v->n)
2829
2830
/*
2831
 * Set v to each element in a list in turn, starting from the element
2832
 * in front of 'start'.
2833
 * You can use this to 'unwind' a list_iterate and back out actions on
2834
 * already-processed elements.
2835
 * If 'start' is 'head' it walks the list backwards.
2836
 */
2837
#define dm_list_uniterate(v, head, start) \
2838
  for (v = (start)->p; v != head; v = v->p)
2839
2840
/*
2841
 * A safe way to walk a list and delete and free some elements along
2842
 * the way.
2843
 * t must be defined as a temporary variable of the same type as v.
2844
 */
2845
#define dm_list_iterate_safe(v, t, head) \
2846
1.72k
  for (v = (head)->n, t = v->n; v != head; v = t, t = v->n)
2847
2848
/*
2849
 * Walk a list, setting 'v' in turn to the containing structure of each item.
2850
 * The containing structure should be the same type as 'v'.
2851
 * The 'struct dm_list' variable within the containing structure is 'field'.
2852
 */
2853
#define dm_list_iterate_items_gen(v, head, field) \
2854
0
  for (v = dm_list_struct_base((head)->n, __typeof__(*v), field); \
2855
0
       &v->field != (head); \
2856
0
       v = dm_list_struct_base(v->field.n, __typeof__(*v), field))
2857
2858
/*
2859
 * Walk a list, setting 'v' in turn to the containing structure of each item.
2860
 * The containing structure should be the same type as 'v'.
2861
 * The list should be 'struct dm_list list' within the containing structure.
2862
 */
2863
0
#define dm_list_iterate_items(v, head) dm_list_iterate_items_gen(v, (head), list)
2864
2865
/*
2866
 * Walk a list, setting 'v' in turn to the containing structure of each item.
2867
 * The containing structure should be the same type as 'v'.
2868
 * The 'struct dm_list' variable within the containing structure is 'field'.
2869
 * t must be defined as a temporary variable of the same type as v.
2870
 */
2871
#define dm_list_iterate_items_gen_safe(v, t, head, field) \
2872
  for (v = dm_list_struct_base((head)->n, __typeof__(*v), field), \
2873
       t = dm_list_struct_base(v->field.n, __typeof__(*v), field); \
2874
       &v->field != (head); \
2875
       v = t, t = dm_list_struct_base(v->field.n, __typeof__(*v), field))
2876
/*
2877
 * Walk a list, setting 'v' in turn to the containing structure of each item.
2878
 * The containing structure should be the same type as 'v'.
2879
 * The list should be 'struct dm_list list' within the containing structure.
2880
 * t must be defined as a temporary variable of the same type as v.
2881
 */
2882
#define dm_list_iterate_items_safe(v, t, head) \
2883
  dm_list_iterate_items_gen_safe(v, t, (head), list)
2884
2885
/*
2886
 * Walk a list backwards, setting 'v' in turn to the containing structure
2887
 * of each item.
2888
 * The containing structure should be the same type as 'v'.
2889
 * The 'struct dm_list' variable within the containing structure is 'field'.
2890
 */
2891
#define dm_list_iterate_back_items_gen(v, head, field) \
2892
  for (v = dm_list_struct_base((head)->p, __typeof__(*v), field); \
2893
       &v->field != (head); \
2894
       v = dm_list_struct_base(v->field.p, __typeof__(*v), field))
2895
2896
/*
2897
 * Walk a list backwards, setting 'v' in turn to the containing structure
2898
 * of each item.
2899
 * The containing structure should be the same type as 'v'.
2900
 * The list should be 'struct dm_list list' within the containing structure.
2901
 */
2902
#define dm_list_iterate_back_items(v, head) dm_list_iterate_back_items_gen(v, (head), list)
2903
2904
/*
2905
 * Return the number of elements in a list by walking it.
2906
 */
2907
unsigned int dm_list_size(const struct dm_list *head);
2908
2909
/*
2910
 * Retrieve the list of devices and put them into easily accessible
2911
 * struct dm_active_device list elements.
2912
 * devs_features provides flag-set with used features so it's easy to check
2913
 * whether the kernel provides i.e. UUID info together with DM names
2914
 */
2915
0
#define DM_DEVICE_LIST_HAS_EVENT_NR 1
2916
0
#define DM_DEVICE_LIST_HAS_UUID   2
2917
int dm_task_get_device_list(struct dm_task *dmt, struct dm_list **devs_list,
2918
          unsigned *devs_features);
2919
/* Release all associated memory with list of active DM devices */
2920
void dm_device_list_destroy(struct dm_list **devs_list);
2921
/*
2922
 * Compare two dm_list structures containing dm_active_device elements.
2923
 * Returns 1 if both lists contain identical devices (same devno and uuid in same order),
2924
 * 0 if lists differ.
2925
 */
2926
int dm_device_list_equal(const struct dm_list *list1, const struct dm_list *list2);
2927
2928
/*********
2929
 * selinux
2930
 *********/
2931
2932
/*
2933
 * Obtain SELinux security context assigned for the path and set this
2934
 * context for creating a new file system object. This security context
2935
 * is global and it is used until reset to default policy behaviour
2936
 * by calling 'dm_prepare_selinux_context(NULL, 0)'.
2937
 */
2938
int dm_prepare_selinux_context(const char *path, mode_t mode);
2939
/*
2940
 * Set SELinux context for existing file system object.
2941
 */
2942
int dm_set_selinux_context(const char *path, mode_t mode);
2943
2944
/*********************
2945
 * string manipulation
2946
 *********************/
2947
2948
/*
2949
 * Break up the name of a mapped device into its constituent
2950
 * Volume Group, Logical Volume and Layer (if present).
2951
 * If mem is supplied, the result is allocated from the mempool.
2952
 * Otherwise the strings are changed in situ.
2953
 */
2954
int dm_split_lvm_name(struct dm_pool *mem, const char *dmname,
2955
          char **vgname, char **lvname, char **layer);
2956
2957
/*
2958
 * Destructively split buffer into NULL-separated words in argv.
2959
 * Returns number of words.
2960
 */
2961
int dm_split_words(char *buffer, unsigned max,
2962
       unsigned ignore_comments, /* Not implemented */
2963
       char **argv);
2964
2965
/*
2966
 * Returns -1 if buffer too small
2967
 */
2968
int dm_snprintf(char *buf, size_t bufsize, const char *format, ...)
2969
    __attribute__ ((format(printf, 3, 4)));
2970
2971
/*
2972
 * Returns pointer to the last component of the path.
2973
 */
2974
const char *dm_basename(const char *path);
2975
2976
/*
2977
 * Returns number of occurrences of 'c' in 'str' of length 'size'.
2978
 */
2979
unsigned dm_count_chars(const char *str, size_t len, const int c);
2980
2981
/*
2982
 * Length of string after escaping double quotes and backslashes.
2983
 */
2984
size_t dm_escaped_len(const char *str);
2985
2986
/*
2987
 * <vg>-<lv>-<layer> or if !layer just <vg>-<lv>.
2988
 */
2989
char *dm_build_dm_name(struct dm_pool *mem, const char *vgname,
2990
           const char *lvname, const char *layer);
2991
char *dm_build_dm_uuid(struct dm_pool *mem, const char *uuid_prefix, const char *lvid, const char *layer);
2992
2993
/*
2994
 * Copies a string, quoting double quotes with backslashes.
2995
 */
2996
char *dm_escape_double_quotes(char *out, const char *src);
2997
2998
/*
2999
 * Undo quoting in situ.
3000
 */
3001
void dm_unescape_double_quotes(char *src);
3002
3003
/*
3004
 * Unescape colons and "at" signs in situ and save the substrings
3005
 * starting at the position of the first unescaped colon and the
3006
 * first unescaped "at" sign. This is normally used to unescape
3007
 * device names used as PVs.
3008
 */
3009
void dm_unescape_colons_and_at_signs(char *src,
3010
             char **substr_first_unquoted_colon,
3011
             char **substr_first_unquoted_at_sign);
3012
3013
/*
3014
 * Replacement for strncpy() function.
3015
 *
3016
 * Copies no more than n bytes from string pointed by src to the buffer
3017
 * pointed by dest and ensure string is finished with '\0'.
3018
 * Returns 0 if the whole string does not fit.
3019
 */
3020
int dm_strncpy(char *dest, const char *src, size_t n);
3021
3022
/*
3023
 * Recognize unit specifier in the 'units' arg and return a factor
3024
 * representing that unit. If the 'units' contains a prefix with digits,
3025
 * the 'units' is considered to be a custom unit.
3026
 *
3027
 * Also, set 'unit_type' output arg to the character that represents
3028
 * the unit specified. The 'unit_type' character equals to the unit
3029
 * character itself recognized in the 'units' arg for canonical units.
3030
 * Otherwise, the 'unit_type' character is set to 'U' for custom unit.
3031
 *
3032
 * An example for k/K canonical units and 8k/8K custom units:
3033
 *
3034
 *   units  unit_type  return value (factor)
3035
 *   k      k          1024
3036
 *   K      K          1000
3037
 *   8k     U          1024*8
3038
 *   8K     U          1000*8
3039
 *   etc...
3040
 *
3041
 * Recognized units:
3042
 *
3043
 *   h/H - human readable (returns 1 for both)
3044
 *   b/B - byte (returns 1 for both)
3045
 *   s/S - sector (returns 512 for both)
3046
 *   k/K - kilo (returns 1024/1000 respectively)
3047
 *   m/M - mega (returns 1024^2/1000^2 respectively)
3048
 *   g/G - giga (returns 1024^3/1000^3 respectively)
3049
 *   t/T - tera (returns 1024^4/1000^4 respectively)
3050
 *   p/P - peta (returns 1024^5/1000^5 respectively)
3051
 *   e/E - exa (returns 1024^6/1000^6 respectively)
3052
 *
3053
 * Only one units character is allowed in the 'units' arg
3054
 * if strict mode is enabled by 'strict' arg.
3055
 *
3056
 * The 'endptr' output arg, if not NULL, saves the pointer
3057
 * in the 'units' string which follows the unit specifier
3058
 * recognized (IOW the position where the parsing of the
3059
 * unit specifier stopped).
3060
 *
3061
 * Returns the unit factor or 0 if no unit is recognized.
3062
 */
3063
uint64_t dm_units_to_factor(const char *units, char *unit_type,
3064
          int strict, const char **endptr);
3065
3066
/*
3067
 * Type of unit specifier used by dm_size_to_string().
3068
 */
3069
typedef enum dm_size_suffix_e {
3070
  DM_SIZE_LONG = 0, /* Megabyte */
3071
  DM_SIZE_SHORT = 1,  /* MB or MiB */
3072
  DM_SIZE_UNIT = 2  /* M or m */
3073
} dm_size_suffix_t;
3074
3075
/*
3076
 * Convert a size (in 512-byte sectors) into a printable string using units of unit_type.
3077
 * An upper-case unit_type indicates output units based on powers of 1000 are
3078
 * required; a lower-case unit_type indicates powers of 1024.
3079
 * For correct operation, unit_factor must be one of:
3080
 *  0 - the correct value will be calculated internally;
3081
 *   or the output from dm_units_to_factor() corresponding to unit_type;
3082
 *   or 'u' or 'U', an arbitrary number of bytes to use as the power base.
3083
 * Set include_suffix to 1 to include a suffix of suffix_type.
3084
 * Set use_si_units to 0 for suffixes that don't distinguish between 1000 and 1024.
3085
 * Set use_si_units to 1 for a suffix that does distinguish.
3086
 */
3087
const char *dm_size_to_string(struct dm_pool *mem, uint64_t size,
3088
            char unit_type, int use_si_units,
3089
            uint64_t unit_factor, int include_suffix,
3090
            dm_size_suffix_t suffix_type);
3091
3092
/**************************
3093
 * file/stream manipulation
3094
 **************************/
3095
3096
/*
3097
 * Create a directory (with parent directories if necessary).
3098
 * Returns 1 on success, 0 on failure.
3099
 */
3100
int dm_create_dir(const char *dir);
3101
3102
int dm_is_empty_dir(const char *dir);
3103
3104
/*
3105
 * Close a stream, with nicer error checking than fclose's.
3106
 * Derived from gnulib's close-stream.c.
3107
 *
3108
 * Close "stream".  Return 0 if successful, and EOF (setting errno)
3109
 * otherwise.  Upon failure, set errno to 0 if the error number
3110
 * cannot be determined.  Useful mainly for writable streams.
3111
 */
3112
int dm_fclose(FILE *stream);
3113
3114
/*
3115
 * Returns size of a buffer which is allocated with dm_malloc.
3116
 * Pointer to the buffer is stored in *buf.
3117
 * Returns -1 on failure leaving buf undefined.
3118
 */
3119
int dm_asprintf(char **result, const char *format, ...)
3120
    __attribute__ ((format(printf, 2, 3)));
3121
int dm_vasprintf(char **result, const char *format, va_list aq)
3122
    __attribute__ ((format(printf, 2, 0)));
3123
3124
/*
3125
 * create lockfile (pidfile) - create and lock a lock file
3126
 * @lockfile: location of lock file
3127
 *
3128
 * Returns: 1 on success, 0 otherwise, errno is handled internally
3129
 */
3130
int dm_create_lockfile(const char* lockfile);
3131
3132
/*
3133
 * Query whether a daemon is running based on its lockfile
3134
 *
3135
 * Returns: 1 if running, 0 if not
3136
 */
3137
int dm_daemon_is_running(const char* lockfile);
3138
3139
/*********************
3140
 * regular expressions
3141
 *********************/
3142
struct dm_regex;
3143
3144
/*
3145
 * Initialise an array of num patterns for matching.
3146
 * Uses memory from mem.
3147
 */
3148
struct dm_regex *dm_regex_create(struct dm_pool *mem, const char * const *patterns,
3149
         unsigned num_patterns);
3150
3151
/*
3152
 * Match string s against the patterns.
3153
 * Returns the index of the highest pattern in the array that matches,
3154
 * or -1 if none match.
3155
 */
3156
int dm_regex_match(struct dm_regex *regex, const char *s);
3157
3158
/*
3159
 * This is useful for regression testing only.  The idea is if two
3160
 * fingerprints are different, then the two dfas are certainly not
3161
 * isomorphic.  If two fingerprints _are_ the same then it's very likely
3162
 * that the dfas are isomorphic.
3163
 *
3164
 * This function must be called before any matching is done.
3165
 */
3166
uint32_t dm_regex_fingerprint(struct dm_regex *regex);
3167
3168
/******************
3169
 * percent handling
3170
 ******************/
3171
/*
3172
 * A fixed-point representation of percent values. One percent equals to
3173
 * DM_PERCENT_1 as defined below. Values that are not multiples of DM_PERCENT_1
3174
 * represent fractions, with precision of 1/1000000 of a percent. See
3175
 * dm_percent_to_float for a conversion to a floating-point representation.
3176
 *
3177
 * You should always use dm_make_percent when building dm_percent_t values. The
3178
 * implementation of dm_make_percent is biased towards the middle: it ensures that
3179
 * the result is DM_PERCENT_0 or DM_PERCENT_100 if and only if this is the actual
3180
 * value -- it never rounds any intermediate value (> 0 or < 100) to either 0
3181
 * or 100.
3182
*/
3183
#define DM_PERCENT_CHAR '%'
3184
3185
typedef enum dm_percent_range_e {
3186
  DM_PERCENT_0 = 0,
3187
  DM_PERCENT_1 = 1000000,
3188
  DM_PERCENT_100 = 100 * DM_PERCENT_1,
3189
  DM_PERCENT_INVALID = -1,
3190
  DM_PERCENT_FAILED = -2
3191
} dm_percent_range_t;
3192
3193
typedef int32_t dm_percent_t;
3194
3195
float dm_percent_to_float(dm_percent_t percent);
3196
/*
3197
 * Return adjusted/rounded float for better percent value printing.
3198
 * Function ensures for given precision of digits:
3199
 * 100.0% returns only when the value is DM_PERCENT_100
3200
 *        for close smaller values rounds to nearest smaller value
3201
 * 0.0% returns only for value DM_PERCENT_0
3202
 *        for close bigger values rounds to nearest bigger value
3203
 * In all other cases returns same value as dm_percent_to_float()
3204
 */
3205
float dm_percent_to_round_float(dm_percent_t percent, unsigned digits);
3206
dm_percent_t dm_make_percent(uint64_t numerator, uint64_t denominator);
3207
3208
/********************
3209
 * timestamp handling
3210
 ********************/
3211
3212
/*
3213
 * Create a dm_timestamp object to use with dm_timestamp_get.
3214
 */
3215
struct dm_timestamp *dm_timestamp_alloc(void);
3216
3217
/*
3218
 * Update dm_timestamp object to represent the current time.
3219
 */
3220
int dm_timestamp_get(struct dm_timestamp *ts);
3221
3222
/*
3223
 * Copy a timestamp from ts_old to ts_new.
3224
 */
3225
void dm_timestamp_copy(struct dm_timestamp *ts_new, struct dm_timestamp *ts_old);
3226
3227
/*
3228
 * Compare two timestamps.
3229
 *
3230
 * Return: -1 if ts1 is less than ts2
3231
 *        0 if ts1 is equal to ts2
3232
 *          1 if ts1 is greater than ts2
3233
 */
3234
int dm_timestamp_compare(struct dm_timestamp *ts1, struct dm_timestamp *ts2);
3235
3236
/*
3237
 * Return the absolute difference in nanoseconds between
3238
 * the dm_timestamp objects ts1 and ts2.
3239
 *
3240
 * Callers that need to know whether ts1 is before, equal to, or after ts2
3241
 * in addition to the magnitude should use dm_timestamp_compare.
3242
 */
3243
uint64_t dm_timestamp_delta(struct dm_timestamp *ts1, struct dm_timestamp *ts2);
3244
3245
/*
3246
 * Destroy a dm_timestamp object.
3247
 */
3248
void dm_timestamp_destroy(struct dm_timestamp *ts);
3249
3250
/*********************
3251
 * reporting functions
3252
 *********************/
3253
3254
struct dm_report_object_type {
3255
  uint32_t id;      /* Powers of 2 */
3256
  const char *desc;
3257
  const char *prefix;   /* field id string prefix (optional) */
3258
  /* FIXME: convert to proper usage of const pointers here */
3259
  void *(*data_fn)(void *object); /* callback from report_object() */
3260
};
3261
3262
struct dm_report_field;
3263
3264
/*
3265
 * dm_report_field_type flags
3266
 */
3267
#define DM_REPORT_FIELD_MASK        0x00000FFF
3268
#define DM_REPORT_FIELD_ALIGN_MASK      0x0000000F
3269
#define DM_REPORT_FIELD_ALIGN_LEFT      0x00000001
3270
#define DM_REPORT_FIELD_ALIGN_RIGHT     0x00000002
3271
#define DM_REPORT_FIELD_TYPE_MASK     0x00000FF0
3272
#define DM_REPORT_FIELD_TYPE_NONE     0x00000000
3273
#define DM_REPORT_FIELD_TYPE_STRING     0x00000010
3274
#define DM_REPORT_FIELD_TYPE_NUMBER     0x00000020
3275
#define DM_REPORT_FIELD_TYPE_SIZE     0x00000040
3276
#define DM_REPORT_FIELD_TYPE_PERCENT      0x00000080
3277
#define DM_REPORT_FIELD_TYPE_STRING_LIST    0x00000100
3278
#define DM_REPORT_FIELD_TYPE_TIME     0x00000200
3279
3280
/* For use with reserved values only! */
3281
#define DM_REPORT_FIELD_RESERVED_VALUE_MASK   0x0000000F
3282
#define DM_REPORT_FIELD_RESERVED_VALUE_NAMED    0x00000001 /* only named value, less strict form of reservation */
3283
#define DM_REPORT_FIELD_RESERVED_VALUE_RANGE    0x00000002 /* value is range - low and high value defined */
3284
#define DM_REPORT_FIELD_RESERVED_VALUE_DYNAMIC_VALUE  0x00000004 /* value is computed in runtime */
3285
#define DM_REPORT_FIELD_RESERVED_VALUE_FUZZY_NAMES  0x00000008 /* value names are recognized in runtime */
3286
3287
#define DM_REPORT_FIELD_TYPE_ID_LEN 32
3288
#define DM_REPORT_FIELD_TYPE_HEADING_LEN 32
3289
3290
struct dm_report;
3291
struct dm_report_field_type {
3292
  uint32_t type;    /* object type id */
3293
  uint32_t flags;   /* DM_REPORT_FIELD_* */
3294
  uint32_t offset;  /* byte offset in the object */
3295
  int32_t width;    /* default width */
3296
  /* string used to specify the field */
3297
  const char id[DM_REPORT_FIELD_TYPE_ID_LEN];
3298
  /* string printed in header */
3299
  const char heading[DM_REPORT_FIELD_TYPE_HEADING_LEN];
3300
  int (*report_fn)(struct dm_report *rh, struct dm_pool *mem,
3301
       struct dm_report_field *field, const void *data,
3302
       void *private_data);
3303
  const char *desc; /* description of the field */
3304
};
3305
3306
/*
3307
 * Per-field reserved value.
3308
 */
3309
struct dm_report_field_reserved_value {
3310
  /* field_num is the position of the field in 'fields'
3311
     array passed to dm_report_init_with_selection */
3312
  uint32_t field_num;
3313
  /* the value is of the same type as the field
3314
     identified by field_num */
3315
  const void *value;
3316
};
3317
3318
/*
3319
 * Reserved value is a 'value' that is used directly if any of the 'names' is hit
3320
 * or in case of fuzzy names, if such fuzzy name matches.
3321
 *
3322
 * If type is any of DM_REPORT_FIELD_TYPE_*, the reserved value is recognized
3323
 * for all fields of that type.
3324
 *
3325
 * If type is DM_REPORT_FIELD_TYPE_NONE, the reserved value is recognized
3326
 * for the exact field specified - hence the type of the value is automatically
3327
 * the same as the type of the field itself.
3328
 *
3329
 * The array of reserved values is used to initialize reporting with
3330
 * selection enabled (see also dm_report_init_with_selection function).
3331
 */
3332
struct dm_report_reserved_value {
3333
  const uint32_t type;    /* DM_REPORT_FIELD_RESERVED_VALUE_* and DM_REPORT_FIELD_TYPE_*  */
3334
  const void *value;    /* reserved value:
3335
            uint64_t for DM_REPORT_FIELD_TYPE_NUMBER
3336
            uint64_t for DM_REPORT_FIELD_TYPE_SIZE (number of 512-byte sectors)
3337
            uint64_t for DM_REPORT_FIELD_TYPE_PERCENT
3338
            const char* for DM_REPORT_FIELD_TYPE_STRING
3339
            struct dm_report_field_reserved_value for DM_REPORT_FIELD_TYPE_NONE
3340
            dm_report_reserved_handler* if DM_REPORT_FIELD_RESERVED_VALUE_{DYNAMIC_VALUE,FUZZY_NAMES} is used */
3341
  const char **names;   /* null-terminated array of static names for this reserved value */
3342
  const char *description;  /* description of the reserved value */
3343
};
3344
3345
/*
3346
 * Available actions for dm_report_reserved_value_handler.
3347
 */
3348
typedef enum dm_report_reserved_action_e {
3349
  DM_REPORT_RESERVED_PARSE_FUZZY_NAME,
3350
  DM_REPORT_RESERVED_GET_DYNAMIC_VALUE,
3351
} dm_report_reserved_action_t;
3352
3353
/*
3354
 * Generic reserved value handler to process reserved value names and/or values.
3355
 *
3356
 * Actions and their input/output:
3357
 *
3358
 *  DM_REPORT_RESERVED_PARSE_FUZZY_NAME
3359
 *    data_in:  const char *fuzzy_name
3360
 *    data_out: const char *canonical_name, NULL if fuzzy_name not recognized
3361
 *
3362
 *  DM_REPORT_RESERVED_GET_DYNAMIC_VALUE
3363
 *    data_in:  const char *canonical_name
3364
 *    data_out: void *value, NULL if canonical_name not recognized
3365
 *
3366
 * All actions return:
3367
 *
3368
 *  -1 if action not implemented
3369
 *  0 on error
3370
 *  1 on success
3371
 */
3372
typedef int (*dm_report_reserved_handler) (struct dm_report *rh,
3373
             struct dm_pool *mem,
3374
             uint32_t field_num,
3375
             dm_report_reserved_action_t action,
3376
             const void *data_in,
3377
             const void **data_out);
3378
3379
/*
3380
 * The dm_report_value_cache_{set,get} are helper functions to store and retrieve
3381
 * various values used during reporting (dm_report_field_type.report_fn) and/or
3382
 * selection processing (dm_report_reserved_handler instances) to avoid
3383
 * recalculation of these values or to share values among calls.
3384
 */
3385
int dm_report_value_cache_set(struct dm_report *rh, const char *name, const void *data);
3386
const void *dm_report_value_cache_get(struct dm_report *rh, const char *name);
3387
/*
3388
 * dm_report_init output_flags
3389
 */
3390
#define DM_REPORT_OUTPUT_MASK     0x000000FF
3391
#define DM_REPORT_OUTPUT_ALIGNED    0x00000001
3392
#define DM_REPORT_OUTPUT_BUFFERED   0x00000002
3393
#define DM_REPORT_OUTPUT_HEADINGS   0x00000004
3394
#define DM_REPORT_OUTPUT_FIELD_NAME_PREFIX  0x00000008
3395
#define DM_REPORT_OUTPUT_FIELD_UNQUOTED   0x00000010
3396
#define DM_REPORT_OUTPUT_COLUMNS_AS_ROWS  0x00000020
3397
#define DM_REPORT_OUTPUT_MULTIPLE_TIMES   0x00000040
3398
#define DM_REPORT_OUTPUT_FIELD_IDS_IN_HEADINGS  0x00000080
3399
3400
struct dm_report *dm_report_init(uint32_t *report_types,
3401
         const struct dm_report_object_type *types,
3402
         const struct dm_report_field_type *fields,
3403
         const char *output_fields,
3404
         const char *output_separator,
3405
         uint32_t output_flags,
3406
         const char *sort_keys,
3407
         void *private_data);
3408
struct dm_report *dm_report_init_with_selection(uint32_t *report_types,
3409
            const struct dm_report_object_type *types,
3410
            const struct dm_report_field_type *fields,
3411
            const char *output_fields,
3412
            const char *output_separator,
3413
            uint32_t output_flags,
3414
            const char *sort_keys,
3415
            const char *selection,
3416
            const struct dm_report_reserved_value reserved_values[],
3417
            void *private_data);
3418
/*
3419
 * Report an object, pass it through the selection criteria if they
3420
 * are present and display the result on output if it passes the criteria.
3421
 */
3422
int dm_report_object(struct dm_report *rh, void *object);
3423
/*
3424
 * The same as dm_report_object, but display the result on output only if
3425
 * 'do_output' arg is set. Also, save the result of selection in 'selected'
3426
 * arg if it's not NULL (either 1 if the object passes, otherwise 0).
3427
 */
3428
int dm_report_object_is_selected(struct dm_report *rh, void *object, int do_output, int *selected);
3429
3430
/*
3431
 * Compact report output so that if field value is empty for all rows in
3432
 * the report, drop the field from output completely (including headers).
3433
 * Compact output is applicable only if report is buffered, otherwise
3434
 * this function has no effect.
3435
 */
3436
int dm_report_compact_fields(struct dm_report *rh);
3437
3438
/*
3439
 * The same as dm_report_compact_fields, but for selected fields only.
3440
 * The "fields" arg is comma separated list of field names (the same format
3441
 * as used for "output_fields" arg in dm_report_init fn).
3442
 */
3443
int dm_report_compact_given_fields(struct dm_report *rh, const char *fields);
3444
3445
/*
3446
 * Returns 1 if there is no data waiting to be output.
3447
 */
3448
int dm_report_is_empty(struct dm_report *rh);
3449
3450
/*
3451
 * Destroy report content without doing output.
3452
 */
3453
void dm_report_destroy_rows(struct dm_report *rh);
3454
3455
int dm_report_output(struct dm_report *rh);
3456
3457
/*
3458
 * Output the report headings for a columns-based report, even if they
3459
 * have already been shown. Useful for repeating reports that wish to
3460
 * issue a periodic reminder of the column headings.
3461
 */
3462
int dm_report_column_headings(struct dm_report *rh);
3463
3464
void dm_report_free(struct dm_report *rh);
3465
3466
/*
3467
 * Prefix added to each field name with DM_REPORT_OUTPUT_FIELD_NAME_PREFIX
3468
 */
3469
int dm_report_set_output_field_name_prefix(struct dm_report *rh,
3470
             const char *output_field_name_prefix);
3471
3472
int dm_report_set_selection(struct dm_report *rh, const char *selection);
3473
3474
/*
3475
 * Report functions are provided for simple data types.
3476
 * They take care of allocating copies of the data.
3477
 */
3478
int dm_report_field_string(struct dm_report *rh, struct dm_report_field *field,
3479
         const char *const *data);
3480
int dm_report_field_string_list(struct dm_report *rh, struct dm_report_field *field,
3481
        const struct dm_list *data, const char *delimiter);
3482
int dm_report_field_string_list_unsorted(struct dm_report *rh, struct dm_report_field *field,
3483
           const struct dm_list *data, const char *delimiter);
3484
int dm_report_field_int32(struct dm_report *rh, struct dm_report_field *field,
3485
        const int32_t *data);
3486
int dm_report_field_uint32(struct dm_report *rh, struct dm_report_field *field,
3487
         const uint32_t *data);
3488
int dm_report_field_int(struct dm_report *rh, struct dm_report_field *field,
3489
      const int *data);
3490
int dm_report_field_uint64(struct dm_report *rh, struct dm_report_field *field,
3491
         const uint64_t *data);
3492
int dm_report_field_percent(struct dm_report *rh, struct dm_report_field *field,
3493
          const dm_percent_t *data);
3494
3495
/*
3496
 * For custom fields, allocate the data in 'mem' and use
3497
 * dm_report_field_set_value().
3498
 * 'sortvalue' may be NULL if it matches 'value'
3499
 */
3500
void dm_report_field_set_value(struct dm_report_field *field, const void *value,
3501
             const void *sortvalue);
3502
3503
/*
3504
 * Report group support.
3505
 */
3506
struct dm_report_group;
3507
3508
typedef enum dm_report_group_type_e {
3509
  DM_REPORT_GROUP_SINGLE,
3510
  DM_REPORT_GROUP_BASIC,
3511
  DM_REPORT_GROUP_JSON,
3512
  DM_REPORT_GROUP_JSON_STD
3513
} dm_report_group_type_t;
3514
3515
struct dm_report_group *dm_report_group_create(dm_report_group_type_t type, void *data);
3516
int dm_report_group_push(struct dm_report_group *group, struct dm_report *report, void *data);
3517
int dm_report_group_pop(struct dm_report_group *group);
3518
int dm_report_group_output_and_pop_all(struct dm_report_group *group);
3519
int dm_report_group_destroy(struct dm_report_group *group);
3520
3521
/*
3522
 * Stats counter access methods
3523
 *
3524
 * Each method returns the corresponding stats counter value from the
3525
 * supplied dm_stats handle for the specified region_id and area_id.
3526
 * If either region_id or area_id uses one of the special values
3527
 * DM_STATS_REGION_CURRENT or DM_STATS_AREA_CURRENT then the region
3528
 * or area is selected according to the current state of the dm_stats
3529
 * handle's embedded cursor.
3530
 *
3531
 * Two methods are provided to access counter values: a named function
3532
 * for each available counter field and a single function that accepts
3533
 * an enum value specifying the required field. New code is encouraged
3534
 * to use the enum based interface as calls to the named functions are
3535
 * implemented using the enum method internally.
3536
 *
3537
 * See the kernel documentation for complete descriptions of each
3538
 * counter field:
3539
 *
3540
 * Documentation/device-mapper/statistics.txt
3541
 * Documentation/iostats.txt
3542
 *
3543
 * reads: the number of reads completed
3544
 * reads_merged: the number of reads merged
3545
 * read_sectors: the number of sectors read
3546
 * read_nsecs: the number of nanoseconds spent reading
3547
 * writes: the number of writes completed
3548
 * writes_merged: the number of writes merged
3549
 * write_sectors: the number of sectors written
3550
 * write_nsecs: the number of nanoseconds spent writing
3551
 * io_in_progress: the number of I/Os currently in progress
3552
 * io_nsecs: the number of nanoseconds spent doing I/Os
3553
 * weighted_io_nsecs: the weighted number of nanoseconds spent doing I/Os
3554
 * total_read_nsecs: the total time spent reading in nanoseconds
3555
 * total_write_nsecs: the total time spent writing in nanoseconds
3556
 */
3557
3558
#define DM_STATS_REGION_CURRENT UINT64_MAX
3559
#define DM_STATS_AREA_CURRENT UINT64_MAX
3560
3561
typedef enum dm_stats_counter_e {
3562
  DM_STATS_READS_COUNT,
3563
  DM_STATS_READS_MERGED_COUNT,
3564
  DM_STATS_READ_SECTORS_COUNT,
3565
  DM_STATS_READ_NSECS,
3566
  DM_STATS_WRITES_COUNT,
3567
  DM_STATS_WRITES_MERGED_COUNT,
3568
  DM_STATS_WRITE_SECTORS_COUNT,
3569
  DM_STATS_WRITE_NSECS,
3570
  DM_STATS_IO_IN_PROGRESS_COUNT,
3571
  DM_STATS_IO_NSECS,
3572
  DM_STATS_WEIGHTED_IO_NSECS,
3573
  DM_STATS_TOTAL_READ_NSECS,
3574
  DM_STATS_TOTAL_WRITE_NSECS,
3575
  DM_STATS_NR_COUNTERS
3576
} dm_stats_counter_t;
3577
3578
uint64_t dm_stats_get_counter(const struct dm_stats *dms,
3579
            dm_stats_counter_t counter,
3580
            uint64_t region_id, uint64_t area_id);
3581
3582
uint64_t dm_stats_get_reads(const struct dm_stats *dms,
3583
          uint64_t region_id, uint64_t area_id);
3584
3585
uint64_t dm_stats_get_reads_merged(const struct dm_stats *dms,
3586
           uint64_t region_id, uint64_t area_id);
3587
3588
uint64_t dm_stats_get_read_sectors(const struct dm_stats *dms,
3589
           uint64_t region_id, uint64_t area_id);
3590
3591
uint64_t dm_stats_get_read_nsecs(const struct dm_stats *dms,
3592
         uint64_t region_id, uint64_t area_id);
3593
3594
uint64_t dm_stats_get_writes(const struct dm_stats *dms,
3595
           uint64_t region_id, uint64_t area_id);
3596
3597
uint64_t dm_stats_get_writes_merged(const struct dm_stats *dms,
3598
            uint64_t region_id, uint64_t area_id);
3599
3600
uint64_t dm_stats_get_write_sectors(const struct dm_stats *dms,
3601
            uint64_t region_id, uint64_t area_id);
3602
3603
uint64_t dm_stats_get_write_nsecs(const struct dm_stats *dms,
3604
          uint64_t region_id, uint64_t area_id);
3605
3606
uint64_t dm_stats_get_io_in_progress(const struct dm_stats *dms,
3607
             uint64_t region_id, uint64_t area_id);
3608
3609
uint64_t dm_stats_get_io_nsecs(const struct dm_stats *dms,
3610
             uint64_t region_id, uint64_t area_id);
3611
3612
uint64_t dm_stats_get_weighted_io_nsecs(const struct dm_stats *dms,
3613
          uint64_t region_id, uint64_t area_id);
3614
3615
uint64_t dm_stats_get_total_read_nsecs(const struct dm_stats *dms,
3616
               uint64_t region_id, uint64_t area_id);
3617
3618
uint64_t dm_stats_get_total_write_nsecs(const struct dm_stats *dms,
3619
          uint64_t region_id, uint64_t area_id);
3620
3621
/*
3622
 * Derived statistics access methods
3623
 *
3624
 * Each method returns the corresponding value calculated from the
3625
 * counters stored in the supplied dm_stats handle for the specified
3626
 * region_id and area_id. If either region_id or area_id uses one of the
3627
 * special values DM_STATS_REGION_CURRENT or DM_STATS_AREA_CURRENT then
3628
 * the region or area is selected according to the current state of the
3629
 * dm_stats handle's embedded cursor.
3630
 *
3631
 * The set of metrics is based on the fields provided by the Linux
3632
 * iostats program.
3633
 *
3634
 * rd_merges_per_sec: the number of reads merged per second
3635
 * wr_merges_per_sec: the number of writes merged per second
3636
 * reads_per_sec: the number of reads completed per second
3637
 * writes_per_sec: the number of writes completed per second
3638
 * read_sectors_per_sec: the number of sectors read per second
3639
 * write_sectors_per_sec: the number of sectors written per second
3640
 * average_request_size: the average size of requests submitted
3641
 * service_time: the average service time (in ns) for requests issued
3642
 * average_queue_size: the average queue length
3643
 * average_wait_time: the average time for requests to be served (in ns)
3644
 * average_rd_wait_time: the average read wait time
3645
 * average_wr_wait_time: the average write wait time
3646
 */
3647
3648
typedef enum dm_stats_metric_e {
3649
  DM_STATS_RD_MERGES_PER_SEC,
3650
  DM_STATS_WR_MERGES_PER_SEC,
3651
  DM_STATS_READS_PER_SEC,
3652
  DM_STATS_WRITES_PER_SEC,
3653
  DM_STATS_READ_SECTORS_PER_SEC,
3654
  DM_STATS_WRITE_SECTORS_PER_SEC,
3655
  DM_STATS_AVERAGE_REQUEST_SIZE,
3656
  DM_STATS_AVERAGE_QUEUE_SIZE,
3657
  DM_STATS_AVERAGE_WAIT_TIME,
3658
  DM_STATS_AVERAGE_RD_WAIT_TIME,
3659
  DM_STATS_AVERAGE_WR_WAIT_TIME,
3660
  DM_STATS_SERVICE_TIME,
3661
  DM_STATS_THROUGHPUT,
3662
  DM_STATS_UTILIZATION,
3663
  DM_STATS_NR_METRICS
3664
} dm_stats_metric_t;
3665
3666
int dm_stats_get_metric(const struct dm_stats *dms, int metric,
3667
      uint64_t region_id, uint64_t area_id, double *value);
3668
3669
int dm_stats_get_rd_merges_per_sec(const struct dm_stats *dms, double *rrqm,
3670
           uint64_t region_id, uint64_t area_id);
3671
3672
int dm_stats_get_wr_merges_per_sec(const struct dm_stats *dms, double *wrqm,
3673
           uint64_t region_id, uint64_t area_id);
3674
3675
int dm_stats_get_reads_per_sec(const struct dm_stats *dms, double *rd_s,
3676
             uint64_t region_id, uint64_t area_id);
3677
3678
int dm_stats_get_writes_per_sec(const struct dm_stats *dms, double *wr_s,
3679
        uint64_t region_id, uint64_t area_id);
3680
3681
int dm_stats_get_read_sectors_per_sec(const struct dm_stats *dms,
3682
              double *rsec_s, uint64_t region_id,
3683
              uint64_t area_id);
3684
3685
int dm_stats_get_write_sectors_per_sec(const struct dm_stats *dms,
3686
               double *wsec_s, uint64_t region_id,
3687
               uint64_t area_id);
3688
3689
int dm_stats_get_average_request_size(const struct dm_stats *dms,
3690
              double *arqsz, uint64_t region_id,
3691
              uint64_t area_id);
3692
3693
int dm_stats_get_service_time(const struct dm_stats *dms, double *svctm,
3694
            uint64_t region_id, uint64_t area_id);
3695
3696
int dm_stats_get_average_queue_size(const struct dm_stats *dms, double *qusz,
3697
            uint64_t region_id, uint64_t area_id);
3698
3699
int dm_stats_get_average_wait_time(const struct dm_stats *dms, double *await,
3700
           uint64_t region_id, uint64_t area_id);
3701
3702
int dm_stats_get_average_rd_wait_time(const struct dm_stats *dms,
3703
              double *await, uint64_t region_id,
3704
              uint64_t area_id);
3705
3706
int dm_stats_get_average_wr_wait_time(const struct dm_stats *dms,
3707
              double *await, uint64_t region_id,
3708
              uint64_t area_id);
3709
3710
int dm_stats_get_throughput(const struct dm_stats *dms, double *tput,
3711
          uint64_t region_id, uint64_t area_id);
3712
3713
int dm_stats_get_utilization(const struct dm_stats *dms, dm_percent_t *util,
3714
           uint64_t region_id, uint64_t area_id);
3715
3716
/*
3717
 * Statistics histogram access methods.
3718
 *
3719
 * Methods to access latency histograms for regions that have them
3720
 * enabled. Each histogram contains a configurable number of bins
3721
 * spanning a user defined latency interval.
3722
 *
3723
 * The bin count, upper and lower bin bounds, and bin values are
3724
 * made available via the following area methods.
3725
 *
3726
 * Methods to obtain a simple string representation of the histogram
3727
 * and its bounds are also provided.
3728
 */
3729
3730
/*
3731
 * Retrieve a pointer to the histogram associated with the specified
3732
 * area. If the area does not have a histogram configured this function
3733
 * returns NULL.
3734
 *
3735
 * The pointer does not need to be freed explicitly by the caller: it
3736
 * will become invalid following a subsequent dm_stats_list(),
3737
 * dm_stats_populate() or dm_stats_destroy() of the corresponding
3738
 * dm_stats handle.
3739
 *
3740
 * If region_id or area_id is one of the special values
3741
 * DM_STATS_REGION_CURRENT or DM_STATS_AREA_CURRENT the current cursor
3742
 * value is used to select the region or area.
3743
 */
3744
struct dm_histogram *dm_stats_get_histogram(const struct dm_stats *dms,
3745
              uint64_t region_id,
3746
              uint64_t area_id);
3747
3748
/*
3749
 * Return the number of bins in the specified histogram handle.
3750
 */
3751
int dm_histogram_get_nr_bins(const struct dm_histogram *dmh);
3752
3753
/*
3754
 * Get the lower bound of the specified bin of the histogram for the
3755
 * area specified by region_id and area_id. The value is returned in
3756
 * nanoseconds.
3757
 */
3758
uint64_t dm_histogram_get_bin_lower(const struct dm_histogram *dmh, int bin);
3759
3760
/*
3761
 * Get the upper bound of the specified bin of the histogram for the
3762
 * area specified by region_id and area_id. The value is returned in
3763
 * nanoseconds.
3764
 */
3765
uint64_t dm_histogram_get_bin_upper(const struct dm_histogram *dmh, int bin);
3766
3767
/*
3768
 * Get the width of the specified bin of the histogram for the area
3769
 * specified by region_id and area_id. The width is equal to the bin
3770
 * upper bound minus the lower bound and yields the range of latency
3771
 * values covered by this bin. The value is returned in nanoseconds.
3772
 */
3773
uint64_t dm_histogram_get_bin_width(const struct dm_histogram *dmh, int bin);
3774
3775
/*
3776
 * Get the value of the specified bin of the histogram for the area
3777
 * specified by region_id and area_id.
3778
 */
3779
uint64_t dm_histogram_get_bin_count(const struct dm_histogram *dmh, int bin);
3780
3781
/*
3782
 * Get the percentage (relative frequency) of the specified bin of the
3783
 * histogram for the area specified by region_id and area_id.
3784
 */
3785
dm_percent_t dm_histogram_get_bin_percent(const struct dm_histogram *dmh,
3786
            int bin);
3787
3788
/*
3789
 * Return the total observations (sum of bin counts) for the histogram
3790
 * of the area specified by region_id and area_id.
3791
 */
3792
uint64_t dm_histogram_get_sum(const struct dm_histogram *dmh);
3793
3794
/*
3795
 * Histogram formatting flags.
3796
 */
3797
#define DM_HISTOGRAM_SUFFIX  0x1
3798
#define DM_HISTOGRAM_VALUES  0x2
3799
#define DM_HISTOGRAM_PERCENT 0X4
3800
#define DM_HISTOGRAM_BOUNDS_LOWER 0x10
3801
#define DM_HISTOGRAM_BOUNDS_UPPER 0x20
3802
#define DM_HISTOGRAM_BOUNDS_RANGE 0x30
3803
3804
/*
3805
 * Return a string representation of the supplied histogram's values and
3806
 * bin boundaries.
3807
 *
3808
 * The bin argument selects the bin to format. If this argument is less
3809
 * than zero all bins will be included in the resulting string.
3810
 *
3811
 * width specifies a minimum width for the field in characters; if it is
3812
 * zero the width will be determined automatically based on the options
3813
 * selected for formatting. A value less than zero disables field width
3814
 * control: bin boundaries and values will be output with a minimum
3815
 * amount of whitespace.
3816
 *
3817
 * flags is a collection of flag arguments that control the string format:
3818
 *
3819
 * DM_HISTOGRAM_VALUES  - Include bin values in the string.
3820
 * DM_HISTOGRAM_SUFFIX  - Include time unit suffixes when printing bounds.
3821
 * DM_HISTOGRAM_PERCENT - Format bin values as a percentage.
3822
 *
3823
 * DM_HISTOGRAM_BOUNDS_LOWER - Include the lower bound of each bin.
3824
 * DM_HISTOGRAM_BOUNDS_UPPER - Include the upper bound of each bin.
3825
 * DM_HISTOGRAM_BOUNDS_RANGE - Show the span of each bin as "lo-up".
3826
 *
3827
 * The returned pointer does not need to be freed explicitly by the
3828
 * caller: it will become invalid following a subsequent
3829
 * dm_stats_list(), dm_stats_populate() or dm_stats_destroy() of the
3830
 * corresponding dm_stats handle.
3831
 */
3832
const char *dm_histogram_to_string(const struct dm_histogram *dmh, int bin,
3833
           int width, int flags);
3834
3835
/*************************
3836
 * config file parse/print
3837
 *************************/
3838
typedef enum dm_config_value_type_e {
3839
  DM_CFG_INT,
3840
  DM_CFG_FLOAT,
3841
  DM_CFG_STRING,
3842
  DM_CFG_EMPTY_ARRAY
3843
} dm_config_value_type_t;
3844
3845
struct dm_config_value {
3846
  dm_config_value_type_t type;
3847
3848
  union dm_config_value_u {
3849
    int64_t i;
3850
    float f;
3851
    double d;         /* Unused. */
3852
    const char *str;
3853
  } v;
3854
3855
  struct dm_config_value *next; /* For arrays */
3856
  uint32_t format_flags;
3857
};
3858
3859
struct dm_config_node {
3860
  const char *key;
3861
  struct dm_config_node *parent, *sib, *child;
3862
  struct dm_config_value *v;
3863
  int id;
3864
};
3865
3866
struct dm_config_tree {
3867
  struct dm_config_node *root;
3868
  struct dm_config_tree *cascade;
3869
  struct dm_pool *mem;
3870
  void *custom;
3871
};
3872
3873
struct dm_config_tree *dm_config_create(void);
3874
struct dm_config_tree *dm_config_from_string(const char *config_settings);
3875
int dm_config_parse(struct dm_config_tree *cft, const char *start, const char *end);
3876
int dm_config_parse_without_dup_node_check(struct dm_config_tree *cft, const char *start, const char *end);
3877
int dm_config_parse_only_section(struct dm_config_tree *cft, const char *start, const char *end, const char *section);
3878
3879
void *dm_config_get_custom(struct dm_config_tree *cft);
3880
void dm_config_set_custom(struct dm_config_tree *cft, void *custom);
3881
3882
/*
3883
 * When searching, first_cft is checked before second_cft.
3884
 */
3885
struct dm_config_tree *dm_config_insert_cascaded_tree(struct dm_config_tree *first_cft, struct dm_config_tree *second_cft);
3886
3887
/*
3888
 * If there's a cascaded dm_config_tree, remove the top layer
3889
 * and return the layer below.  Otherwise return NULL.
3890
 */
3891
struct dm_config_tree *dm_config_remove_cascaded_tree(struct dm_config_tree *cft);
3892
3893
/*
3894
 * Create a new, uncascaded config tree equivalent to the input cascade.
3895
 */
3896
struct dm_config_tree *dm_config_flatten(struct dm_config_tree *cft);
3897
3898
void dm_config_destroy(struct dm_config_tree *cft);
3899
3900
/* Simple output line by line. */
3901
typedef int (*dm_putline_fn)(const char *line, void *baton);
3902
/* More advanced output with config node reference. */
3903
typedef int (*dm_config_node_out_fn)(const struct dm_config_node *cn, const char *line, void *baton);
3904
3905
/*
3906
 * Specification for advanced config node output.
3907
 */
3908
struct dm_config_node_out_spec {
3909
  dm_config_node_out_fn prefix_fn; /* called before processing config node lines */
3910
  dm_config_node_out_fn line_fn; /* called for each config node line */
3911
  dm_config_node_out_fn suffix_fn; /* called after processing config node lines */
3912
};
3913
3914
/* Write the node and any subsequent siblings it has. */
3915
int dm_config_write_node(const struct dm_config_node *cn, dm_putline_fn putline, void *baton);
3916
int dm_config_write_node_out(const struct dm_config_node *cn, const struct dm_config_node_out_spec *out_spec, void *baton);
3917
3918
/* Write given node only without subsequent siblings. */
3919
int dm_config_write_one_node(const struct dm_config_node *cn, dm_putline_fn putline, void *baton);
3920
int dm_config_write_one_node_out(const struct dm_config_node *cn, const struct dm_config_node_out_spec *out_spec, void *baton);
3921
3922
struct dm_config_node *dm_config_find_node(const struct dm_config_node *cn, const char *path);
3923
int dm_config_has_node(const struct dm_config_node *cn, const char *path);
3924
int dm_config_remove_node(struct dm_config_node *parent, struct dm_config_node *rem_node);
3925
const char *dm_config_find_str(const struct dm_config_node *cn, const char *path, const char *fail);
3926
const char *dm_config_find_str_allow_empty(const struct dm_config_node *cn, const char *path, const char *fail);
3927
int dm_config_find_int(const struct dm_config_node *cn, const char *path, int fail);
3928
int64_t dm_config_find_int64(const struct dm_config_node *cn, const char *path, int64_t fail);
3929
float dm_config_find_float(const struct dm_config_node *cn, const char *path, float fail);
3930
3931
const struct dm_config_node *dm_config_tree_find_node(const struct dm_config_tree *cft, const char *path);
3932
const char *dm_config_tree_find_str(const struct dm_config_tree *cft, const char *path, const char *fail);
3933
const char *dm_config_tree_find_str_allow_empty(const struct dm_config_tree *cft, const char *path, const char *fail);
3934
int dm_config_tree_find_int(const struct dm_config_tree *cft, const char *path, int fail);
3935
int64_t dm_config_tree_find_int64(const struct dm_config_tree *cft, const char *path, int64_t fail);
3936
float dm_config_tree_find_float(const struct dm_config_tree *cft, const char *path, float fail);
3937
int dm_config_tree_find_bool(const struct dm_config_tree *cft, const char *path, int fail);
3938
3939
/*
3940
 * Understands (0, ~0), (y, n), (yes, no), (on,
3941
 * off), (true, false).
3942
 */
3943
int dm_config_find_bool(const struct dm_config_node *cn, const char *path, int fail);
3944
int dm_config_value_is_bool(const struct dm_config_value *v);
3945
3946
int dm_config_get_uint32(const struct dm_config_node *cn, const char *path, uint32_t *result);
3947
int dm_config_get_uint64(const struct dm_config_node *cn, const char *path, uint64_t *result);
3948
int dm_config_get_str(const struct dm_config_node *cn, const char *path, const char **result);
3949
int dm_config_get_list(const struct dm_config_node *cn, const char *path, const struct dm_config_value **result);
3950
int dm_config_get_section(const struct dm_config_node *cn, const char *path, const struct dm_config_node **result);
3951
3952
unsigned dm_config_maybe_section(const char *str, unsigned len);
3953
3954
const char *dm_config_parent_name(const struct dm_config_node *n);
3955
3956
struct dm_config_node *dm_config_clone_node_with_mem(struct dm_pool *mem, const struct dm_config_node *cn, int siblings);
3957
struct dm_config_node *dm_config_create_node(struct dm_config_tree *cft, const char *key);
3958
struct dm_config_value *dm_config_create_value(struct dm_config_tree *cft);
3959
struct dm_config_node *dm_config_clone_node(struct dm_config_tree *cft, const struct dm_config_node *cn, int siblings);
3960
3961
/*
3962
 * Common formatting flags applicable to all config node types (lower 16 bits).
3963
 */
3964
#define DM_CONFIG_VALUE_FMT_COMMON_ARRAY             0x00000001 /* value is array */
3965
#define DM_CONFIG_VALUE_FMT_COMMON_EXTRA_SPACES      0x00000002 /* add spaces in "key = value" pairs in contrast to "key=value" for better readability */
3966
3967
/*
3968
 * Type-related config node formatting flags (higher 16 bits).
3969
 */
3970
/* int-related formatting flags */
3971
#define DM_CONFIG_VALUE_FMT_INT_OCTAL                0x00010000 /* print number in octal form */
3972
3973
/* string-related formatting flags */
3974
#define DM_CONFIG_VALUE_FMT_STRING_NO_QUOTES         0x00010000 /* do not print quotes around string value */
3975
3976
void dm_config_value_set_format_flags(struct dm_config_value *cv, uint32_t format_flags);
3977
uint32_t dm_config_value_get_format_flags(struct dm_config_value *cv);
3978
3979
struct dm_pool *dm_config_memory(struct dm_config_tree *cft);
3980
3981
/* Udev device directory. */
3982
#define DM_UDEV_DEV_DIR "/dev/"
3983
3984
/* Cookie prefixes.
3985
 *
3986
 * The cookie value consists of a prefix (16 bits) and a base (16 bits).
3987
 * We can use the prefix to store the flags. These flags are sent to
3988
 * kernel within given dm task. When returned back to userspace in
3989
 * DM_COOKIE udev environment variable, we can control several aspects
3990
 * of udev rules we use by decoding the cookie prefix. When doing the
3991
 * notification, we replace the cookie prefix with DM_COOKIE_MAGIC,
3992
 * so we notify the right semaphore.
3993
 *
3994
 * It is still possible to use cookies for passing the flags to udev
3995
 * rules even when udev_sync is disabled. The base part of the cookie
3996
 * will be zero (there's no notification semaphore) and prefix will be
3997
 * set then. However, having udev_sync enabled is highly recommended.
3998
 */
3999
0
#define DM_COOKIE_MAGIC 0x0D4D
4000
0
#define DM_UDEV_FLAGS_MASK 0xFFFF0000
4001
0
#define DM_UDEV_FLAGS_SHIFT 16
4002
4003
/*
4004
 * DM_UDEV_DISABLE_DM_RULES_FLAG is set in case we need to disable
4005
 * basic device-mapper udev rules that create symlinks in /dev/<DM_DIR>
4006
 * directory. However, we can't reliably prevent creating default
4007
 * nodes by udev (commonly /dev/dm-X, where X is a number).
4008
 */
4009
0
#define DM_UDEV_DISABLE_DM_RULES_FLAG 0x0001
4010
/*
4011
 * DM_UDEV_DISABLE_SUBSYSTEM_RULES_FLAG is set in case we need to disable
4012
 * subsystem udev rules, but still we need the general DM udev rules to
4013
 * be applied (to create the nodes and symlinks under /dev and /dev/disk).
4014
 */
4015
0
#define DM_UDEV_DISABLE_SUBSYSTEM_RULES_FLAG 0x0002
4016
/*
4017
 * DM_UDEV_DISABLE_DISK_RULES_FLAG is set in case we need to disable
4018
 * general DM rules that set symlinks in /dev/disk directory.
4019
 */
4020
#define DM_UDEV_DISABLE_DISK_RULES_FLAG 0x0004
4021
/*
4022
 * DM_UDEV_DISABLE_OTHER_RULES_FLAG is set in case we need to disable
4023
 * all the other rules that are not general device-mapper nor subsystem
4024
 * related (the rules belong to other software or packages). All foreign
4025
 * rules should check this flag directly and they should ignore further
4026
 * rule processing for such event.
4027
 */
4028
#define DM_UDEV_DISABLE_OTHER_RULES_FLAG 0x0008
4029
/*
4030
 * DM_UDEV_LOW_PRIORITY_FLAG is set in case we need to instruct the
4031
 * udev rules to give low priority to the device that is currently
4032
 * processed. For example, this provides a way to select which symlinks
4033
 * could be overwritten by high priority ones if their names are equal.
4034
 * Common situation is a name based on FS UUID while using origin and
4035
 * snapshot devices.
4036
 */
4037
#define DM_UDEV_LOW_PRIORITY_FLAG 0x0010
4038
/*
4039
 * DM_UDEV_DISABLE_LIBRARY_FALLBACK is set in case we need to disable
4040
 * libdevmapper's node management. We will rely on udev completely
4041
 * and there will be no fallback action provided by libdevmapper if
4042
 * udev does something improperly. Using the library fallback code has
4043
 * a consequence that you need to take into account: any device node
4044
 * or symlink created without udev is not recorded in udev database
4045
 * which other applications may read to get complete list of devices.
4046
 * For this reason, use of DM_UDEV_DISABLE_LIBRARY_FALLBACK is
4047
 * recommended on systems where udev is used. Keep library fallback
4048
 * enabled just for exceptional cases where you need to debug udev-related
4049
 * problems. If you hit such problems, please contact us through upstream
4050
 * LVM2 development mailing list (see also README file). This flag is
4051
 * currently not set by default in libdevmapper so you need to set it
4052
 * explicitly if you're sure that udev is behaving correctly on your
4053
 * setups.
4054
 */
4055
0
#define DM_UDEV_DISABLE_LIBRARY_FALLBACK 0x0020
4056
/*
4057
 * DM_UDEV_PRIMARY_SOURCE_FLAG is automatically appended by
4058
 * libdevmapper for all ioctls generating udev uevents. Once used in
4059
 * udev rules, we know if this is a real "primary sourced" event or not.
4060
 * We need to distinguish real events originated in libdevmapper from
4061
 * any spurious events to gather all missing information (e.g. events
4062
 * generated as a result of "udevadm trigger" command or as a result
4063
 * of the "watch" udev rule).
4064
 */
4065
0
#define DM_UDEV_PRIMARY_SOURCE_FLAG 0x0040
4066
4067
/*
4068
 * Udev flags reserved for use by any device-mapper subsystem.
4069
 */
4070
#define DM_SUBSYSTEM_UDEV_FLAG0 0x0100
4071
#define DM_SUBSYSTEM_UDEV_FLAG1 0x0200
4072
#define DM_SUBSYSTEM_UDEV_FLAG2 0x0400
4073
#define DM_SUBSYSTEM_UDEV_FLAG3 0x0800
4074
#define DM_SUBSYSTEM_UDEV_FLAG4 0x1000
4075
#define DM_SUBSYSTEM_UDEV_FLAG5 0x2000
4076
#define DM_SUBSYSTEM_UDEV_FLAG6 0x4000
4077
#define DM_SUBSYSTEM_UDEV_FLAG7 0x8000
4078
4079
int dm_cookie_supported(void);
4080
4081
/*
4082
 * Udev synchronization functions.
4083
 */
4084
void dm_udev_set_sync_support(int sync_with_udev);
4085
int dm_udev_get_sync_support(void);
4086
void dm_udev_set_checking(int checking);
4087
int dm_udev_get_checking(void);
4088
4089
/*
4090
 * Default value to get new auto generated cookie created
4091
 */
4092
#define DM_COOKIE_AUTO_CREATE 0
4093
int dm_udev_create_cookie(uint32_t *cookie);
4094
int dm_udev_complete(uint32_t cookie);
4095
int dm_udev_wait(uint32_t cookie);
4096
4097
/*
4098
 * dm_dev_wait_immediate
4099
 * If *ready is 1 on return, the wait is complete.
4100
 * If *ready is 0 on return, the wait is incomplete and either
4101
 * this function or dm_udev_wait() must be called again.
4102
 * Returns 0 on error, when neither function should be called again.
4103
 */
4104
int dm_udev_wait_immediate(uint32_t cookie, int *ready);
4105
4106
0
#define DM_DEV_DIR_UMASK 0022
4107
0
#define DM_CONTROL_NODE_UMASK 0177
4108
4109
#ifdef __cplusplus
4110
}
4111
#endif
4112
#endif        /* LIB_DEVICE_MAPPER_H */