dm-crypt.c 29 KB

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