2 * Copyright (C) 2003 Christophe Saout <christophe@saout.de>
3 * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
4 * Copyright (C) 2006-2009 Red Hat, Inc. All rights reserved.
6 * This file is released under the GPL.
9 #include <linux/completion.h>
10 #include <linux/err.h>
11 #include <linux/module.h>
12 #include <linux/init.h>
13 #include <linux/kernel.h>
14 #include <linux/bio.h>
15 #include <linux/blkdev.h>
16 #include <linux/mempool.h>
17 #include <linux/slab.h>
18 #include <linux/crypto.h>
19 #include <linux/workqueue.h>
20 #include <linux/backing-dev.h>
21 #include <linux/percpu.h>
22 #include <asm/atomic.h>
23 #include <linux/scatterlist.h>
25 #include <asm/unaligned.h>
27 #include <linux/device-mapper.h>
29 #define DM_MSG_PREFIX "crypt"
30 #define MESG_STR(x) x, sizeof(x)
33 * context holding the current state of a multi-part conversion
35 struct convert_context {
36 struct completion restart;
39 unsigned int offset_in;
40 unsigned int offset_out;
48 * per bio private data
51 struct dm_target *target;
53 struct work_struct work;
55 struct convert_context ctx;
60 struct dm_crypt_io *base_io;
63 struct dm_crypt_request {
64 struct convert_context *ctx;
65 struct scatterlist sg_in;
66 struct scatterlist sg_out;
72 struct crypt_iv_operations {
73 int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
75 void (*dtr)(struct crypt_config *cc);
76 int (*init)(struct crypt_config *cc);
77 int (*wipe)(struct crypt_config *cc);
78 int (*generator)(struct crypt_config *cc, u8 *iv,
79 struct dm_crypt_request *dmreq);
80 int (*post)(struct crypt_config *cc, u8 *iv,
81 struct dm_crypt_request *dmreq);
84 struct iv_essiv_private {
85 struct crypto_hash *hash_tfm;
89 struct iv_benbi_private {
94 * Crypt: maps a linear range of a block device
95 * and encrypts / decrypts at the same time.
97 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID };
100 * Duplicated per-CPU state for cipher.
103 struct ablkcipher_request *req;
104 /* ESSIV: struct crypto_cipher *essiv_tfm */
106 struct crypto_ablkcipher *tfms[0];
110 * The fields in here must be read only after initialization,
111 * changing state should be in crypt_cpu.
113 struct crypt_config {
118 * pool for per bio private data, crypto requests and
119 * encryption requeusts/buffer pages
123 mempool_t *page_pool;
126 struct workqueue_struct *io_queue;
127 struct workqueue_struct *crypt_queue;
132 struct crypt_iv_operations *iv_gen_ops;
134 struct iv_essiv_private essiv;
135 struct iv_benbi_private benbi;
138 unsigned int iv_size;
141 * Duplicated per cpu state. Access through
142 * per_cpu_ptr() only.
144 struct crypt_cpu __percpu *cpu;
148 * Layout of each crypto request:
150 * struct ablkcipher_request
153 * struct dm_crypt_request
157 * The padding is added so that dm_crypt_request and the IV are
160 unsigned int dmreq_start;
163 unsigned int key_size;
164 unsigned int key_parts;
169 #define MIN_POOL_PAGES 32
170 #define MIN_BIO_PAGES 8
172 static struct kmem_cache *_crypt_io_pool;
174 static void clone_init(struct dm_crypt_io *, struct bio *);
175 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
176 static u8 *iv_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq);
178 static struct crypt_cpu *this_crypt_config(struct crypt_config *cc)
180 return this_cpu_ptr(cc->cpu);
184 * Use this to access cipher attributes that are the same for each CPU.
186 static struct crypto_ablkcipher *any_tfm(struct crypt_config *cc)
188 return __this_cpu_ptr(cc->cpu)->tfms[0];
192 * Different IV generation algorithms:
194 * plain: the initial vector is the 32-bit little-endian version of the sector
195 * number, padded with zeros if necessary.
197 * plain64: the initial vector is the 64-bit little-endian version of the sector
198 * number, padded with zeros if necessary.
200 * essiv: "encrypted sector|salt initial vector", the sector number is
201 * encrypted with the bulk cipher using a salt as key. The salt
202 * should be derived from the bulk cipher's key via hashing.
204 * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
205 * (needed for LRW-32-AES and possible other narrow block modes)
207 * null: the initial vector is always zero. Provides compatibility with
208 * obsolete loop_fish2 devices. Do not use for new devices.
210 * plumb: unimplemented, see:
211 * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
214 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
215 struct dm_crypt_request *dmreq)
217 memset(iv, 0, cc->iv_size);
218 *(u32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
223 static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
224 struct dm_crypt_request *dmreq)
226 memset(iv, 0, cc->iv_size);
227 *(u64 *)iv = cpu_to_le64(dmreq->iv_sector);
232 /* Initialise ESSIV - compute salt but no local memory allocations */
233 static int crypt_iv_essiv_init(struct crypt_config *cc)
235 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
236 struct hash_desc desc;
237 struct scatterlist sg;
238 struct crypto_cipher *essiv_tfm;
241 sg_init_one(&sg, cc->key, cc->key_size);
242 desc.tfm = essiv->hash_tfm;
243 desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
245 err = crypto_hash_digest(&desc, &sg, cc->key_size, essiv->salt);
249 for_each_possible_cpu(cpu) {
250 essiv_tfm = per_cpu_ptr(cc->cpu, cpu)->iv_private,
252 err = crypto_cipher_setkey(essiv_tfm, essiv->salt,
253 crypto_hash_digestsize(essiv->hash_tfm));
261 /* Wipe salt and reset key derived from volume key */
262 static int crypt_iv_essiv_wipe(struct crypt_config *cc)
264 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
265 unsigned salt_size = crypto_hash_digestsize(essiv->hash_tfm);
266 struct crypto_cipher *essiv_tfm;
269 memset(essiv->salt, 0, salt_size);
271 for_each_possible_cpu(cpu) {
272 essiv_tfm = per_cpu_ptr(cc->cpu, cpu)->iv_private;
273 r = crypto_cipher_setkey(essiv_tfm, essiv->salt, salt_size);
281 /* Set up per cpu cipher state */
282 static struct crypto_cipher *setup_essiv_cpu(struct crypt_config *cc,
283 struct dm_target *ti,
284 u8 *salt, unsigned saltsize)
286 struct crypto_cipher *essiv_tfm;
289 /* Setup the essiv_tfm with the given salt */
290 essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
291 if (IS_ERR(essiv_tfm)) {
292 ti->error = "Error allocating crypto tfm for ESSIV";
296 if (crypto_cipher_blocksize(essiv_tfm) !=
297 crypto_ablkcipher_ivsize(any_tfm(cc))) {
298 ti->error = "Block size of ESSIV cipher does "
299 "not match IV size of block cipher";
300 crypto_free_cipher(essiv_tfm);
301 return ERR_PTR(-EINVAL);
304 err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
306 ti->error = "Failed to set key for ESSIV cipher";
307 crypto_free_cipher(essiv_tfm);
314 static void crypt_iv_essiv_dtr(struct crypt_config *cc)
317 struct crypt_cpu *cpu_cc;
318 struct crypto_cipher *essiv_tfm;
319 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
321 crypto_free_hash(essiv->hash_tfm);
322 essiv->hash_tfm = NULL;
327 for_each_possible_cpu(cpu) {
328 cpu_cc = per_cpu_ptr(cc->cpu, cpu);
329 essiv_tfm = cpu_cc->iv_private;
332 crypto_free_cipher(essiv_tfm);
334 cpu_cc->iv_private = NULL;
338 static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
341 struct crypto_cipher *essiv_tfm = NULL;
342 struct crypto_hash *hash_tfm = NULL;
347 ti->error = "Digest algorithm missing for ESSIV mode";
351 /* Allocate hash algorithm */
352 hash_tfm = crypto_alloc_hash(opts, 0, CRYPTO_ALG_ASYNC);
353 if (IS_ERR(hash_tfm)) {
354 ti->error = "Error initializing ESSIV hash";
355 err = PTR_ERR(hash_tfm);
359 salt = kzalloc(crypto_hash_digestsize(hash_tfm), GFP_KERNEL);
361 ti->error = "Error kmallocing salt storage in ESSIV";
366 cc->iv_gen_private.essiv.salt = salt;
367 cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
369 for_each_possible_cpu(cpu) {
370 essiv_tfm = setup_essiv_cpu(cc, ti, salt,
371 crypto_hash_digestsize(hash_tfm));
372 if (IS_ERR(essiv_tfm)) {
373 crypt_iv_essiv_dtr(cc);
374 return PTR_ERR(essiv_tfm);
376 per_cpu_ptr(cc->cpu, cpu)->iv_private = essiv_tfm;
382 if (hash_tfm && !IS_ERR(hash_tfm))
383 crypto_free_hash(hash_tfm);
388 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
389 struct dm_crypt_request *dmreq)
391 struct crypto_cipher *essiv_tfm = this_crypt_config(cc)->iv_private;
393 memset(iv, 0, cc->iv_size);
394 *(u64 *)iv = cpu_to_le64(dmreq->iv_sector);
395 crypto_cipher_encrypt_one(essiv_tfm, iv, iv);
400 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
403 unsigned bs = crypto_ablkcipher_blocksize(any_tfm(cc));
406 /* we need to calculate how far we must shift the sector count
407 * to get the cipher block count, we use this shift in _gen */
409 if (1 << log != bs) {
410 ti->error = "cypher blocksize is not a power of 2";
415 ti->error = "cypher blocksize is > 512";
419 cc->iv_gen_private.benbi.shift = 9 - log;
424 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
428 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
429 struct dm_crypt_request *dmreq)
433 memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
435 val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
436 put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
441 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
442 struct dm_crypt_request *dmreq)
444 memset(iv, 0, cc->iv_size);
449 static struct crypt_iv_operations crypt_iv_plain_ops = {
450 .generator = crypt_iv_plain_gen
453 static struct crypt_iv_operations crypt_iv_plain64_ops = {
454 .generator = crypt_iv_plain64_gen
457 static struct crypt_iv_operations crypt_iv_essiv_ops = {
458 .ctr = crypt_iv_essiv_ctr,
459 .dtr = crypt_iv_essiv_dtr,
460 .init = crypt_iv_essiv_init,
461 .wipe = crypt_iv_essiv_wipe,
462 .generator = crypt_iv_essiv_gen
465 static struct crypt_iv_operations crypt_iv_benbi_ops = {
466 .ctr = crypt_iv_benbi_ctr,
467 .dtr = crypt_iv_benbi_dtr,
468 .generator = crypt_iv_benbi_gen
471 static struct crypt_iv_operations crypt_iv_null_ops = {
472 .generator = crypt_iv_null_gen
475 static void crypt_convert_init(struct crypt_config *cc,
476 struct convert_context *ctx,
477 struct bio *bio_out, struct bio *bio_in,
480 ctx->bio_in = bio_in;
481 ctx->bio_out = bio_out;
484 ctx->idx_in = bio_in ? bio_in->bi_idx : 0;
485 ctx->idx_out = bio_out ? bio_out->bi_idx : 0;
486 ctx->sector = sector + cc->iv_offset;
487 init_completion(&ctx->restart);
490 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
491 struct ablkcipher_request *req)
493 return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
496 static struct ablkcipher_request *req_of_dmreq(struct crypt_config *cc,
497 struct dm_crypt_request *dmreq)
499 return (struct ablkcipher_request *)((char *)dmreq - cc->dmreq_start);
502 static u8 *iv_of_dmreq(struct crypt_config *cc,
503 struct dm_crypt_request *dmreq)
505 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
506 crypto_ablkcipher_alignmask(any_tfm(cc)) + 1);
509 static int crypt_convert_block(struct crypt_config *cc,
510 struct convert_context *ctx,
511 struct ablkcipher_request *req)
513 struct bio_vec *bv_in = bio_iovec_idx(ctx->bio_in, ctx->idx_in);
514 struct bio_vec *bv_out = bio_iovec_idx(ctx->bio_out, ctx->idx_out);
515 struct dm_crypt_request *dmreq;
519 dmreq = dmreq_of_req(cc, req);
520 iv = iv_of_dmreq(cc, dmreq);
522 dmreq->iv_sector = ctx->sector;
524 sg_init_table(&dmreq->sg_in, 1);
525 sg_set_page(&dmreq->sg_in, bv_in->bv_page, 1 << SECTOR_SHIFT,
526 bv_in->bv_offset + ctx->offset_in);
528 sg_init_table(&dmreq->sg_out, 1);
529 sg_set_page(&dmreq->sg_out, bv_out->bv_page, 1 << SECTOR_SHIFT,
530 bv_out->bv_offset + ctx->offset_out);
532 ctx->offset_in += 1 << SECTOR_SHIFT;
533 if (ctx->offset_in >= bv_in->bv_len) {
538 ctx->offset_out += 1 << SECTOR_SHIFT;
539 if (ctx->offset_out >= bv_out->bv_len) {
544 if (cc->iv_gen_ops) {
545 r = cc->iv_gen_ops->generator(cc, iv, dmreq);
550 ablkcipher_request_set_crypt(req, &dmreq->sg_in, &dmreq->sg_out,
551 1 << SECTOR_SHIFT, iv);
553 if (bio_data_dir(ctx->bio_in) == WRITE)
554 r = crypto_ablkcipher_encrypt(req);
556 r = crypto_ablkcipher_decrypt(req);
558 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
559 r = cc->iv_gen_ops->post(cc, iv, dmreq);
564 static void kcryptd_async_done(struct crypto_async_request *async_req,
567 static void crypt_alloc_req(struct crypt_config *cc,
568 struct convert_context *ctx)
570 struct crypt_cpu *this_cc = this_crypt_config(cc);
571 unsigned key_index = ctx->sector & (cc->tfms_count - 1);
574 this_cc->req = mempool_alloc(cc->req_pool, GFP_NOIO);
576 ablkcipher_request_set_tfm(this_cc->req, this_cc->tfms[key_index]);
577 ablkcipher_request_set_callback(this_cc->req,
578 CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
579 kcryptd_async_done, dmreq_of_req(cc, this_cc->req));
583 * Encrypt / decrypt data from one bio to another one (can be the same one)
585 static int crypt_convert(struct crypt_config *cc,
586 struct convert_context *ctx)
588 struct crypt_cpu *this_cc = this_crypt_config(cc);
591 atomic_set(&ctx->pending, 1);
593 while(ctx->idx_in < ctx->bio_in->bi_vcnt &&
594 ctx->idx_out < ctx->bio_out->bi_vcnt) {
596 crypt_alloc_req(cc, ctx);
598 atomic_inc(&ctx->pending);
600 r = crypt_convert_block(cc, ctx, this_cc->req);
605 wait_for_completion(&ctx->restart);
606 INIT_COMPLETION(ctx->restart);
615 atomic_dec(&ctx->pending);
622 atomic_dec(&ctx->pending);
630 static void dm_crypt_bio_destructor(struct bio *bio)
632 struct dm_crypt_io *io = bio->bi_private;
633 struct crypt_config *cc = io->target->private;
635 bio_free(bio, cc->bs);
639 * Generate a new unfragmented bio with the given size
640 * This should never violate the device limitations
641 * May return a smaller bio when running out of pages, indicated by
642 * *out_of_pages set to 1.
644 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size,
645 unsigned *out_of_pages)
647 struct crypt_config *cc = io->target->private;
649 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
650 gfp_t gfp_mask = GFP_NOIO | __GFP_HIGHMEM;
654 clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, cc->bs);
658 clone_init(io, clone);
661 for (i = 0; i < nr_iovecs; i++) {
662 page = mempool_alloc(cc->page_pool, gfp_mask);
669 * if additional pages cannot be allocated without waiting,
670 * return a partially allocated bio, the caller will then try
671 * to allocate additional bios while submitting this partial bio
673 if (i == (MIN_BIO_PAGES - 1))
674 gfp_mask = (gfp_mask | __GFP_NOWARN) & ~__GFP_WAIT;
676 len = (size > PAGE_SIZE) ? PAGE_SIZE : size;
678 if (!bio_add_page(clone, page, len, 0)) {
679 mempool_free(page, cc->page_pool);
686 if (!clone->bi_size) {
694 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
699 for (i = 0; i < clone->bi_vcnt; i++) {
700 bv = bio_iovec_idx(clone, i);
701 BUG_ON(!bv->bv_page);
702 mempool_free(bv->bv_page, cc->page_pool);
707 static struct dm_crypt_io *crypt_io_alloc(struct dm_target *ti,
708 struct bio *bio, sector_t sector)
710 struct crypt_config *cc = ti->private;
711 struct dm_crypt_io *io;
713 io = mempool_alloc(cc->io_pool, GFP_NOIO);
719 atomic_set(&io->pending, 0);
724 static void crypt_inc_pending(struct dm_crypt_io *io)
726 atomic_inc(&io->pending);
730 * One of the bios was finished. Check for completion of
731 * the whole request and correctly clean up the buffer.
732 * If base_io is set, wait for the last fragment to complete.
734 static void crypt_dec_pending(struct dm_crypt_io *io)
736 struct crypt_config *cc = io->target->private;
737 struct bio *base_bio = io->base_bio;
738 struct dm_crypt_io *base_io = io->base_io;
739 int error = io->error;
741 if (!atomic_dec_and_test(&io->pending))
744 mempool_free(io, cc->io_pool);
746 if (likely(!base_io))
747 bio_endio(base_bio, error);
749 if (error && !base_io->error)
750 base_io->error = error;
751 crypt_dec_pending(base_io);
756 * kcryptd/kcryptd_io:
758 * Needed because it would be very unwise to do decryption in an
761 * kcryptd performs the actual encryption or decryption.
763 * kcryptd_io performs the IO submission.
765 * They must be separated as otherwise the final stages could be
766 * starved by new requests which can block in the first stages due
767 * to memory allocation.
769 * The work is done per CPU global for all dm-crypt instances.
770 * They should not depend on each other and do not block.
772 static void crypt_endio(struct bio *clone, int error)
774 struct dm_crypt_io *io = clone->bi_private;
775 struct crypt_config *cc = io->target->private;
776 unsigned rw = bio_data_dir(clone);
778 if (unlikely(!bio_flagged(clone, BIO_UPTODATE) && !error))
782 * free the processed pages
785 crypt_free_buffer_pages(cc, clone);
789 if (rw == READ && !error) {
790 kcryptd_queue_crypt(io);
797 crypt_dec_pending(io);
800 static void clone_init(struct dm_crypt_io *io, struct bio *clone)
802 struct crypt_config *cc = io->target->private;
804 clone->bi_private = io;
805 clone->bi_end_io = crypt_endio;
806 clone->bi_bdev = cc->dev->bdev;
807 clone->bi_rw = io->base_bio->bi_rw;
808 clone->bi_destructor = dm_crypt_bio_destructor;
811 static void kcryptd_unplug(struct crypt_config *cc)
813 blk_unplug(bdev_get_queue(cc->dev->bdev));
816 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
818 struct crypt_config *cc = io->target->private;
819 struct bio *base_bio = io->base_bio;
823 * The block layer might modify the bvec array, so always
824 * copy the required bvecs because we need the original
825 * one in order to decrypt the whole bio data *afterwards*.
827 clone = bio_alloc_bioset(gfp, bio_segments(base_bio), cc->bs);
833 crypt_inc_pending(io);
835 clone_init(io, clone);
837 clone->bi_vcnt = bio_segments(base_bio);
838 clone->bi_size = base_bio->bi_size;
839 clone->bi_sector = cc->start + io->sector;
840 memcpy(clone->bi_io_vec, bio_iovec(base_bio),
841 sizeof(struct bio_vec) * clone->bi_vcnt);
843 generic_make_request(clone);
847 static void kcryptd_io_write(struct dm_crypt_io *io)
849 struct bio *clone = io->ctx.bio_out;
850 generic_make_request(clone);
853 static void kcryptd_io(struct work_struct *work)
855 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
857 if (bio_data_dir(io->base_bio) == READ) {
858 crypt_inc_pending(io);
859 if (kcryptd_io_read(io, GFP_NOIO))
861 crypt_dec_pending(io);
863 kcryptd_io_write(io);
866 static void kcryptd_queue_io(struct dm_crypt_io *io)
868 struct crypt_config *cc = io->target->private;
870 INIT_WORK(&io->work, kcryptd_io);
871 queue_work(cc->io_queue, &io->work);
874 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io,
875 int error, int async)
877 struct bio *clone = io->ctx.bio_out;
878 struct crypt_config *cc = io->target->private;
880 if (unlikely(error < 0)) {
881 crypt_free_buffer_pages(cc, clone);
884 crypt_dec_pending(io);
888 /* crypt_convert should have filled the clone bio */
889 BUG_ON(io->ctx.idx_out < clone->bi_vcnt);
891 clone->bi_sector = cc->start + io->sector;
894 kcryptd_queue_io(io);
896 generic_make_request(clone);
899 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
901 struct crypt_config *cc = io->target->private;
903 struct dm_crypt_io *new_io;
905 unsigned out_of_pages = 0;
906 unsigned remaining = io->base_bio->bi_size;
907 sector_t sector = io->sector;
911 * Prevent io from disappearing until this function completes.
913 crypt_inc_pending(io);
914 crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
917 * The allocated buffers can be smaller than the whole bio,
918 * so repeat the whole process until all the data can be handled.
921 clone = crypt_alloc_buffer(io, remaining, &out_of_pages);
922 if (unlikely(!clone)) {
927 io->ctx.bio_out = clone;
930 remaining -= clone->bi_size;
931 sector += bio_sectors(clone);
933 crypt_inc_pending(io);
934 r = crypt_convert(cc, &io->ctx);
935 crypt_finished = atomic_dec_and_test(&io->ctx.pending);
937 /* Encryption was already finished, submit io now */
938 if (crypt_finished) {
939 kcryptd_crypt_write_io_submit(io, r, 0);
942 * If there was an error, do not try next fragments.
943 * For async, error is processed in async handler.
952 * Out of memory -> run queues
953 * But don't wait if split was due to the io size restriction
955 if (unlikely(out_of_pages))
956 congestion_wait(BLK_RW_ASYNC, HZ/100);
959 * With async crypto it is unsafe to share the crypto context
960 * between fragments, so switch to a new dm_crypt_io structure.
962 if (unlikely(!crypt_finished && remaining)) {
963 new_io = crypt_io_alloc(io->target, io->base_bio,
965 crypt_inc_pending(new_io);
966 crypt_convert_init(cc, &new_io->ctx, NULL,
967 io->base_bio, sector);
968 new_io->ctx.idx_in = io->ctx.idx_in;
969 new_io->ctx.offset_in = io->ctx.offset_in;
972 * Fragments after the first use the base_io
976 new_io->base_io = io;
978 new_io->base_io = io->base_io;
979 crypt_inc_pending(io->base_io);
980 crypt_dec_pending(io);
987 crypt_dec_pending(io);
990 static void kcryptd_crypt_read_done(struct dm_crypt_io *io, int error)
992 if (unlikely(error < 0))
995 crypt_dec_pending(io);
998 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
1000 struct crypt_config *cc = io->target->private;
1003 crypt_inc_pending(io);
1005 crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
1008 r = crypt_convert(cc, &io->ctx);
1010 if (atomic_dec_and_test(&io->ctx.pending))
1011 kcryptd_crypt_read_done(io, r);
1013 crypt_dec_pending(io);
1016 static void kcryptd_async_done(struct crypto_async_request *async_req,
1019 struct dm_crypt_request *dmreq = async_req->data;
1020 struct convert_context *ctx = dmreq->ctx;
1021 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1022 struct crypt_config *cc = io->target->private;
1024 if (error == -EINPROGRESS) {
1025 complete(&ctx->restart);
1029 if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
1030 error = cc->iv_gen_ops->post(cc, iv_of_dmreq(cc, dmreq), dmreq);
1032 mempool_free(req_of_dmreq(cc, dmreq), cc->req_pool);
1034 if (!atomic_dec_and_test(&ctx->pending))
1037 if (bio_data_dir(io->base_bio) == READ)
1038 kcryptd_crypt_read_done(io, error);
1040 kcryptd_crypt_write_io_submit(io, error, 1);
1043 static void kcryptd_crypt(struct work_struct *work)
1045 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1047 if (bio_data_dir(io->base_bio) == READ)
1048 kcryptd_crypt_read_convert(io);
1050 kcryptd_crypt_write_convert(io);
1053 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
1055 struct crypt_config *cc = io->target->private;
1057 INIT_WORK(&io->work, kcryptd_crypt);
1058 queue_work(cc->crypt_queue, &io->work);
1062 * Decode key from its hex representation
1064 static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
1072 for (i = 0; i < size; i++) {
1076 key[i] = (u8)simple_strtoul(buffer, &endp, 16);
1078 if (endp != &buffer[2])
1089 * Encode key into its hex representation
1091 static void crypt_encode_key(char *hex, u8 *key, unsigned int size)
1095 for (i = 0; i < size; i++) {
1096 sprintf(hex, "%02x", *key);
1102 static void crypt_free_tfms(struct crypt_config *cc, int cpu)
1104 struct crypt_cpu *cpu_cc = per_cpu_ptr(cc->cpu, cpu);
1107 for (i = 0; i < cc->tfms_count; i++)
1108 if (cpu_cc->tfms[i] && !IS_ERR(cpu_cc->tfms[i])) {
1109 crypto_free_ablkcipher(cpu_cc->tfms[i]);
1110 cpu_cc->tfms[i] = NULL;
1114 static int crypt_alloc_tfms(struct crypt_config *cc, int cpu, char *ciphermode)
1116 struct crypt_cpu *cpu_cc = per_cpu_ptr(cc->cpu, cpu);
1120 for (i = 0; i < cc->tfms_count; i++) {
1121 cpu_cc->tfms[i] = crypto_alloc_ablkcipher(ciphermode, 0, 0);
1122 if (IS_ERR(cpu_cc->tfms[i])) {
1123 err = PTR_ERR(cpu_cc->tfms[i]);
1124 crypt_free_tfms(cc, cpu);
1132 static int crypt_setkey_allcpus(struct crypt_config *cc)
1134 unsigned subkey_size = cc->key_size >> ilog2(cc->tfms_count);
1135 int cpu, err = 0, i, r;
1137 for_each_possible_cpu(cpu) {
1138 for (i = 0; i < cc->tfms_count; i++) {
1139 r = crypto_ablkcipher_setkey(per_cpu_ptr(cc->cpu, cpu)->tfms[i],
1140 cc->key + (i * subkey_size), subkey_size);
1149 static int crypt_set_key(struct crypt_config *cc, char *key)
1151 /* The key size may not be changed. */
1152 if (cc->key_size != (strlen(key) >> 1))
1155 /* Hyphen (which gives a key_size of zero) means there is no key. */
1156 if (!cc->key_size && strcmp(key, "-"))
1159 if (cc->key_size && crypt_decode_key(cc->key, key, cc->key_size) < 0)
1162 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
1164 return crypt_setkey_allcpus(cc);
1167 static int crypt_wipe_key(struct crypt_config *cc)
1169 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
1170 memset(&cc->key, 0, cc->key_size * sizeof(u8));
1172 return crypt_setkey_allcpus(cc);
1175 static void crypt_dtr(struct dm_target *ti)
1177 struct crypt_config *cc = ti->private;
1178 struct crypt_cpu *cpu_cc;
1187 destroy_workqueue(cc->io_queue);
1188 if (cc->crypt_queue)
1189 destroy_workqueue(cc->crypt_queue);
1192 for_each_possible_cpu(cpu) {
1193 cpu_cc = per_cpu_ptr(cc->cpu, cpu);
1195 mempool_free(cpu_cc->req, cc->req_pool);
1196 crypt_free_tfms(cc, cpu);
1200 bioset_free(cc->bs);
1203 mempool_destroy(cc->page_pool);
1205 mempool_destroy(cc->req_pool);
1207 mempool_destroy(cc->io_pool);
1209 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
1210 cc->iv_gen_ops->dtr(cc);
1213 dm_put_device(ti, cc->dev);
1216 free_percpu(cc->cpu);
1219 kzfree(cc->cipher_string);
1221 /* Must zero key material before freeing */
1225 static int crypt_ctr_cipher(struct dm_target *ti,
1226 char *cipher_in, char *key)
1228 struct crypt_config *cc = ti->private;
1229 char *tmp, *cipher, *chainmode, *ivmode, *ivopts, *keycount;
1230 char *cipher_api = NULL;
1231 int cpu, ret = -EINVAL;
1233 /* Convert to crypto api definition? */
1234 if (strchr(cipher_in, '(')) {
1235 ti->error = "Bad cipher specification";
1239 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
1240 if (!cc->cipher_string)
1244 * Legacy dm-crypt cipher specification
1245 * cipher[:keycount]-mode-iv:ivopts
1248 keycount = strsep(&tmp, "-");
1249 cipher = strsep(&keycount, ":");
1253 else if (sscanf(keycount, "%u", &cc->tfms_count) != 1 ||
1254 !is_power_of_2(cc->tfms_count)) {
1255 ti->error = "Bad cipher key count specification";
1258 cc->key_parts = cc->tfms_count;
1260 cc->cipher = kstrdup(cipher, GFP_KERNEL);
1264 chainmode = strsep(&tmp, "-");
1265 ivopts = strsep(&tmp, "-");
1266 ivmode = strsep(&ivopts, ":");
1269 DMWARN("Ignoring unexpected additional cipher options");
1271 cc->cpu = __alloc_percpu(sizeof(*(cc->cpu)) +
1272 cc->tfms_count * sizeof(*(cc->cpu->tfms)),
1273 __alignof__(struct crypt_cpu));
1275 ti->error = "Cannot allocate per cpu state";
1280 * For compatibility with the original dm-crypt mapping format, if
1281 * only the cipher name is supplied, use cbc-plain.
1283 if (!chainmode || (!strcmp(chainmode, "plain") && !ivmode)) {
1288 if (strcmp(chainmode, "ecb") && !ivmode) {
1289 ti->error = "IV mechanism required";
1293 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
1297 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
1298 "%s(%s)", chainmode, cipher);
1304 /* Allocate cipher */
1305 for_each_possible_cpu(cpu) {
1306 ret = crypt_alloc_tfms(cc, cpu, cipher_api);
1308 ti->error = "Error allocating crypto tfm";
1313 /* Initialize and set key */
1314 ret = crypt_set_key(cc, key);
1316 ti->error = "Error decoding and setting key";
1321 cc->iv_size = crypto_ablkcipher_ivsize(any_tfm(cc));
1323 /* at least a 64 bit sector number should fit in our buffer */
1324 cc->iv_size = max(cc->iv_size,
1325 (unsigned int)(sizeof(u64) / sizeof(u8)));
1327 DMWARN("Selected cipher does not support IVs");
1331 /* Choose ivmode, see comments at iv code. */
1333 cc->iv_gen_ops = NULL;
1334 else if (strcmp(ivmode, "plain") == 0)
1335 cc->iv_gen_ops = &crypt_iv_plain_ops;
1336 else if (strcmp(ivmode, "plain64") == 0)
1337 cc->iv_gen_ops = &crypt_iv_plain64_ops;
1338 else if (strcmp(ivmode, "essiv") == 0)
1339 cc->iv_gen_ops = &crypt_iv_essiv_ops;
1340 else if (strcmp(ivmode, "benbi") == 0)
1341 cc->iv_gen_ops = &crypt_iv_benbi_ops;
1342 else if (strcmp(ivmode, "null") == 0)
1343 cc->iv_gen_ops = &crypt_iv_null_ops;
1346 ti->error = "Invalid IV mode";
1351 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
1352 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
1354 ti->error = "Error creating IV";
1359 /* Initialize IV (set keys for ESSIV etc) */
1360 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
1361 ret = cc->iv_gen_ops->init(cc);
1363 ti->error = "Error initialising IV";
1374 ti->error = "Cannot allocate cipher strings";
1379 * Construct an encryption mapping:
1380 * <cipher> <key> <iv_offset> <dev_path> <start>
1382 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
1384 struct crypt_config *cc;
1385 unsigned int key_size;
1386 unsigned long long tmpll;
1390 ti->error = "Not enough arguments";
1394 key_size = strlen(argv[1]) >> 1;
1396 cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
1398 ti->error = "Cannot allocate encryption context";
1401 cc->key_size = key_size;
1404 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
1409 cc->io_pool = mempool_create_slab_pool(MIN_IOS, _crypt_io_pool);
1411 ti->error = "Cannot allocate crypt io mempool";
1415 cc->dmreq_start = sizeof(struct ablkcipher_request);
1416 cc->dmreq_start += crypto_ablkcipher_reqsize(any_tfm(cc));
1417 cc->dmreq_start = ALIGN(cc->dmreq_start, crypto_tfm_ctx_alignment());
1418 cc->dmreq_start += crypto_ablkcipher_alignmask(any_tfm(cc)) &
1419 ~(crypto_tfm_ctx_alignment() - 1);
1421 cc->req_pool = mempool_create_kmalloc_pool(MIN_IOS, cc->dmreq_start +
1422 sizeof(struct dm_crypt_request) + cc->iv_size);
1423 if (!cc->req_pool) {
1424 ti->error = "Cannot allocate crypt request mempool";
1428 cc->page_pool = mempool_create_page_pool(MIN_POOL_PAGES, 0);
1429 if (!cc->page_pool) {
1430 ti->error = "Cannot allocate page mempool";
1434 cc->bs = bioset_create(MIN_IOS, 0);
1436 ti->error = "Cannot allocate crypt bioset";
1441 if (sscanf(argv[2], "%llu", &tmpll) != 1) {
1442 ti->error = "Invalid iv_offset sector";
1445 cc->iv_offset = tmpll;
1447 if (dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev)) {
1448 ti->error = "Device lookup failed";
1452 if (sscanf(argv[4], "%llu", &tmpll) != 1) {
1453 ti->error = "Invalid device sector";
1459 cc->io_queue = alloc_workqueue("kcryptd_io",
1463 if (!cc->io_queue) {
1464 ti->error = "Couldn't create kcryptd io queue";
1468 cc->crypt_queue = alloc_workqueue("kcryptd",
1473 if (!cc->crypt_queue) {
1474 ti->error = "Couldn't create kcryptd queue";
1478 ti->num_flush_requests = 1;
1486 static int crypt_map(struct dm_target *ti, struct bio *bio,
1487 union map_info *map_context)
1489 struct dm_crypt_io *io;
1490 struct crypt_config *cc;
1492 if (bio->bi_rw & REQ_FLUSH) {
1494 bio->bi_bdev = cc->dev->bdev;
1495 return DM_MAPIO_REMAPPED;
1498 io = crypt_io_alloc(ti, bio, dm_target_offset(ti, bio->bi_sector));
1500 if (bio_data_dir(io->base_bio) == READ) {
1501 if (kcryptd_io_read(io, GFP_NOWAIT))
1502 kcryptd_queue_io(io);
1504 kcryptd_queue_crypt(io);
1506 return DM_MAPIO_SUBMITTED;
1509 static int crypt_status(struct dm_target *ti, status_type_t type,
1510 char *result, unsigned int maxlen)
1512 struct crypt_config *cc = ti->private;
1513 unsigned int sz = 0;
1516 case STATUSTYPE_INFO:
1520 case STATUSTYPE_TABLE:
1521 DMEMIT("%s ", cc->cipher_string);
1523 if (cc->key_size > 0) {
1524 if ((maxlen - sz) < ((cc->key_size << 1) + 1))
1527 crypt_encode_key(result + sz, cc->key, cc->key_size);
1528 sz += cc->key_size << 1;
1535 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
1536 cc->dev->name, (unsigned long long)cc->start);
1542 static void crypt_postsuspend(struct dm_target *ti)
1544 struct crypt_config *cc = ti->private;
1546 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
1549 static int crypt_preresume(struct dm_target *ti)
1551 struct crypt_config *cc = ti->private;
1553 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
1554 DMERR("aborting resume - crypt key is not set.");
1561 static void crypt_resume(struct dm_target *ti)
1563 struct crypt_config *cc = ti->private;
1565 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
1568 /* Message interface
1572 static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
1574 struct crypt_config *cc = ti->private;
1580 if (!strnicmp(argv[0], MESG_STR("key"))) {
1581 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
1582 DMWARN("not suspended during key manipulation.");
1585 if (argc == 3 && !strnicmp(argv[1], MESG_STR("set"))) {
1586 ret = crypt_set_key(cc, argv[2]);
1589 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
1590 ret = cc->iv_gen_ops->init(cc);
1593 if (argc == 2 && !strnicmp(argv[1], MESG_STR("wipe"))) {
1594 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
1595 ret = cc->iv_gen_ops->wipe(cc);
1599 return crypt_wipe_key(cc);
1604 DMWARN("unrecognised message received.");
1608 static int crypt_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
1609 struct bio_vec *biovec, int max_size)
1611 struct crypt_config *cc = ti->private;
1612 struct request_queue *q = bdev_get_queue(cc->dev->bdev);
1614 if (!q->merge_bvec_fn)
1617 bvm->bi_bdev = cc->dev->bdev;
1618 bvm->bi_sector = cc->start + dm_target_offset(ti, bvm->bi_sector);
1620 return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
1623 static int crypt_iterate_devices(struct dm_target *ti,
1624 iterate_devices_callout_fn fn, void *data)
1626 struct crypt_config *cc = ti->private;
1628 return fn(ti, cc->dev, cc->start, ti->len, data);
1631 static struct target_type crypt_target = {
1633 .version = {1, 10, 0},
1634 .module = THIS_MODULE,
1638 .status = crypt_status,
1639 .postsuspend = crypt_postsuspend,
1640 .preresume = crypt_preresume,
1641 .resume = crypt_resume,
1642 .message = crypt_message,
1643 .merge = crypt_merge,
1644 .iterate_devices = crypt_iterate_devices,
1647 static int __init dm_crypt_init(void)
1651 _crypt_io_pool = KMEM_CACHE(dm_crypt_io, 0);
1652 if (!_crypt_io_pool)
1655 r = dm_register_target(&crypt_target);
1657 DMERR("register failed %d", r);
1658 kmem_cache_destroy(_crypt_io_pool);
1664 static void __exit dm_crypt_exit(void)
1666 dm_unregister_target(&crypt_target);
1667 kmem_cache_destroy(_crypt_io_pool);
1670 module_init(dm_crypt_init);
1671 module_exit(dm_crypt_exit);
1673 MODULE_AUTHOR("Christophe Saout <christophe@saout.de>");
1674 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
1675 MODULE_LICENSE("GPL");