dm-crypt.c 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  1. /*
  2. * Copyright (C) 2003 Christophe Saout <christophe@saout.de>
  3. * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
  4. * Copyright (C) 2006-2007 Red Hat, Inc. All rights reserved.
  5. *
  6. * This file is released under the GPL.
  7. */
  8. #include <linux/err.h>
  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 <linux/backing-dev.h>
  19. #include <asm/atomic.h>
  20. #include <linux/scatterlist.h>
  21. #include <asm/page.h>
  22. #include <asm/unaligned.h>
  23. #include "dm.h"
  24. #define DM_MSG_PREFIX "crypt"
  25. #define MESG_STR(x) x, sizeof(x)
  26. /*
  27. * context holding the current state of a multi-part conversion
  28. */
  29. struct convert_context {
  30. struct bio *bio_in;
  31. struct bio *bio_out;
  32. unsigned int offset_in;
  33. unsigned int offset_out;
  34. unsigned int idx_in;
  35. unsigned int idx_out;
  36. sector_t sector;
  37. };
  38. /*
  39. * per bio private data
  40. */
  41. struct dm_crypt_io {
  42. struct dm_target *target;
  43. struct bio *base_bio;
  44. struct work_struct work;
  45. struct convert_context ctx;
  46. atomic_t pending;
  47. int error;
  48. sector_t sector;
  49. };
  50. struct crypt_config;
  51. struct crypt_iv_operations {
  52. int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
  53. const char *opts);
  54. void (*dtr)(struct crypt_config *cc);
  55. const char *(*status)(struct crypt_config *cc);
  56. int (*generator)(struct crypt_config *cc, u8 *iv, sector_t sector);
  57. };
  58. /*
  59. * Crypt: maps a linear range of a block device
  60. * and encrypts / decrypts at the same time.
  61. */
  62. enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID };
  63. struct crypt_config {
  64. struct dm_dev *dev;
  65. sector_t start;
  66. /*
  67. * pool for per bio private data and
  68. * for encryption buffer pages
  69. */
  70. mempool_t *io_pool;
  71. mempool_t *page_pool;
  72. struct bio_set *bs;
  73. struct workqueue_struct *io_queue;
  74. struct workqueue_struct *crypt_queue;
  75. /*
  76. * crypto related data
  77. */
  78. struct crypt_iv_operations *iv_gen_ops;
  79. char *iv_mode;
  80. union {
  81. struct crypto_cipher *essiv_tfm;
  82. int benbi_shift;
  83. } iv_gen_private;
  84. sector_t iv_offset;
  85. unsigned int iv_size;
  86. char cipher[CRYPTO_MAX_ALG_NAME];
  87. char chainmode[CRYPTO_MAX_ALG_NAME];
  88. struct crypto_blkcipher *tfm;
  89. unsigned long flags;
  90. unsigned int key_size;
  91. u8 key[0];
  92. };
  93. #define MIN_IOS 16
  94. #define MIN_POOL_PAGES 32
  95. #define MIN_BIO_PAGES 8
  96. static struct kmem_cache *_crypt_io_pool;
  97. static void clone_init(struct dm_crypt_io *, struct bio *);
  98. static void kcryptd_queue_crypt(struct dm_crypt_io *io);
  99. /*
  100. * Different IV generation algorithms:
  101. *
  102. * plain: the initial vector is the 32-bit little-endian version of the sector
  103. * number, padded with zeros if necessary.
  104. *
  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.
  108. *
  109. * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
  110. * (needed for LRW-32-AES and possible other narrow block modes)
  111. *
  112. * null: the initial vector is always zero. Provides compatibility with
  113. * obsolete loop_fish2 devices. Do not use for new devices.
  114. *
  115. * plumb: unimplemented, see:
  116. * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
  117. */
  118. static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
  119. {
  120. memset(iv, 0, cc->iv_size);
  121. *(u32 *)iv = cpu_to_le32(sector & 0xffffffff);
  122. return 0;
  123. }
  124. static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
  125. const char *opts)
  126. {
  127. struct crypto_cipher *essiv_tfm;
  128. struct crypto_hash *hash_tfm;
  129. struct hash_desc desc;
  130. struct scatterlist sg;
  131. unsigned int saltsize;
  132. u8 *salt;
  133. int err;
  134. if (opts == NULL) {
  135. ti->error = "Digest algorithm missing for ESSIV mode";
  136. return -EINVAL;
  137. }
  138. /* Hash the cipher key with the given hash algorithm */
  139. hash_tfm = crypto_alloc_hash(opts, 0, CRYPTO_ALG_ASYNC);
  140. if (IS_ERR(hash_tfm)) {
  141. ti->error = "Error initializing ESSIV hash";
  142. return PTR_ERR(hash_tfm);
  143. }
  144. saltsize = crypto_hash_digestsize(hash_tfm);
  145. salt = kmalloc(saltsize, GFP_KERNEL);
  146. if (salt == NULL) {
  147. ti->error = "Error kmallocing salt storage in ESSIV";
  148. crypto_free_hash(hash_tfm);
  149. return -ENOMEM;
  150. }
  151. sg_init_one(&sg, cc->key, cc->key_size);
  152. desc.tfm = hash_tfm;
  153. desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
  154. err = crypto_hash_digest(&desc, &sg, cc->key_size, salt);
  155. crypto_free_hash(hash_tfm);
  156. if (err) {
  157. ti->error = "Error calculating hash in ESSIV";
  158. kfree(salt);
  159. return err;
  160. }
  161. /* Setup the essiv_tfm with the given salt */
  162. essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
  163. if (IS_ERR(essiv_tfm)) {
  164. ti->error = "Error allocating crypto tfm for ESSIV";
  165. kfree(salt);
  166. return PTR_ERR(essiv_tfm);
  167. }
  168. if (crypto_cipher_blocksize(essiv_tfm) !=
  169. crypto_blkcipher_ivsize(cc->tfm)) {
  170. ti->error = "Block size of ESSIV cipher does "
  171. "not match IV size of block cipher";
  172. crypto_free_cipher(essiv_tfm);
  173. kfree(salt);
  174. return -EINVAL;
  175. }
  176. err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
  177. if (err) {
  178. ti->error = "Failed to set key for ESSIV cipher";
  179. crypto_free_cipher(essiv_tfm);
  180. kfree(salt);
  181. return err;
  182. }
  183. kfree(salt);
  184. cc->iv_gen_private.essiv_tfm = essiv_tfm;
  185. return 0;
  186. }
  187. static void crypt_iv_essiv_dtr(struct crypt_config *cc)
  188. {
  189. crypto_free_cipher(cc->iv_gen_private.essiv_tfm);
  190. cc->iv_gen_private.essiv_tfm = NULL;
  191. }
  192. static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
  193. {
  194. memset(iv, 0, cc->iv_size);
  195. *(u64 *)iv = cpu_to_le64(sector);
  196. crypto_cipher_encrypt_one(cc->iv_gen_private.essiv_tfm, iv, iv);
  197. return 0;
  198. }
  199. static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
  200. const char *opts)
  201. {
  202. unsigned int bs = crypto_blkcipher_blocksize(cc->tfm);
  203. int log = ilog2(bs);
  204. /* we need to calculate how far we must shift the sector count
  205. * to get the cipher block count, we use this shift in _gen */
  206. if (1 << log != bs) {
  207. ti->error = "cypher blocksize is not a power of 2";
  208. return -EINVAL;
  209. }
  210. if (log > 9) {
  211. ti->error = "cypher blocksize is > 512";
  212. return -EINVAL;
  213. }
  214. cc->iv_gen_private.benbi_shift = 9 - log;
  215. return 0;
  216. }
  217. static void crypt_iv_benbi_dtr(struct crypt_config *cc)
  218. {
  219. }
  220. static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
  221. {
  222. __be64 val;
  223. memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
  224. val = cpu_to_be64(((u64)sector << cc->iv_gen_private.benbi_shift) + 1);
  225. put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
  226. return 0;
  227. }
  228. static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
  229. {
  230. memset(iv, 0, cc->iv_size);
  231. return 0;
  232. }
  233. static struct crypt_iv_operations crypt_iv_plain_ops = {
  234. .generator = crypt_iv_plain_gen
  235. };
  236. static struct crypt_iv_operations crypt_iv_essiv_ops = {
  237. .ctr = crypt_iv_essiv_ctr,
  238. .dtr = crypt_iv_essiv_dtr,
  239. .generator = crypt_iv_essiv_gen
  240. };
  241. static struct crypt_iv_operations crypt_iv_benbi_ops = {
  242. .ctr = crypt_iv_benbi_ctr,
  243. .dtr = crypt_iv_benbi_dtr,
  244. .generator = crypt_iv_benbi_gen
  245. };
  246. static struct crypt_iv_operations crypt_iv_null_ops = {
  247. .generator = crypt_iv_null_gen
  248. };
  249. static int
  250. crypt_convert_scatterlist(struct crypt_config *cc, struct scatterlist *out,
  251. struct scatterlist *in, unsigned int length,
  252. int write, sector_t sector)
  253. {
  254. u8 iv[cc->iv_size] __attribute__ ((aligned(__alignof__(u64))));
  255. struct blkcipher_desc desc = {
  256. .tfm = cc->tfm,
  257. .info = iv,
  258. .flags = CRYPTO_TFM_REQ_MAY_SLEEP,
  259. };
  260. int r;
  261. if (cc->iv_gen_ops) {
  262. r = cc->iv_gen_ops->generator(cc, iv, sector);
  263. if (r < 0)
  264. return r;
  265. if (write)
  266. r = crypto_blkcipher_encrypt_iv(&desc, out, in, length);
  267. else
  268. r = crypto_blkcipher_decrypt_iv(&desc, out, in, length);
  269. } else {
  270. if (write)
  271. r = crypto_blkcipher_encrypt(&desc, out, in, length);
  272. else
  273. r = crypto_blkcipher_decrypt(&desc, out, in, length);
  274. }
  275. return r;
  276. }
  277. static void crypt_convert_init(struct crypt_config *cc,
  278. struct convert_context *ctx,
  279. struct bio *bio_out, struct bio *bio_in,
  280. sector_t sector)
  281. {
  282. ctx->bio_in = bio_in;
  283. ctx->bio_out = bio_out;
  284. ctx->offset_in = 0;
  285. ctx->offset_out = 0;
  286. ctx->idx_in = bio_in ? bio_in->bi_idx : 0;
  287. ctx->idx_out = bio_out ? bio_out->bi_idx : 0;
  288. ctx->sector = sector + cc->iv_offset;
  289. }
  290. /*
  291. * Encrypt / decrypt data from one bio to another one (can be the same one)
  292. */
  293. static int crypt_convert(struct crypt_config *cc,
  294. struct convert_context *ctx)
  295. {
  296. int r = 0;
  297. while(ctx->idx_in < ctx->bio_in->bi_vcnt &&
  298. ctx->idx_out < ctx->bio_out->bi_vcnt) {
  299. struct bio_vec *bv_in = bio_iovec_idx(ctx->bio_in, ctx->idx_in);
  300. struct bio_vec *bv_out = bio_iovec_idx(ctx->bio_out, ctx->idx_out);
  301. struct scatterlist sg_in, sg_out;
  302. sg_init_table(&sg_in, 1);
  303. sg_set_page(&sg_in, bv_in->bv_page, 1 << SECTOR_SHIFT, bv_in->bv_offset + ctx->offset_in);
  304. sg_init_table(&sg_out, 1);
  305. sg_set_page(&sg_out, bv_out->bv_page, 1 << SECTOR_SHIFT, bv_out->bv_offset + ctx->offset_out);
  306. ctx->offset_in += sg_in.length;
  307. if (ctx->offset_in >= bv_in->bv_len) {
  308. ctx->offset_in = 0;
  309. ctx->idx_in++;
  310. }
  311. ctx->offset_out += sg_out.length;
  312. if (ctx->offset_out >= bv_out->bv_len) {
  313. ctx->offset_out = 0;
  314. ctx->idx_out++;
  315. }
  316. r = crypt_convert_scatterlist(cc, &sg_out, &sg_in, sg_in.length,
  317. bio_data_dir(ctx->bio_in) == WRITE, ctx->sector);
  318. if (r < 0)
  319. break;
  320. ctx->sector++;
  321. }
  322. return r;
  323. }
  324. static void dm_crypt_bio_destructor(struct bio *bio)
  325. {
  326. struct dm_crypt_io *io = bio->bi_private;
  327. struct crypt_config *cc = io->target->private;
  328. bio_free(bio, cc->bs);
  329. }
  330. /*
  331. * Generate a new unfragmented bio with the given size
  332. * This should never violate the device limitations
  333. * May return a smaller bio when running out of pages
  334. */
  335. static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
  336. {
  337. struct crypt_config *cc = io->target->private;
  338. struct bio *clone;
  339. unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
  340. gfp_t gfp_mask = GFP_NOIO | __GFP_HIGHMEM;
  341. unsigned i, len;
  342. struct page *page;
  343. clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, cc->bs);
  344. if (!clone)
  345. return NULL;
  346. clone_init(io, clone);
  347. for (i = 0; i < nr_iovecs; i++) {
  348. page = mempool_alloc(cc->page_pool, gfp_mask);
  349. if (!page)
  350. break;
  351. /*
  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
  355. */
  356. if (i == (MIN_BIO_PAGES - 1))
  357. gfp_mask = (gfp_mask | __GFP_NOWARN) & ~__GFP_WAIT;
  358. len = (size > PAGE_SIZE) ? PAGE_SIZE : size;
  359. if (!bio_add_page(clone, page, len, 0)) {
  360. mempool_free(page, cc->page_pool);
  361. break;
  362. }
  363. size -= len;
  364. }
  365. if (!clone->bi_size) {
  366. bio_put(clone);
  367. return NULL;
  368. }
  369. return clone;
  370. }
  371. static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
  372. {
  373. unsigned int i;
  374. struct bio_vec *bv;
  375. for (i = 0; i < clone->bi_vcnt; i++) {
  376. bv = bio_iovec_idx(clone, i);
  377. BUG_ON(!bv->bv_page);
  378. mempool_free(bv->bv_page, cc->page_pool);
  379. bv->bv_page = NULL;
  380. }
  381. }
  382. /*
  383. * One of the bios was finished. Check for completion of
  384. * the whole request and correctly clean up the buffer.
  385. */
  386. static void crypt_dec_pending(struct dm_crypt_io *io)
  387. {
  388. struct crypt_config *cc = io->target->private;
  389. if (!atomic_dec_and_test(&io->pending))
  390. return;
  391. bio_endio(io->base_bio, io->error);
  392. mempool_free(io, cc->io_pool);
  393. }
  394. /*
  395. * kcryptd/kcryptd_io:
  396. *
  397. * Needed because it would be very unwise to do decryption in an
  398. * interrupt context.
  399. *
  400. * kcryptd performs the actual encryption or decryption.
  401. *
  402. * kcryptd_io performs the IO submission.
  403. *
  404. * They must be separated as otherwise the final stages could be
  405. * starved by new requests which can block in the first stages due
  406. * to memory allocation.
  407. */
  408. static void crypt_endio(struct bio *clone, int error)
  409. {
  410. struct dm_crypt_io *io = clone->bi_private;
  411. struct crypt_config *cc = io->target->private;
  412. unsigned rw = bio_data_dir(clone);
  413. if (unlikely(!bio_flagged(clone, BIO_UPTODATE) && !error))
  414. error = -EIO;
  415. /*
  416. * free the processed pages
  417. */
  418. if (rw == WRITE)
  419. crypt_free_buffer_pages(cc, clone);
  420. bio_put(clone);
  421. if (rw == READ && !error) {
  422. kcryptd_queue_crypt(io);
  423. return;
  424. }
  425. if (unlikely(error))
  426. io->error = error;
  427. crypt_dec_pending(io);
  428. }
  429. static void clone_init(struct dm_crypt_io *io, struct bio *clone)
  430. {
  431. struct crypt_config *cc = io->target->private;
  432. clone->bi_private = io;
  433. clone->bi_end_io = crypt_endio;
  434. clone->bi_bdev = cc->dev->bdev;
  435. clone->bi_rw = io->base_bio->bi_rw;
  436. clone->bi_destructor = dm_crypt_bio_destructor;
  437. }
  438. static void kcryptd_io_read(struct dm_crypt_io *io)
  439. {
  440. struct crypt_config *cc = io->target->private;
  441. struct bio *base_bio = io->base_bio;
  442. struct bio *clone;
  443. atomic_inc(&io->pending);
  444. /*
  445. * The block layer might modify the bvec array, so always
  446. * copy the required bvecs because we need the original
  447. * one in order to decrypt the whole bio data *afterwards*.
  448. */
  449. clone = bio_alloc_bioset(GFP_NOIO, bio_segments(base_bio), cc->bs);
  450. if (unlikely(!clone)) {
  451. io->error = -ENOMEM;
  452. crypt_dec_pending(io);
  453. return;
  454. }
  455. clone_init(io, clone);
  456. clone->bi_idx = 0;
  457. clone->bi_vcnt = bio_segments(base_bio);
  458. clone->bi_size = base_bio->bi_size;
  459. clone->bi_sector = cc->start + io->sector;
  460. memcpy(clone->bi_io_vec, bio_iovec(base_bio),
  461. sizeof(struct bio_vec) * clone->bi_vcnt);
  462. generic_make_request(clone);
  463. }
  464. static void kcryptd_io_write(struct dm_crypt_io *io)
  465. {
  466. }
  467. static void kcryptd_io(struct work_struct *work)
  468. {
  469. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  470. if (bio_data_dir(io->base_bio) == READ)
  471. kcryptd_io_read(io);
  472. else
  473. kcryptd_io_write(io);
  474. }
  475. static void kcryptd_queue_io(struct dm_crypt_io *io)
  476. {
  477. struct crypt_config *cc = io->target->private;
  478. INIT_WORK(&io->work, kcryptd_io);
  479. queue_work(cc->io_queue, &io->work);
  480. }
  481. static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int error)
  482. {
  483. struct bio *clone = io->ctx.bio_out;
  484. struct crypt_config *cc = io->target->private;
  485. if (unlikely(error < 0)) {
  486. crypt_free_buffer_pages(cc, clone);
  487. bio_put(clone);
  488. io->error = -EIO;
  489. return;
  490. }
  491. /* crypt_convert should have filled the clone bio */
  492. BUG_ON(io->ctx.idx_out < clone->bi_vcnt);
  493. clone->bi_sector = cc->start + io->sector;
  494. io->sector += bio_sectors(clone);
  495. atomic_inc(&io->pending);
  496. generic_make_request(clone);
  497. }
  498. static void kcryptd_crypt_write_convert_loop(struct dm_crypt_io *io)
  499. {
  500. struct crypt_config *cc = io->target->private;
  501. struct bio *clone;
  502. unsigned remaining = io->base_bio->bi_size;
  503. int r;
  504. /*
  505. * The allocated buffers can be smaller than the whole bio,
  506. * so repeat the whole process until all the data can be handled.
  507. */
  508. while (remaining) {
  509. clone = crypt_alloc_buffer(io, remaining);
  510. if (unlikely(!clone)) {
  511. io->error = -ENOMEM;
  512. return;
  513. }
  514. io->ctx.bio_out = clone;
  515. io->ctx.idx_out = 0;
  516. remaining -= clone->bi_size;
  517. r = crypt_convert(cc, &io->ctx);
  518. kcryptd_crypt_write_io_submit(io, r);
  519. if (unlikely(r < 0))
  520. return;
  521. /* out of memory -> run queues */
  522. if (unlikely(remaining))
  523. congestion_wait(WRITE, HZ/100);
  524. }
  525. }
  526. static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
  527. {
  528. struct crypt_config *cc = io->target->private;
  529. /*
  530. * Prevent io from disappearing until this function completes.
  531. */
  532. atomic_inc(&io->pending);
  533. crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, io->sector);
  534. kcryptd_crypt_write_convert_loop(io);
  535. crypt_dec_pending(io);
  536. }
  537. static void kcryptd_crypt_read_done(struct dm_crypt_io *io, int error)
  538. {
  539. if (unlikely(error < 0))
  540. io->error = -EIO;
  541. crypt_dec_pending(io);
  542. }
  543. static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
  544. {
  545. struct crypt_config *cc = io->target->private;
  546. int r = 0;
  547. crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
  548. io->sector);
  549. r = crypt_convert(cc, &io->ctx);
  550. kcryptd_crypt_read_done(io, r);
  551. }
  552. static void kcryptd_crypt(struct work_struct *work)
  553. {
  554. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  555. if (bio_data_dir(io->base_bio) == READ)
  556. kcryptd_crypt_read_convert(io);
  557. else
  558. kcryptd_crypt_write_convert(io);
  559. }
  560. static void kcryptd_queue_crypt(struct dm_crypt_io *io)
  561. {
  562. struct crypt_config *cc = io->target->private;
  563. INIT_WORK(&io->work, kcryptd_crypt);
  564. queue_work(cc->crypt_queue, &io->work);
  565. }
  566. /*
  567. * Decode key from its hex representation
  568. */
  569. static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
  570. {
  571. char buffer[3];
  572. char *endp;
  573. unsigned int i;
  574. buffer[2] = '\0';
  575. for (i = 0; i < size; i++) {
  576. buffer[0] = *hex++;
  577. buffer[1] = *hex++;
  578. key[i] = (u8)simple_strtoul(buffer, &endp, 16);
  579. if (endp != &buffer[2])
  580. return -EINVAL;
  581. }
  582. if (*hex != '\0')
  583. return -EINVAL;
  584. return 0;
  585. }
  586. /*
  587. * Encode key into its hex representation
  588. */
  589. static void crypt_encode_key(char *hex, u8 *key, unsigned int size)
  590. {
  591. unsigned int i;
  592. for (i = 0; i < size; i++) {
  593. sprintf(hex, "%02x", *key);
  594. hex += 2;
  595. key++;
  596. }
  597. }
  598. static int crypt_set_key(struct crypt_config *cc, char *key)
  599. {
  600. unsigned key_size = strlen(key) >> 1;
  601. if (cc->key_size && cc->key_size != key_size)
  602. return -EINVAL;
  603. cc->key_size = key_size; /* initial settings */
  604. if ((!key_size && strcmp(key, "-")) ||
  605. (key_size && crypt_decode_key(cc->key, key, key_size) < 0))
  606. return -EINVAL;
  607. set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  608. return 0;
  609. }
  610. static int crypt_wipe_key(struct crypt_config *cc)
  611. {
  612. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  613. memset(&cc->key, 0, cc->key_size * sizeof(u8));
  614. return 0;
  615. }
  616. /*
  617. * Construct an encryption mapping:
  618. * <cipher> <key> <iv_offset> <dev_path> <start>
  619. */
  620. static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
  621. {
  622. struct crypt_config *cc;
  623. struct crypto_blkcipher *tfm;
  624. char *tmp;
  625. char *cipher;
  626. char *chainmode;
  627. char *ivmode;
  628. char *ivopts;
  629. unsigned int key_size;
  630. unsigned long long tmpll;
  631. if (argc != 5) {
  632. ti->error = "Not enough arguments";
  633. return -EINVAL;
  634. }
  635. tmp = argv[0];
  636. cipher = strsep(&tmp, "-");
  637. chainmode = strsep(&tmp, "-");
  638. ivopts = strsep(&tmp, "-");
  639. ivmode = strsep(&ivopts, ":");
  640. if (tmp)
  641. DMWARN("Unexpected additional cipher options");
  642. key_size = strlen(argv[1]) >> 1;
  643. cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
  644. if (cc == NULL) {
  645. ti->error =
  646. "Cannot allocate transparent encryption context";
  647. return -ENOMEM;
  648. }
  649. if (crypt_set_key(cc, argv[1])) {
  650. ti->error = "Error decoding key";
  651. goto bad_cipher;
  652. }
  653. /* Compatiblity mode for old dm-crypt cipher strings */
  654. if (!chainmode || (strcmp(chainmode, "plain") == 0 && !ivmode)) {
  655. chainmode = "cbc";
  656. ivmode = "plain";
  657. }
  658. if (strcmp(chainmode, "ecb") && !ivmode) {
  659. ti->error = "This chaining mode requires an IV mechanism";
  660. goto bad_cipher;
  661. }
  662. if (snprintf(cc->cipher, CRYPTO_MAX_ALG_NAME, "%s(%s)",
  663. chainmode, cipher) >= CRYPTO_MAX_ALG_NAME) {
  664. ti->error = "Chain mode + cipher name is too long";
  665. goto bad_cipher;
  666. }
  667. tfm = crypto_alloc_blkcipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
  668. if (IS_ERR(tfm)) {
  669. ti->error = "Error allocating crypto tfm";
  670. goto bad_cipher;
  671. }
  672. strcpy(cc->cipher, cipher);
  673. strcpy(cc->chainmode, chainmode);
  674. cc->tfm = tfm;
  675. /*
  676. * Choose ivmode. Valid modes: "plain", "essiv:<esshash>", "benbi".
  677. * See comments at iv code
  678. */
  679. if (ivmode == NULL)
  680. cc->iv_gen_ops = NULL;
  681. else if (strcmp(ivmode, "plain") == 0)
  682. cc->iv_gen_ops = &crypt_iv_plain_ops;
  683. else if (strcmp(ivmode, "essiv") == 0)
  684. cc->iv_gen_ops = &crypt_iv_essiv_ops;
  685. else if (strcmp(ivmode, "benbi") == 0)
  686. cc->iv_gen_ops = &crypt_iv_benbi_ops;
  687. else if (strcmp(ivmode, "null") == 0)
  688. cc->iv_gen_ops = &crypt_iv_null_ops;
  689. else {
  690. ti->error = "Invalid IV mode";
  691. goto bad_ivmode;
  692. }
  693. if (cc->iv_gen_ops && cc->iv_gen_ops->ctr &&
  694. cc->iv_gen_ops->ctr(cc, ti, ivopts) < 0)
  695. goto bad_ivmode;
  696. cc->iv_size = crypto_blkcipher_ivsize(tfm);
  697. if (cc->iv_size)
  698. /* at least a 64 bit sector number should fit in our buffer */
  699. cc->iv_size = max(cc->iv_size,
  700. (unsigned int)(sizeof(u64) / sizeof(u8)));
  701. else {
  702. if (cc->iv_gen_ops) {
  703. DMWARN("Selected cipher does not support IVs");
  704. if (cc->iv_gen_ops->dtr)
  705. cc->iv_gen_ops->dtr(cc);
  706. cc->iv_gen_ops = NULL;
  707. }
  708. }
  709. cc->io_pool = mempool_create_slab_pool(MIN_IOS, _crypt_io_pool);
  710. if (!cc->io_pool) {
  711. ti->error = "Cannot allocate crypt io mempool";
  712. goto bad_slab_pool;
  713. }
  714. cc->page_pool = mempool_create_page_pool(MIN_POOL_PAGES, 0);
  715. if (!cc->page_pool) {
  716. ti->error = "Cannot allocate page mempool";
  717. goto bad_page_pool;
  718. }
  719. cc->bs = bioset_create(MIN_IOS, MIN_IOS);
  720. if (!cc->bs) {
  721. ti->error = "Cannot allocate crypt bioset";
  722. goto bad_bs;
  723. }
  724. if (crypto_blkcipher_setkey(tfm, cc->key, key_size) < 0) {
  725. ti->error = "Error setting key";
  726. goto bad_device;
  727. }
  728. if (sscanf(argv[2], "%llu", &tmpll) != 1) {
  729. ti->error = "Invalid iv_offset sector";
  730. goto bad_device;
  731. }
  732. cc->iv_offset = tmpll;
  733. if (sscanf(argv[4], "%llu", &tmpll) != 1) {
  734. ti->error = "Invalid device sector";
  735. goto bad_device;
  736. }
  737. cc->start = tmpll;
  738. if (dm_get_device(ti, argv[3], cc->start, ti->len,
  739. dm_table_get_mode(ti->table), &cc->dev)) {
  740. ti->error = "Device lookup failed";
  741. goto bad_device;
  742. }
  743. if (ivmode && cc->iv_gen_ops) {
  744. if (ivopts)
  745. *(ivopts - 1) = ':';
  746. cc->iv_mode = kmalloc(strlen(ivmode) + 1, GFP_KERNEL);
  747. if (!cc->iv_mode) {
  748. ti->error = "Error kmallocing iv_mode string";
  749. goto bad_ivmode_string;
  750. }
  751. strcpy(cc->iv_mode, ivmode);
  752. } else
  753. cc->iv_mode = NULL;
  754. cc->io_queue = create_singlethread_workqueue("kcryptd_io");
  755. if (!cc->io_queue) {
  756. ti->error = "Couldn't create kcryptd io queue";
  757. goto bad_io_queue;
  758. }
  759. cc->crypt_queue = create_singlethread_workqueue("kcryptd");
  760. if (!cc->crypt_queue) {
  761. ti->error = "Couldn't create kcryptd queue";
  762. goto bad_crypt_queue;
  763. }
  764. ti->private = cc;
  765. return 0;
  766. bad_crypt_queue:
  767. destroy_workqueue(cc->io_queue);
  768. bad_io_queue:
  769. kfree(cc->iv_mode);
  770. bad_ivmode_string:
  771. dm_put_device(ti, cc->dev);
  772. bad_device:
  773. bioset_free(cc->bs);
  774. bad_bs:
  775. mempool_destroy(cc->page_pool);
  776. bad_page_pool:
  777. mempool_destroy(cc->io_pool);
  778. bad_slab_pool:
  779. if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
  780. cc->iv_gen_ops->dtr(cc);
  781. bad_ivmode:
  782. crypto_free_blkcipher(tfm);
  783. bad_cipher:
  784. /* Must zero key material before freeing */
  785. memset(cc, 0, sizeof(*cc) + cc->key_size * sizeof(u8));
  786. kfree(cc);
  787. return -EINVAL;
  788. }
  789. static void crypt_dtr(struct dm_target *ti)
  790. {
  791. struct crypt_config *cc = (struct crypt_config *) ti->private;
  792. destroy_workqueue(cc->io_queue);
  793. destroy_workqueue(cc->crypt_queue);
  794. bioset_free(cc->bs);
  795. mempool_destroy(cc->page_pool);
  796. mempool_destroy(cc->io_pool);
  797. kfree(cc->iv_mode);
  798. if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
  799. cc->iv_gen_ops->dtr(cc);
  800. crypto_free_blkcipher(cc->tfm);
  801. dm_put_device(ti, cc->dev);
  802. /* Must zero key material before freeing */
  803. memset(cc, 0, sizeof(*cc) + cc->key_size * sizeof(u8));
  804. kfree(cc);
  805. }
  806. static int crypt_map(struct dm_target *ti, struct bio *bio,
  807. union map_info *map_context)
  808. {
  809. struct crypt_config *cc = ti->private;
  810. struct dm_crypt_io *io;
  811. io = mempool_alloc(cc->io_pool, GFP_NOIO);
  812. io->target = ti;
  813. io->base_bio = bio;
  814. io->sector = bio->bi_sector - ti->begin;
  815. io->error = 0;
  816. atomic_set(&io->pending, 0);
  817. if (bio_data_dir(io->base_bio) == READ)
  818. kcryptd_queue_io(io);
  819. else
  820. kcryptd_queue_crypt(io);
  821. return DM_MAPIO_SUBMITTED;
  822. }
  823. static int crypt_status(struct dm_target *ti, status_type_t type,
  824. char *result, unsigned int maxlen)
  825. {
  826. struct crypt_config *cc = (struct crypt_config *) ti->private;
  827. unsigned int sz = 0;
  828. switch (type) {
  829. case STATUSTYPE_INFO:
  830. result[0] = '\0';
  831. break;
  832. case STATUSTYPE_TABLE:
  833. if (cc->iv_mode)
  834. DMEMIT("%s-%s-%s ", cc->cipher, cc->chainmode,
  835. cc->iv_mode);
  836. else
  837. DMEMIT("%s-%s ", cc->cipher, cc->chainmode);
  838. if (cc->key_size > 0) {
  839. if ((maxlen - sz) < ((cc->key_size << 1) + 1))
  840. return -ENOMEM;
  841. crypt_encode_key(result + sz, cc->key, cc->key_size);
  842. sz += cc->key_size << 1;
  843. } else {
  844. if (sz >= maxlen)
  845. return -ENOMEM;
  846. result[sz++] = '-';
  847. }
  848. DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
  849. cc->dev->name, (unsigned long long)cc->start);
  850. break;
  851. }
  852. return 0;
  853. }
  854. static void crypt_postsuspend(struct dm_target *ti)
  855. {
  856. struct crypt_config *cc = ti->private;
  857. set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  858. }
  859. static int crypt_preresume(struct dm_target *ti)
  860. {
  861. struct crypt_config *cc = ti->private;
  862. if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
  863. DMERR("aborting resume - crypt key is not set.");
  864. return -EAGAIN;
  865. }
  866. return 0;
  867. }
  868. static void crypt_resume(struct dm_target *ti)
  869. {
  870. struct crypt_config *cc = ti->private;
  871. clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  872. }
  873. /* Message interface
  874. * key set <key>
  875. * key wipe
  876. */
  877. static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
  878. {
  879. struct crypt_config *cc = ti->private;
  880. if (argc < 2)
  881. goto error;
  882. if (!strnicmp(argv[0], MESG_STR("key"))) {
  883. if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
  884. DMWARN("not suspended during key manipulation.");
  885. return -EINVAL;
  886. }
  887. if (argc == 3 && !strnicmp(argv[1], MESG_STR("set")))
  888. return crypt_set_key(cc, argv[2]);
  889. if (argc == 2 && !strnicmp(argv[1], MESG_STR("wipe")))
  890. return crypt_wipe_key(cc);
  891. }
  892. error:
  893. DMWARN("unrecognised message received.");
  894. return -EINVAL;
  895. }
  896. static struct target_type crypt_target = {
  897. .name = "crypt",
  898. .version= {1, 5, 0},
  899. .module = THIS_MODULE,
  900. .ctr = crypt_ctr,
  901. .dtr = crypt_dtr,
  902. .map = crypt_map,
  903. .status = crypt_status,
  904. .postsuspend = crypt_postsuspend,
  905. .preresume = crypt_preresume,
  906. .resume = crypt_resume,
  907. .message = crypt_message,
  908. };
  909. static int __init dm_crypt_init(void)
  910. {
  911. int r;
  912. _crypt_io_pool = KMEM_CACHE(dm_crypt_io, 0);
  913. if (!_crypt_io_pool)
  914. return -ENOMEM;
  915. r = dm_register_target(&crypt_target);
  916. if (r < 0) {
  917. DMERR("register failed %d", r);
  918. kmem_cache_destroy(_crypt_io_pool);
  919. }
  920. return r;
  921. }
  922. static void __exit dm_crypt_exit(void)
  923. {
  924. int r = dm_unregister_target(&crypt_target);
  925. if (r < 0)
  926. DMERR("unregister failed %d", r);
  927. kmem_cache_destroy(_crypt_io_pool);
  928. }
  929. module_init(dm_crypt_init);
  930. module_exit(dm_crypt_exit);
  931. MODULE_AUTHOR("Christophe Saout <christophe@saout.de>");
  932. MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
  933. MODULE_LICENSE("GPL");