1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::PathBuf;
use std::str::FromStr;

use super::device::Device;
use super::deviceinfo::DeviceInfo;
use super::dm::{DM, DmFlags};
use super::lineardev::{LinearDev, LinearDevTargetParams};
use super::result::{DmResult, DmError, ErrorEnum};
use super::shared::{DmDevice, TargetLine, TargetParams, TargetTable, device_create, device_exists,
                    device_match, parse_device, table_reload};
use super::types::{DataBlocks, DevId, DmName, DmUuid, MetaBlocks, Sectors, TargetTypeBuf};


const CACHE_TARGET_NAME: &str = "cache";

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CacheTargetParams {
    pub meta: Device,
    pub cache: Device,
    pub origin: Device,
    pub cache_block_size: Sectors,
    pub feature_args: HashSet<String>,
    pub policy: String,
    pub policy_args: HashMap<String, String>,
}

impl CacheTargetParams {
    pub fn new(meta: Device,
               cache: Device,
               origin: Device,
               cache_block_size: Sectors,
               feature_args: Vec<String>,
               policy: String,
               policy_args: Vec<(String, String)>)
               -> CacheTargetParams {
        CacheTargetParams {
            meta: meta,
            cache: cache,
            origin: origin,
            cache_block_size: cache_block_size,
            feature_args: feature_args.into_iter().collect::<HashSet<_>>(),
            policy: policy,
            policy_args: policy_args.into_iter().collect::<HashMap<_, _>>(),
        }
    }
}

impl fmt::Display for CacheTargetParams {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} {}", CACHE_TARGET_NAME, self.param_str())
    }
}

impl FromStr for CacheTargetParams {
    type Err = DmError;

    fn from_str(s: &str) -> DmResult<CacheTargetParams> {
        let vals = s.split(' ').collect::<Vec<_>>();

        if vals.len() < 8 {
            let err_msg = format!("expected at least 8 values in params string \"{}\", found {}",
                                  s,
                                  vals.len());
            return Err(DmError::Dm(ErrorEnum::Invalid, err_msg));
        }

        if vals[0] != CACHE_TARGET_NAME {
            let err_msg = format!("Expected a cache target entry but found target type {}",
                                  vals[0]);
            return Err(DmError::Dm(ErrorEnum::Invalid, err_msg));
        }

        let metadata_dev = parse_device(vals[1])?;
        let cache_dev = parse_device(vals[2])?;
        let origin_dev = parse_device(vals[3])?;

        let block_size = vals[4]
            .parse::<u64>()
            .map(Sectors)
            .map_err(|_| {
                DmError::Dm(ErrorEnum::Invalid,
                            format!("failed to parse value for data block size from \"{}\"",
                                    vals[4]))})?;

        let num_feature_args = vals[5]
            .parse::<usize>()
            .map_err(|_| {
                DmError::Dm(ErrorEnum::Invalid,
                            format!("failed to parse value for number of feature args from \"{}\"",
                                    vals[5]))})?;

        let end_feature_args_index = 6 + num_feature_args;
        let feature_args: Vec<String> = vals[6..end_feature_args_index]
            .iter()
            .map(|x| x.to_string())
            .collect();

        let policy = vals[end_feature_args_index].to_owned();

        let num_policy_args = vals[end_feature_args_index + 1]
            .parse::<usize>()
            .map_err(|_| {
                DmError::Dm(ErrorEnum::Invalid,
                            format!("failed to parse value for number of policy args from \"{}\"",
                                    vals[end_feature_args_index + 1]))})?;

        let start_policy_args_index = end_feature_args_index + 2;
        let end_policy_args_index = start_policy_args_index + num_policy_args;
        let policy_args: Vec<(String, String)> = vals[start_policy_args_index..
        end_policy_args_index]
                .chunks(2)
                .map(|x| (x[0].to_string(), x[1].to_string()))
                .collect();

        Ok(CacheTargetParams::new(metadata_dev,
                                  cache_dev,
                                  origin_dev,
                                  block_size,
                                  feature_args,
                                  policy,
                                  policy_args))

    }
}

impl TargetParams for CacheTargetParams {
    fn param_str(&self) -> String {
        let feature_args = if self.feature_args.is_empty() {
            "0".to_owned()
        } else {
            format!("{} {}",
                    self.feature_args.len(),
                    self.feature_args
                        .iter()
                        .cloned()
                        .collect::<Vec<_>>()
                        .join(" "))
        };

        let policy_args = if self.policy_args.is_empty() {
            "0".to_owned()
        } else {
            format!("{} {}",
                    self.policy_args.len(),
                    self.policy_args
                        .iter()
                        .map(|(k, v)| format!("{} {}", k, v))
                        .collect::<Vec<String>>()
                        .join(" "))
        };

        format!("{} {} {} {} {} {} {}",
                self.meta,
                self.cache,
                self.origin,
                *self.cache_block_size,
                feature_args,
                self.policy,
                policy_args)
    }

    fn target_type(&self) -> TargetTypeBuf {
        TargetTypeBuf::new(CACHE_TARGET_NAME.into()).expect("CACHE_TARGET_NAME is valid")
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CacheDevTargetTable {
    table: TargetLine<CacheTargetParams>,
}

impl CacheDevTargetTable {
    pub fn new(start: Sectors, length: Sectors, params: CacheTargetParams) -> CacheDevTargetTable {
        CacheDevTargetTable { table: TargetLine::new(start, length, params) }
    }
}

impl TargetTable for CacheDevTargetTable {
    fn from_raw_table(table: &[(Sectors, Sectors, TargetTypeBuf, String)])
                      -> DmResult<CacheDevTargetTable> {
        if table.len() != 1 {
            let err_msg = format!("CacheDev table should have exactly one line, has {} lines",
                                  table.len());
            return Err(DmError::Dm(ErrorEnum::Invalid, err_msg));
        }
        let line = table.first().expect("table.len() == 1");
        Ok(CacheDevTargetTable::new(line.0,
                                    line.1,
                                    format!("{} {}", line.2.to_string(), line.3)
                                        .parse::<CacheTargetParams>()?))
    }

    fn to_raw_table(&self) -> Vec<(Sectors, Sectors, TargetTypeBuf, String)> {
        to_raw_table_unique!(self)
    }
}


/// Cache usage
#[derive(Debug)]
pub struct CacheDevUsage {
    /// The metadata block size, should always be equal to META_BLOCK_SIZE.
    /// At time of writing, all metadata blocks have the same size.
    pub meta_block_size: Sectors,
    /// The number of metadata blocks in use
    pub used_meta: MetaBlocks,
    /// The number of metadata blocks available
    pub total_meta: MetaBlocks,
    /// The cache block size
    pub cache_block_size: Sectors,
    /// Used cache blocks
    pub used_cache: DataBlocks,
    /// Total cache blocks
    pub total_cache: DataBlocks,
}

impl CacheDevUsage {
    /// Make a new CacheDevUsage struct
    pub fn new(meta_block_size: Sectors,
               used_meta: MetaBlocks,
               total_meta: MetaBlocks,
               cache_block_size: Sectors,
               used_cache: DataBlocks,
               total_cache: DataBlocks)
               -> CacheDevUsage {
        // This is defined at the kernel level and should not change.
        assert_eq!(meta_block_size, Sectors(8));
        CacheDevUsage {
            meta_block_size: meta_block_size,
            used_meta: used_meta,
            total_meta: total_meta,
            cache_block_size: cache_block_size,
            used_cache: used_cache,
            total_cache: total_cache,
        }
    }
}

/// Cache dev performance data
#[derive(Debug)]
pub struct CacheDevPerformance {
    /// Number of read hits
    pub read_hits: u64,
    /// Number of read misses
    pub read_misses: u64,
    /// Number of write hits
    pub write_hits: u64,
    /// Number of write misses
    pub write_misses: u64,
    /// Number of demotions
    pub demotions: u64,
    /// Number of promotions
    pub promotions: u64,
    /// Number of dirty blocks
    pub dirty: u64,
}

impl CacheDevPerformance {
    /// Construct a new CacheDevPerformance struct
    pub fn new(read_hits: u64,
               read_misses: u64,
               write_hits: u64,
               write_misses: u64,
               demotions: u64,
               promotions: u64,
               dirty: u64)
               -> CacheDevPerformance {
        CacheDevPerformance {
            read_hits: read_hits,
            read_misses: read_misses,
            write_hits: write_hits,
            write_misses: write_misses,
            demotions: demotions,
            promotions: promotions,
            dirty: dirty,
        }
    }
}

/// The cache metadata mode
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CacheDevMetadataMode {
    /// The cache is working normally.
    Good,
    /// The cache has been forced to transition to read-only mode.
    ReadOnly,
}

/// Status values of a cache device when it is working
#[derive(Debug)]
pub struct CacheDevWorkingStatus {
    /// A struct recording block usage for all devices
    pub usage: CacheDevUsage,
    /// A struct recording cache dev performance
    pub performance: CacheDevPerformance,
    /// The feature args
    pub feature_args: Vec<String>,
    /// The core args
    pub core_args: Vec<(String, String)>,
    /// The name of the replacement policy to use
    /// User-defined policies are permitted.
    pub policy: String,
    /// Arguments for the designated policy
    pub policy_args: Vec<(String, String)>,
    /// cache metadata mode
    pub metadata_mode: CacheDevMetadataMode,
    /// needs_check flag has been set in metadata superblock
    pub needs_check: bool,
}

impl CacheDevWorkingStatus {
    /// Make a new CacheDevWorkingStatus struct
    #[allow(too_many_arguments)]
    pub fn new(usage: CacheDevUsage,
               performance: CacheDevPerformance,
               feature_args: Vec<String>,
               core_args: Vec<(String, String)>,
               policy: String,
               policy_args: Vec<(String, String)>,
               metadata_mode: CacheDevMetadataMode,
               needs_check: bool)
               -> CacheDevWorkingStatus {
        CacheDevWorkingStatus {
            usage: usage,
            performance: performance,
            feature_args: feature_args,
            core_args: core_args,
            policy: policy,
            policy_args: policy_args,
            metadata_mode: metadata_mode,
            needs_check: needs_check,
        }
    }
}

/// Return type of CacheDev::status()
#[derive(Debug)]
pub enum CacheDevStatus {
    /// The cache has not failed utterly
    Working(Box<CacheDevWorkingStatus>),
    /// The cache is in a failed condition
    Fail,
}


/// DM Cache device
#[derive(Debug)]
pub struct CacheDev {
    dev_info: Box<DeviceInfo>,
    meta_dev: LinearDev,
    cache_dev: LinearDev,
    origin_dev: LinearDev,
    table: CacheDevTargetTable,
}

impl DmDevice<CacheDevTargetTable> for CacheDev {
    fn device(&self) -> Device {
        device!(self)
    }

    fn devnode(&self) -> PathBuf {
        devnode!(self)
    }

    // Omit replacement policy field from equality test when checking that
    // two devices are the same. Equality of replacement policies is not a
    // necessary requirement for equality of devices as the replacement
    // policy can be changed dynamically by a reload of of the device's table.
    // It is convenient that this is the case, because checking equality of
    // replacement policies is somewhat hard. "default", which is a valid
    // policy string, is not a particular policy, but an alias for the default
    // policy for this version of devicemapper. Therefore, using string
    // equality to check equivalence can result in false negatives, as
    // "default" != "smq", the current default policy in the recent kernel.
    // Note: There is the possibility of implementing the following somewhat
    // complicated check. Without loss of generality, let
    // left[0].params.policy = "default" and
    // right[0].params.policy = X, where X != "default". Then, if X is the
    // default policy, return true, otherwise return false. Unfortunately,
    // there is no straightforward programmatic way of determining the default
    // policy for a given kernel, and we are assured that the default policy
    // can vary between kernels, and may of course, change in future.
    fn equivalent_tables(left: &CacheDevTargetTable,
                         right: &CacheDevTargetTable)
                         -> DmResult<bool> {
        let left = &left.table;
        let right = &right.table;

        Ok(left.start == right.start && left.length == right.length &&
           left.params.meta == right.params.meta &&
           left.params.origin == right.params.origin &&
           left.params.cache_block_size == right.params.cache_block_size &&
           left.params.feature_args == right.params.feature_args &&
           left.params.policy_args == right.params.policy_args)
    }

    fn name(&self) -> &DmName {
        name!(self)
    }

    fn size(&self) -> Sectors {
        self.origin_dev.size()
    }

    fn table(&self) -> &CacheDevTargetTable {
        table!(self)
    }

    fn teardown(self, dm: &DM) -> DmResult<()> {
        dm.device_remove(&DevId::Name(self.name()), DmFlags::empty())?;
        self.cache_dev.teardown(dm)?;
        self.origin_dev.teardown(dm)?;
        self.meta_dev.teardown(dm)?;
        Ok(())
    }

    fn uuid(&self) -> Option<&DmUuid> {
        uuid!(self)
    }
}


/// Cache device implementation.
impl CacheDev {
    /// Construct a new CacheDev with the given data and meta devs.
    /// Returns an error if the device is already known to the kernel.
    pub fn new(dm: &DM,
               name: &DmName,
               uuid: Option<&DmUuid>,
               meta: LinearDev,
               cache: LinearDev,
               origin: LinearDev,
               cache_block_size: Sectors)
               -> DmResult<CacheDev> {
        if device_exists(dm, name)? {
            let err_msg = format!("cachedev {} already exists", name);
            return Err(DmError::Dm(ErrorEnum::Invalid, err_msg));
        }

        let table = CacheDev::gen_default_table(&meta, &cache, &origin, cache_block_size);
        let dev_info = device_create(dm, name, uuid, &table)?;

        Ok(CacheDev {
               dev_info: Box::new(dev_info),
               meta_dev: meta,
               cache_dev: cache,
               origin_dev: origin,
               table: table,
           })
    }

    /// Set up a cache device from the given metadata and data devices.
    pub fn setup(dm: &DM,
                 name: &DmName,
                 uuid: Option<&DmUuid>,
                 meta: LinearDev,
                 cache: LinearDev,
                 origin: LinearDev,
                 cache_block_size: Sectors)
                 -> DmResult<CacheDev> {
        let table = CacheDev::gen_default_table(&meta, &origin, &cache, cache_block_size);
        let dev = if device_exists(dm, name)? {
            let dev_info = dm.device_info(&DevId::Name(name))?;
            let dev = CacheDev {
                dev_info: Box::new(dev_info),
                meta_dev: meta,
                cache_dev: cache,
                origin_dev: origin,
                table: table,
            };
            device_match(dm, &dev, uuid)?;
            dev
        } else {
            let dev_info = device_create(dm, name, uuid, &table)?;
            CacheDev {
                dev_info: Box::new(dev_info),
                meta_dev: meta,
                cache_dev: cache,
                origin_dev: origin,
                table: table,
            }
        };

        Ok(dev)
    }

    /// Set the table for the existing origin device.
    /// Warning: It is the client's responsibility to make sure the designated
    /// table is compatible with the device's existing table.
    /// If not, this function will still succeed, but some kind of
    /// data corruption will be the inevitable result.
    pub fn set_origin_table(&mut self,
                            dm: &DM,
                            table: Vec<TargetLine<LinearDevTargetParams>>)
                            -> DmResult<()> {
        self.origin_dev.set_table(dm, table)?;

        let mut table = self.table.clone();
        table.table.length = self.origin_dev.size();
        table_reload(dm, &DevId::Name(self.name()), &table)?;
        self.table = table;

        Ok(())
    }

    /// Generate a table to be passed to DM. The format of the table
    /// entries is:
    /// <start sec (0)> <length> "cache" <cache-specific string>
    /// where the cache-specific string has the format:
    /// <meta maj:min> <cache maj:min> <origin maj:min> <block size>
    /// <#num feature args (0)> <replacement policy (default)>
    /// <#num policy args (0)>
    /// There is exactly one entry in the table.
    /// Various defaults are hard coded in the method.
    fn gen_default_table(meta: &LinearDev,
                         cache: &LinearDev,
                         origin: &LinearDev,
                         cache_block_size: Sectors)
                         -> CacheDevTargetTable {
        CacheDevTargetTable::new(Sectors::default(),
                                 origin.size(),
                                 CacheTargetParams::new(meta.device(),
                                                        cache.device(),
                                                        origin.device(),
                                                        cache_block_size,
                                                        vec![],
                                                        "default".to_owned(),
                                                        vec![]))
    }

    /// Parse pairs of arguments from a slice
    /// Use the same policy as status() method in asserting
    fn parse_pairs(start_index: usize, vals: &[&str]) -> (usize, Vec<(String, String)>) {
        let num_pairs = vals[start_index]
            .parse::<usize>()
            .expect("number value must be valid format");
        if num_pairs % 2 != 0 {
            panic!(format!("Number of args \"{}\" is not even", num_pairs));
        }
        let next_start_index = start_index + num_pairs + 1;
        (next_start_index,
         vals[start_index + 1..next_start_index]
             .chunks(2)
             .map(|p| (p[0].to_string(), p[1].to_string()))
             .collect())
    }

    /// Get the current status of the cache device.
    // Note: This method is not entirely complete. In particular, *_args values
    // may require more or better checking or processing.
    pub fn status(&self, dm: &DM) -> DmResult<CacheDevStatus> {
        let (_, status) = dm.table_status(&DevId::Name(self.name()), DmFlags::empty())?;

        assert_eq!(status.len(),
                   1,
                   "Kernel must return 1 line from cache dev status");

        let status_line = &status.first().expect("assertion above holds").3;
        if status_line.starts_with("Fail") {
            return Ok(CacheDevStatus::Fail);
        }

        let status_vals = status_line.split(' ').collect::<Vec<_>>();
        assert!(status_vals.len() >= 17,
                "Kernel must return at least 17 values from cache dev status");


        let usage = {
            let meta_block_size = status_vals[0];
            let meta_usage = status_vals[1].split('/').collect::<Vec<_>>();
            let cache_block_size = status_vals[2];
            let cache_usage = status_vals[3].split('/').collect::<Vec<_>>();
            CacheDevUsage::new(Sectors(meta_block_size
                                           .parse::<u64>()
                                           .expect("meta_block_size value must be valid")),
                               MetaBlocks(meta_usage[0]
                                              .parse::<u64>()
                                              .expect("used_meta value must be valid")),
                               MetaBlocks(meta_usage[1]
                                              .parse::<u64>()
                                              .expect("total_meta value must be valid")),
                               Sectors(cache_block_size
                                           .parse::<u64>()
                                           .expect("cache_block_size value must be valid")),
                               DataBlocks(cache_usage[0]
                                              .parse::<u64>()
                                              .expect("used_cache value must be valid")),
                               DataBlocks(cache_usage[1]
                                              .parse::<u64>()
                                              .expect("total_cache value must be valid")))
        };

        let performance =
            CacheDevPerformance::new(status_vals[4]
                                         .parse::<u64>()
                                         .expect("read hits value must be valid format"),
                                     status_vals[5]
                                         .parse::<u64>()
                                         .expect("read misses value must be valid format"),
                                     status_vals[6]
                                         .parse::<u64>()
                                         .expect("write hits value must be valid format"),
                                     status_vals[7]
                                         .parse::<u64>()
                                         .expect("write misses value must be valid format"),
                                     status_vals[8]
                                         .parse::<u64>()
                                         .expect("demotions value must be valid format"),
                                     status_vals[9]
                                         .parse::<u64>()
                                         .expect("promotions value must be valid format"),
                                     status_vals[10]
                                         .parse::<u64>()
                                         .expect("dirty value must be valid format"));

        let num_feature_args = status_vals[11]
            .parse::<usize>()
            .expect("number value must be valid format");
        let core_args_start_index = 12usize + num_feature_args;
        let feature_args: Vec<String> = status_vals[12..core_args_start_index]
            .iter()
            .map(|x| x.to_string())
            .collect();

        let (policy_start_index, core_args) = CacheDev::parse_pairs(core_args_start_index,
                                                                    &status_vals);

        let policy = status_vals[policy_start_index].to_string();
        let (rest_start_index, policy_args) = CacheDev::parse_pairs(policy_start_index + 1,
                                                                    &status_vals);

        let cache_metadata_mode = match status_vals[rest_start_index] {
            "rw" => CacheDevMetadataMode::Good,
            "ro" => CacheDevMetadataMode::ReadOnly,
            val => {
                panic!(format!("Kernel returned unexpected {}th value \"{}\" in thin pool status",
                               rest_start_index + 1,
                               val))
            }
        };

        let needs_check = match status_vals[rest_start_index + 1] {
            "-" => false,
            "needs_check" => true,
            val => {
                panic!(format!("Kernel returned unexpected {}th value \"{}\" in thin pool status",
                               rest_start_index + 2,
                               val))
            }
        };

        Ok(CacheDevStatus::Working(Box::new(CacheDevWorkingStatus::new(usage,
                                                                       performance,
                                                                       feature_args,
                                                                       core_args,
                                                                       policy,
                                                                       policy_args,
                                                                       cache_metadata_mode,
                                                                       needs_check))))
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::super::consts::IEC;
    use super::super::device::devnode_to_devno;
    use super::super::lineardev::{LinearDevTargetParams, LinearTargetParams};
    use super::super::loopbacked::test_with_spec;

    use super::*;

    // Specified in kernel docs
    const MIN_CACHE_BLOCK_SIZE: Sectors = Sectors(64); // 32 KiB
    #[allow(dead_code)]
    const MAX_CACHE_BLOCK_SIZE: Sectors = Sectors(2_097_152); // 1 GiB

    // Test creating a minimal cache dev.
    // Verify that status method executes and gives reasonable values.
    fn test_minimal_cache_dev(paths: &[&Path]) -> () {
        assert!(paths.len() >= 2);
        let dev1 = Device::from(devnode_to_devno(paths[0]).unwrap().unwrap());

        let dm = DM::new().unwrap();

        let meta_name = DmName::new("cache-meta").expect("valid format");

        // Minimum recommended metadata size for thinpool
        let meta_length = Sectors(4 * IEC::Ki);
        let meta_params = LinearTargetParams::new(dev1, Sectors(0));
        let meta_table = vec![TargetLine::new(Sectors(0),
                                              meta_length,
                                              LinearDevTargetParams::Linear(meta_params))];
        let meta = LinearDev::setup(&dm, meta_name, None, meta_table).unwrap();

        let cache_name = DmName::new("cache-cache").expect("valid format");
        let cache_offset = meta_length;
        let cache_length = MIN_CACHE_BLOCK_SIZE;
        let cache_params = LinearTargetParams::new(dev1, cache_offset);
        let cache_table = vec![TargetLine::new(Sectors(0),
                                               cache_length,
                                               LinearDevTargetParams::Linear(cache_params))];
        let cache = LinearDev::setup(&dm, cache_name, None, cache_table).unwrap();

        let dev2 = Device::from(devnode_to_devno(paths[1]).unwrap().unwrap());

        let origin_name = DmName::new("cache-origin").expect("valid format");
        let origin_length = 512u64 * MIN_CACHE_BLOCK_SIZE;
        let origin_params = LinearTargetParams::new(dev2, Sectors(0));
        let origin_table = vec![TargetLine::new(Sectors(0),
                                                origin_length,
                                                LinearDevTargetParams::Linear(origin_params))];
        let origin = LinearDev::setup(&dm, origin_name, None, origin_table).unwrap();

        let cache = CacheDev::new(&dm,
                                  DmName::new("cache").expect("valid format"),
                                  None,
                                  meta,
                                  cache,
                                  origin,
                                  MIN_CACHE_BLOCK_SIZE)
                .unwrap();

        match cache.status(&dm).unwrap() {
            CacheDevStatus::Working(ref status) => {
                let usage = &status.usage;

                assert_eq!(usage.meta_block_size, Sectors(8));

                // Even an empty cache dev takes up some metadata space.
                assert!(usage.used_meta > MetaBlocks(0));

                assert_eq!(usage.cache_block_size, MIN_CACHE_BLOCK_SIZE);
                assert_eq!(usage.cache_block_size,
                           cache.table.table.params.cache_block_size);

                // No data means no cache blocks used
                assert_eq!(usage.used_cache, DataBlocks(0));

                let performance = &status.performance;

                // No activity should mean all performance data is 0
                assert_eq!(performance.read_hits, 0);
                assert_eq!(performance.read_misses, 0);
                assert_eq!(performance.write_hits, 0);
                assert_eq!(performance.write_misses, 0);
                assert_eq!(performance.demotions, 0);
                assert_eq!(performance.promotions, 0);
                assert_eq!(performance.dirty, 0);

                // The current defaults for configuration values
                assert_eq!(status.feature_args, vec!["writeback"]);
                assert_eq!(status.core_args,
                           vec![("migration_threshold".to_string(), "2048".to_string())]);
                assert_eq!(status.policy, "smq");

                assert_eq!(status.policy_args, vec![] as Vec<(String, String)>);

                assert_eq!(status.metadata_mode, CacheDevMetadataMode::Good);

                assert_eq!(status.needs_check, false);


            }
            _ => assert!(false),
        }

        let table = CacheDev::load_table(&dm, &DevId::Name(cache.name()))
            .unwrap()
            .table;

        let params = &table.params;
        assert_eq!(params.cache_block_size, MIN_CACHE_BLOCK_SIZE);
        assert_eq!(params.feature_args, HashSet::new());
        assert_eq!(params.policy, "default");

        cache.teardown(&dm).unwrap();
    }

    #[test]
    fn loop_test_minimal_cache_dev() {
        test_with_spec(2, test_minimal_cache_dev);
    }
}