dm-crypt.c 29 KB

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