dm-crypt.c 26 KB

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