dm-crypt.c 26 KB

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