2 * Copyright (C) 2003 Christophe Saout <christophe@saout.de>
3 * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
5 * This file is released under the GPL.
9 #include <linux/module.h>
10 #include <linux/init.h>
11 #include <linux/kernel.h>
12 #include <linux/bio.h>
13 #include <linux/blkdev.h>
14 #include <linux/mempool.h>
15 #include <linux/slab.h>
16 #include <linux/crypto.h>
17 #include <linux/workqueue.h>
18 #include <asm/atomic.h>
19 #include <linux/scatterlist.h>
24 #define DM_MSG_PREFIX "crypt"
27 * per bio private data
30 struct dm_target *target;
32 struct bio *first_clone;
33 struct work_struct work;
39 * context holding the current state of a multi-part conversion
41 struct convert_context {
44 unsigned int offset_in;
45 unsigned int offset_out;
54 struct crypt_iv_operations {
55 int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
57 void (*dtr)(struct crypt_config *cc);
58 const char *(*status)(struct crypt_config *cc);
59 int (*generator)(struct crypt_config *cc, u8 *iv, sector_t sector);
63 * Crypt: maps a linear range of a block device
64 * and encrypts / decrypts at the same time.
71 * pool for per bio private data and
72 * for encryption buffer pages
80 struct crypt_iv_operations *iv_gen_ops;
82 struct crypto_cipher *iv_gen_private;
86 char cipher[CRYPTO_MAX_ALG_NAME];
87 char chainmode[CRYPTO_MAX_ALG_NAME];
88 struct crypto_blkcipher *tfm;
89 unsigned int key_size;
94 #define MIN_POOL_PAGES 32
95 #define MIN_BIO_PAGES 8
97 static kmem_cache_t *_crypt_io_pool;
100 * Different IV generation algorithms:
102 * plain: the initial vector is the 32-bit little-endian version of the sector
103 * number, padded with zeros if neccessary.
105 * essiv: "encrypted sector|salt initial vector", the sector number is
106 * encrypted with the bulk cipher using a salt as key. The salt
107 * should be derived from the bulk cipher's key via hashing.
109 * plumb: unimplemented, see:
110 * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
113 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
115 memset(iv, 0, cc->iv_size);
116 *(u32 *)iv = cpu_to_le32(sector & 0xffffffff);
121 static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
124 struct crypto_cipher *essiv_tfm;
125 struct crypto_hash *hash_tfm;
126 struct hash_desc desc;
127 struct scatterlist sg;
128 unsigned int saltsize;
133 ti->error = "Digest algorithm missing for ESSIV mode";
137 /* Hash the cipher key with the given hash algorithm */
138 hash_tfm = crypto_alloc_hash(opts, 0, CRYPTO_ALG_ASYNC);
139 if (IS_ERR(hash_tfm)) {
140 ti->error = "Error initializing ESSIV hash";
141 return PTR_ERR(hash_tfm);
144 saltsize = crypto_hash_digestsize(hash_tfm);
145 salt = kmalloc(saltsize, GFP_KERNEL);
147 ti->error = "Error kmallocing salt storage in ESSIV";
148 crypto_free_hash(hash_tfm);
152 sg_set_buf(&sg, cc->key, cc->key_size);
154 desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
155 err = crypto_hash_digest(&desc, &sg, cc->key_size, salt);
156 crypto_free_hash(hash_tfm);
159 ti->error = "Error calculating hash in ESSIV";
163 /* Setup the essiv_tfm with the given salt */
164 essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
165 if (IS_ERR(essiv_tfm)) {
166 ti->error = "Error allocating crypto tfm for ESSIV";
168 return PTR_ERR(essiv_tfm);
170 if (crypto_cipher_blocksize(essiv_tfm) !=
171 crypto_blkcipher_ivsize(cc->tfm)) {
172 ti->error = "Block size of ESSIV cipher does "
173 "not match IV size of block cipher";
174 crypto_free_cipher(essiv_tfm);
178 err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
180 ti->error = "Failed to set key for ESSIV cipher";
181 crypto_free_cipher(essiv_tfm);
187 cc->iv_gen_private = essiv_tfm;
191 static void crypt_iv_essiv_dtr(struct crypt_config *cc)
193 crypto_free_cipher(cc->iv_gen_private);
194 cc->iv_gen_private = NULL;
197 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
199 memset(iv, 0, cc->iv_size);
200 *(u64 *)iv = cpu_to_le64(sector);
201 crypto_cipher_encrypt_one(cc->iv_gen_private, iv, iv);
205 static struct crypt_iv_operations crypt_iv_plain_ops = {
206 .generator = crypt_iv_plain_gen
209 static struct crypt_iv_operations crypt_iv_essiv_ops = {
210 .ctr = crypt_iv_essiv_ctr,
211 .dtr = crypt_iv_essiv_dtr,
212 .generator = crypt_iv_essiv_gen
217 crypt_convert_scatterlist(struct crypt_config *cc, struct scatterlist *out,
218 struct scatterlist *in, unsigned int length,
219 int write, sector_t sector)
222 struct blkcipher_desc desc = {
225 .flags = CRYPTO_TFM_REQ_MAY_SLEEP,
229 if (cc->iv_gen_ops) {
230 r = cc->iv_gen_ops->generator(cc, iv, sector);
235 r = crypto_blkcipher_encrypt_iv(&desc, out, in, length);
237 r = crypto_blkcipher_decrypt_iv(&desc, out, in, length);
240 r = crypto_blkcipher_encrypt(&desc, out, in, length);
242 r = crypto_blkcipher_decrypt(&desc, out, in, length);
249 crypt_convert_init(struct crypt_config *cc, struct convert_context *ctx,
250 struct bio *bio_out, struct bio *bio_in,
251 sector_t sector, int write)
253 ctx->bio_in = bio_in;
254 ctx->bio_out = bio_out;
257 ctx->idx_in = bio_in ? bio_in->bi_idx : 0;
258 ctx->idx_out = bio_out ? bio_out->bi_idx : 0;
259 ctx->sector = sector + cc->iv_offset;
264 * Encrypt / decrypt data from one bio to another one (can be the same one)
266 static int crypt_convert(struct crypt_config *cc,
267 struct convert_context *ctx)
271 while(ctx->idx_in < ctx->bio_in->bi_vcnt &&
272 ctx->idx_out < ctx->bio_out->bi_vcnt) {
273 struct bio_vec *bv_in = bio_iovec_idx(ctx->bio_in, ctx->idx_in);
274 struct bio_vec *bv_out = bio_iovec_idx(ctx->bio_out, ctx->idx_out);
275 struct scatterlist sg_in = {
276 .page = bv_in->bv_page,
277 .offset = bv_in->bv_offset + ctx->offset_in,
278 .length = 1 << SECTOR_SHIFT
280 struct scatterlist sg_out = {
281 .page = bv_out->bv_page,
282 .offset = bv_out->bv_offset + ctx->offset_out,
283 .length = 1 << SECTOR_SHIFT
286 ctx->offset_in += sg_in.length;
287 if (ctx->offset_in >= bv_in->bv_len) {
292 ctx->offset_out += sg_out.length;
293 if (ctx->offset_out >= bv_out->bv_len) {
298 r = crypt_convert_scatterlist(cc, &sg_out, &sg_in, sg_in.length,
299 ctx->write, ctx->sector);
310 * Generate a new unfragmented bio with the given size
311 * This should never violate the device limitations
312 * May return a smaller bio when running out of pages
315 crypt_alloc_buffer(struct crypt_config *cc, unsigned int size,
316 struct bio *base_bio, unsigned int *bio_vec_idx)
319 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
320 gfp_t gfp_mask = GFP_NOIO | __GFP_HIGHMEM;
324 * Use __GFP_NOMEMALLOC to tell the VM to act less aggressively and
325 * to fail earlier. This is not necessary but increases throughput.
326 * FIXME: Is this really intelligent?
329 bio = bio_clone(base_bio, GFP_NOIO|__GFP_NOMEMALLOC);
331 bio = bio_alloc(GFP_NOIO|__GFP_NOMEMALLOC, nr_iovecs);
335 /* if the last bio was not complete, continue where that one ended */
336 bio->bi_idx = *bio_vec_idx;
337 bio->bi_vcnt = *bio_vec_idx;
339 bio->bi_flags &= ~(1 << BIO_SEG_VALID);
341 /* bio->bi_idx pages have already been allocated */
342 size -= bio->bi_idx * PAGE_SIZE;
344 for(i = bio->bi_idx; i < nr_iovecs; i++) {
345 struct bio_vec *bv = bio_iovec_idx(bio, i);
347 bv->bv_page = mempool_alloc(cc->page_pool, gfp_mask);
352 * if additional pages cannot be allocated without waiting,
353 * return a partially allocated bio, the caller will then try
354 * to allocate additional bios while submitting this partial bio
356 if ((i - bio->bi_idx) == (MIN_BIO_PAGES - 1))
357 gfp_mask = (gfp_mask | __GFP_NOWARN) & ~__GFP_WAIT;
360 if (size > PAGE_SIZE)
361 bv->bv_len = PAGE_SIZE;
365 bio->bi_size += bv->bv_len;
376 * Remember the last bio_vec allocated to be able
377 * to correctly continue after the splitting.
379 *bio_vec_idx = bio->bi_vcnt;
384 static void crypt_free_buffer_pages(struct crypt_config *cc,
385 struct bio *bio, unsigned int bytes)
387 unsigned int i, start, end;
391 * This is ugly, but Jens Axboe thinks that using bi_idx in the
392 * endio function is too dangerous at the moment, so I calculate the
393 * correct position using bi_vcnt and bi_size.
394 * The bv_offset and bv_len fields might already be modified but we
395 * know that we always allocated whole pages.
396 * A fix to the bi_idx issue in the kernel is in the works, so
397 * we will hopefully be able to revert to the cleaner solution soon.
399 i = bio->bi_vcnt - 1;
400 bv = bio_iovec_idx(bio, i);
401 end = (i << PAGE_SHIFT) + (bv->bv_offset + bv->bv_len) - bio->bi_size;
404 start >>= PAGE_SHIFT;
410 for(i = start; i < end; i++) {
411 bv = bio_iovec_idx(bio, i);
412 BUG_ON(!bv->bv_page);
413 mempool_free(bv->bv_page, cc->page_pool);
419 * One of the bios was finished. Check for completion of
420 * the whole request and correctly clean up the buffer.
422 static void dec_pending(struct crypt_io *io, int error)
424 struct crypt_config *cc = (struct crypt_config *) io->target->private;
429 if (!atomic_dec_and_test(&io->pending))
433 bio_put(io->first_clone);
435 bio_endio(io->bio, io->bio->bi_size, io->error);
437 mempool_free(io, cc->io_pool);
443 * Needed because it would be very unwise to do decryption in an
444 * interrupt context, so bios returning from read requests get
447 static struct workqueue_struct *_kcryptd_workqueue;
449 static void kcryptd_do_work(void *data)
451 struct crypt_io *io = (struct crypt_io *) data;
452 struct crypt_config *cc = (struct crypt_config *) io->target->private;
453 struct convert_context ctx;
456 crypt_convert_init(cc, &ctx, io->bio, io->bio,
457 io->bio->bi_sector - io->target->begin, 0);
458 r = crypt_convert(cc, &ctx);
463 static void kcryptd_queue_io(struct crypt_io *io)
465 INIT_WORK(&io->work, kcryptd_do_work, io);
466 queue_work(_kcryptd_workqueue, &io->work);
470 * Decode key from its hex representation
472 static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
480 for(i = 0; i < size; i++) {
484 key[i] = (u8)simple_strtoul(buffer, &endp, 16);
486 if (endp != &buffer[2])
497 * Encode key into its hex representation
499 static void crypt_encode_key(char *hex, u8 *key, unsigned int size)
503 for(i = 0; i < size; i++) {
504 sprintf(hex, "%02x", *key);
511 * Construct an encryption mapping:
512 * <cipher> <key> <iv_offset> <dev_path> <start>
514 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
516 struct crypt_config *cc;
517 struct crypto_blkcipher *tfm;
523 unsigned int key_size;
524 unsigned long long tmpll;
527 ti->error = "Not enough arguments";
532 cipher = strsep(&tmp, "-");
533 chainmode = strsep(&tmp, "-");
534 ivopts = strsep(&tmp, "-");
535 ivmode = strsep(&ivopts, ":");
538 DMWARN("Unexpected additional cipher options");
540 key_size = strlen(argv[1]) >> 1;
542 cc = kmalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
545 "Cannot allocate transparent encryption context";
549 cc->key_size = key_size;
550 if ((!key_size && strcmp(argv[1], "-") != 0) ||
551 (key_size && crypt_decode_key(cc->key, argv[1], key_size) < 0)) {
552 ti->error = "Error decoding key";
556 /* Compatiblity mode for old dm-crypt cipher strings */
557 if (!chainmode || (strcmp(chainmode, "plain") == 0 && !ivmode)) {
562 if (strcmp(chainmode, "ecb") && !ivmode) {
563 ti->error = "This chaining mode requires an IV mechanism";
567 if (snprintf(cc->cipher, CRYPTO_MAX_ALG_NAME, "%s(%s)", chainmode,
568 cipher) >= CRYPTO_MAX_ALG_NAME) {
569 ti->error = "Chain mode + cipher name is too long";
573 tfm = crypto_alloc_blkcipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
575 ti->error = "Error allocating crypto tfm";
579 strcpy(cc->cipher, cipher);
580 strcpy(cc->chainmode, chainmode);
584 * Choose ivmode. Valid modes: "plain", "essiv:<esshash>".
585 * See comments at iv code
589 cc->iv_gen_ops = NULL;
590 else if (strcmp(ivmode, "plain") == 0)
591 cc->iv_gen_ops = &crypt_iv_plain_ops;
592 else if (strcmp(ivmode, "essiv") == 0)
593 cc->iv_gen_ops = &crypt_iv_essiv_ops;
595 ti->error = "Invalid IV mode";
599 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr &&
600 cc->iv_gen_ops->ctr(cc, ti, ivopts) < 0)
603 cc->iv_size = crypto_blkcipher_ivsize(tfm);
605 /* at least a 64 bit sector number should fit in our buffer */
606 cc->iv_size = max(cc->iv_size,
607 (unsigned int)(sizeof(u64) / sizeof(u8)));
609 if (cc->iv_gen_ops) {
610 DMWARN("Selected cipher does not support IVs");
611 if (cc->iv_gen_ops->dtr)
612 cc->iv_gen_ops->dtr(cc);
613 cc->iv_gen_ops = NULL;
617 cc->io_pool = mempool_create_slab_pool(MIN_IOS, _crypt_io_pool);
619 ti->error = "Cannot allocate crypt io mempool";
623 cc->page_pool = mempool_create_page_pool(MIN_POOL_PAGES, 0);
624 if (!cc->page_pool) {
625 ti->error = "Cannot allocate page mempool";
629 if (crypto_blkcipher_setkey(tfm, cc->key, key_size) < 0) {
630 ti->error = "Error setting key";
634 if (sscanf(argv[2], "%llu", &tmpll) != 1) {
635 ti->error = "Invalid iv_offset sector";
638 cc->iv_offset = tmpll;
640 if (sscanf(argv[4], "%llu", &tmpll) != 1) {
641 ti->error = "Invalid device sector";
646 if (dm_get_device(ti, argv[3], cc->start, ti->len,
647 dm_table_get_mode(ti->table), &cc->dev)) {
648 ti->error = "Device lookup failed";
652 if (ivmode && cc->iv_gen_ops) {
655 cc->iv_mode = kmalloc(strlen(ivmode) + 1, GFP_KERNEL);
657 ti->error = "Error kmallocing iv_mode string";
660 strcpy(cc->iv_mode, ivmode);
668 mempool_destroy(cc->page_pool);
670 mempool_destroy(cc->io_pool);
672 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
673 cc->iv_gen_ops->dtr(cc);
675 crypto_free_blkcipher(tfm);
677 /* Must zero key material before freeing */
678 memset(cc, 0, sizeof(*cc) + cc->key_size * sizeof(u8));
683 static void crypt_dtr(struct dm_target *ti)
685 struct crypt_config *cc = (struct crypt_config *) ti->private;
687 mempool_destroy(cc->page_pool);
688 mempool_destroy(cc->io_pool);
691 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
692 cc->iv_gen_ops->dtr(cc);
693 crypto_free_blkcipher(cc->tfm);
694 dm_put_device(ti, cc->dev);
696 /* Must zero key material before freeing */
697 memset(cc, 0, sizeof(*cc) + cc->key_size * sizeof(u8));
701 static int crypt_endio(struct bio *bio, unsigned int done, int error)
703 struct crypt_io *io = (struct crypt_io *) bio->bi_private;
704 struct crypt_config *cc = (struct crypt_config *) io->target->private;
706 if (bio_data_dir(bio) == WRITE) {
708 * free the processed pages, even if
709 * it's only a partially completed write
711 crypt_free_buffer_pages(cc, bio, done);
720 * successful reads are decrypted by the worker thread
722 if ((bio_data_dir(bio) == READ)
723 && bio_flagged(bio, BIO_UPTODATE)) {
724 kcryptd_queue_io(io);
728 dec_pending(io, error);
732 static inline struct bio *
733 crypt_clone(struct crypt_config *cc, struct crypt_io *io, struct bio *bio,
734 sector_t sector, unsigned int *bvec_idx,
735 struct convert_context *ctx)
739 if (bio_data_dir(bio) == WRITE) {
740 clone = crypt_alloc_buffer(cc, bio->bi_size,
741 io->first_clone, bvec_idx);
743 ctx->bio_out = clone;
744 if (crypt_convert(cc, ctx) < 0) {
745 crypt_free_buffer_pages(cc, clone,
753 * The block layer might modify the bvec array, so always
754 * copy the required bvecs because we need the original
755 * one in order to decrypt the whole bio data *afterwards*.
757 clone = bio_alloc(GFP_NOIO, bio_segments(bio));
760 clone->bi_vcnt = bio_segments(bio);
761 clone->bi_size = bio->bi_size;
762 memcpy(clone->bi_io_vec, bio_iovec(bio),
763 sizeof(struct bio_vec) * clone->bi_vcnt);
770 clone->bi_private = io;
771 clone->bi_end_io = crypt_endio;
772 clone->bi_bdev = cc->dev->bdev;
773 clone->bi_sector = cc->start + sector;
774 clone->bi_rw = bio->bi_rw;
779 static int crypt_map(struct dm_target *ti, struct bio *bio,
780 union map_info *map_context)
782 struct crypt_config *cc = (struct crypt_config *) ti->private;
783 struct crypt_io *io = mempool_alloc(cc->io_pool, GFP_NOIO);
784 struct convert_context ctx;
786 unsigned int remaining = bio->bi_size;
787 sector_t sector = bio->bi_sector - ti->begin;
788 unsigned int bvec_idx = 0;
792 io->first_clone = NULL;
794 atomic_set(&io->pending, 1); /* hold a reference */
796 if (bio_data_dir(bio) == WRITE)
797 crypt_convert_init(cc, &ctx, NULL, bio, sector, 1);
800 * The allocated buffers can be smaller than the whole bio,
801 * so repeat the whole process until all the data can be handled.
804 clone = crypt_clone(cc, io, bio, sector, &bvec_idx, &ctx);
808 if (!io->first_clone) {
810 * hold a reference to the first clone, because it
811 * holds the bio_vec array and that can't be freed
812 * before all other clones are released
815 io->first_clone = clone;
817 atomic_inc(&io->pending);
819 remaining -= clone->bi_size;
820 sector += bio_sectors(clone);
822 generic_make_request(clone);
824 /* out of memory -> run queues */
826 blk_congestion_wait(bio_data_dir(clone), HZ/100);
829 /* drop reference, clones could have returned before we reach this */
834 if (io->first_clone) {
835 dec_pending(io, -ENOMEM);
839 /* if no bio has been dispatched yet, we can directly return the error */
840 mempool_free(io, cc->io_pool);
844 static int crypt_status(struct dm_target *ti, status_type_t type,
845 char *result, unsigned int maxlen)
847 struct crypt_config *cc = (struct crypt_config *) ti->private;
849 const char *chainmode = NULL;
853 case STATUSTYPE_INFO:
857 case STATUSTYPE_TABLE:
858 cipher = crypto_blkcipher_name(cc->tfm);
860 chainmode = cc->chainmode;
863 DMEMIT("%s-%s-%s ", cipher, chainmode, cc->iv_mode);
865 DMEMIT("%s-%s ", cipher, chainmode);
867 if (cc->key_size > 0) {
868 if ((maxlen - sz) < ((cc->key_size << 1) + 1))
871 crypt_encode_key(result + sz, cc->key, cc->key_size);
872 sz += cc->key_size << 1;
879 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
880 cc->dev->name, (unsigned long long)cc->start);
886 static struct target_type crypt_target = {
889 .module = THIS_MODULE,
893 .status = crypt_status,
896 static int __init dm_crypt_init(void)
900 _crypt_io_pool = kmem_cache_create("dm-crypt_io",
901 sizeof(struct crypt_io),
906 _kcryptd_workqueue = create_workqueue("kcryptd");
907 if (!_kcryptd_workqueue) {
909 DMERR("couldn't create kcryptd");
913 r = dm_register_target(&crypt_target);
915 DMERR("register failed %d", r);
922 destroy_workqueue(_kcryptd_workqueue);
924 kmem_cache_destroy(_crypt_io_pool);
928 static void __exit dm_crypt_exit(void)
930 int r = dm_unregister_target(&crypt_target);
933 DMERR("unregister failed %d", r);
935 destroy_workqueue(_kcryptd_workqueue);
936 kmem_cache_destroy(_crypt_io_pool);
939 module_init(dm_crypt_init);
940 module_exit(dm_crypt_exit);
942 MODULE_AUTHOR("Christophe Saout <christophe@saout.de>");
943 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
944 MODULE_LICENSE("GPL");