dm-crypt.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338
  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 <linux/device-mapper.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. struct dm_crypt_io *base_io;
  53. };
  54. struct dm_crypt_request {
  55. struct scatterlist sg_in;
  56. struct scatterlist sg_out;
  57. };
  58. struct crypt_config;
  59. struct crypt_iv_operations {
  60. int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
  61. const char *opts);
  62. void (*dtr)(struct crypt_config *cc);
  63. const char *(*status)(struct crypt_config *cc);
  64. int (*generator)(struct crypt_config *cc, u8 *iv, sector_t sector);
  65. };
  66. /*
  67. * Crypt: maps a linear range of a block device
  68. * and encrypts / decrypts at the same time.
  69. */
  70. enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID };
  71. struct crypt_config {
  72. struct dm_dev *dev;
  73. sector_t start;
  74. /*
  75. * pool for per bio private data, crypto requests and
  76. * encryption requeusts/buffer pages
  77. */
  78. mempool_t *io_pool;
  79. mempool_t *req_pool;
  80. mempool_t *page_pool;
  81. struct bio_set *bs;
  82. struct workqueue_struct *io_queue;
  83. struct workqueue_struct *crypt_queue;
  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. }
  287. static int crypt_convert_block(struct crypt_config *cc,
  288. struct convert_context *ctx,
  289. struct ablkcipher_request *req)
  290. {
  291. struct bio_vec *bv_in = bio_iovec_idx(ctx->bio_in, ctx->idx_in);
  292. struct bio_vec *bv_out = bio_iovec_idx(ctx->bio_out, ctx->idx_out);
  293. struct dm_crypt_request *dmreq;
  294. u8 *iv;
  295. int r = 0;
  296. dmreq = (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
  297. iv = (u8 *)ALIGN((unsigned long)(dmreq + 1),
  298. crypto_ablkcipher_alignmask(cc->tfm) + 1);
  299. sg_init_table(&dmreq->sg_in, 1);
  300. sg_set_page(&dmreq->sg_in, bv_in->bv_page, 1 << SECTOR_SHIFT,
  301. bv_in->bv_offset + ctx->offset_in);
  302. sg_init_table(&dmreq->sg_out, 1);
  303. sg_set_page(&dmreq->sg_out, bv_out->bv_page, 1 << SECTOR_SHIFT,
  304. bv_out->bv_offset + ctx->offset_out);
  305. ctx->offset_in += 1 << SECTOR_SHIFT;
  306. if (ctx->offset_in >= bv_in->bv_len) {
  307. ctx->offset_in = 0;
  308. ctx->idx_in++;
  309. }
  310. ctx->offset_out += 1 << SECTOR_SHIFT;
  311. if (ctx->offset_out >= bv_out->bv_len) {
  312. ctx->offset_out = 0;
  313. ctx->idx_out++;
  314. }
  315. if (cc->iv_gen_ops) {
  316. r = cc->iv_gen_ops->generator(cc, iv, ctx->sector);
  317. if (r < 0)
  318. return r;
  319. }
  320. ablkcipher_request_set_crypt(req, &dmreq->sg_in, &dmreq->sg_out,
  321. 1 << SECTOR_SHIFT, iv);
  322. if (bio_data_dir(ctx->bio_in) == WRITE)
  323. r = crypto_ablkcipher_encrypt(req);
  324. else
  325. r = crypto_ablkcipher_decrypt(req);
  326. return r;
  327. }
  328. static void kcryptd_async_done(struct crypto_async_request *async_req,
  329. int error);
  330. static void crypt_alloc_req(struct crypt_config *cc,
  331. struct convert_context *ctx)
  332. {
  333. if (!cc->req)
  334. cc->req = mempool_alloc(cc->req_pool, GFP_NOIO);
  335. ablkcipher_request_set_tfm(cc->req, cc->tfm);
  336. ablkcipher_request_set_callback(cc->req, CRYPTO_TFM_REQ_MAY_BACKLOG |
  337. CRYPTO_TFM_REQ_MAY_SLEEP,
  338. kcryptd_async_done, ctx);
  339. }
  340. /*
  341. * Encrypt / decrypt data from one bio to another one (can be the same one)
  342. */
  343. static int crypt_convert(struct crypt_config *cc,
  344. struct convert_context *ctx)
  345. {
  346. int r;
  347. atomic_set(&ctx->pending, 1);
  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. cond_resched();
  368. continue;
  369. /* error */
  370. default:
  371. atomic_dec(&ctx->pending);
  372. return r;
  373. }
  374. }
  375. return 0;
  376. }
  377. static void dm_crypt_bio_destructor(struct bio *bio)
  378. {
  379. struct dm_crypt_io *io = bio->bi_private;
  380. struct crypt_config *cc = io->target->private;
  381. bio_free(bio, cc->bs);
  382. }
  383. /*
  384. * Generate a new unfragmented bio with the given size
  385. * This should never violate the device limitations
  386. * May return a smaller bio when running out of pages, indicated by
  387. * *out_of_pages set to 1.
  388. */
  389. static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size,
  390. unsigned *out_of_pages)
  391. {
  392. struct crypt_config *cc = io->target->private;
  393. struct bio *clone;
  394. unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
  395. gfp_t gfp_mask = GFP_NOIO | __GFP_HIGHMEM;
  396. unsigned i, len;
  397. struct page *page;
  398. clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, cc->bs);
  399. if (!clone)
  400. return NULL;
  401. clone_init(io, clone);
  402. *out_of_pages = 0;
  403. for (i = 0; i < nr_iovecs; i++) {
  404. page = mempool_alloc(cc->page_pool, gfp_mask);
  405. if (!page) {
  406. *out_of_pages = 1;
  407. break;
  408. }
  409. /*
  410. * if additional pages cannot be allocated without waiting,
  411. * return a partially allocated bio, the caller will then try
  412. * to allocate additional bios while submitting this partial bio
  413. */
  414. if (i == (MIN_BIO_PAGES - 1))
  415. gfp_mask = (gfp_mask | __GFP_NOWARN) & ~__GFP_WAIT;
  416. len = (size > PAGE_SIZE) ? PAGE_SIZE : size;
  417. if (!bio_add_page(clone, page, len, 0)) {
  418. mempool_free(page, cc->page_pool);
  419. break;
  420. }
  421. size -= len;
  422. }
  423. if (!clone->bi_size) {
  424. bio_put(clone);
  425. return NULL;
  426. }
  427. return clone;
  428. }
  429. static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
  430. {
  431. unsigned int i;
  432. struct bio_vec *bv;
  433. for (i = 0; i < clone->bi_vcnt; i++) {
  434. bv = bio_iovec_idx(clone, i);
  435. BUG_ON(!bv->bv_page);
  436. mempool_free(bv->bv_page, cc->page_pool);
  437. bv->bv_page = NULL;
  438. }
  439. }
  440. static struct dm_crypt_io *crypt_io_alloc(struct dm_target *ti,
  441. struct bio *bio, sector_t sector)
  442. {
  443. struct crypt_config *cc = ti->private;
  444. struct dm_crypt_io *io;
  445. io = mempool_alloc(cc->io_pool, GFP_NOIO);
  446. io->target = ti;
  447. io->base_bio = bio;
  448. io->sector = sector;
  449. io->error = 0;
  450. io->base_io = NULL;
  451. atomic_set(&io->pending, 0);
  452. return io;
  453. }
  454. static void crypt_inc_pending(struct dm_crypt_io *io)
  455. {
  456. atomic_inc(&io->pending);
  457. }
  458. /*
  459. * One of the bios was finished. Check for completion of
  460. * the whole request and correctly clean up the buffer.
  461. * If base_io is set, wait for the last fragment to complete.
  462. */
  463. static void crypt_dec_pending(struct dm_crypt_io *io)
  464. {
  465. struct crypt_config *cc = io->target->private;
  466. if (!atomic_dec_and_test(&io->pending))
  467. return;
  468. if (likely(!io->base_io))
  469. bio_endio(io->base_bio, io->error);
  470. else {
  471. if (io->error && !io->base_io->error)
  472. io->base_io->error = io->error;
  473. crypt_dec_pending(io->base_io);
  474. }
  475. mempool_free(io, cc->io_pool);
  476. }
  477. /*
  478. * kcryptd/kcryptd_io:
  479. *
  480. * Needed because it would be very unwise to do decryption in an
  481. * interrupt context.
  482. *
  483. * kcryptd performs the actual encryption or decryption.
  484. *
  485. * kcryptd_io performs the IO submission.
  486. *
  487. * They must be separated as otherwise the final stages could be
  488. * starved by new requests which can block in the first stages due
  489. * to memory allocation.
  490. */
  491. static void crypt_endio(struct bio *clone, int error)
  492. {
  493. struct dm_crypt_io *io = clone->bi_private;
  494. struct crypt_config *cc = io->target->private;
  495. unsigned rw = bio_data_dir(clone);
  496. if (unlikely(!bio_flagged(clone, BIO_UPTODATE) && !error))
  497. error = -EIO;
  498. /*
  499. * free the processed pages
  500. */
  501. if (rw == WRITE)
  502. crypt_free_buffer_pages(cc, clone);
  503. bio_put(clone);
  504. if (rw == READ && !error) {
  505. kcryptd_queue_crypt(io);
  506. return;
  507. }
  508. if (unlikely(error))
  509. io->error = error;
  510. crypt_dec_pending(io);
  511. }
  512. static void clone_init(struct dm_crypt_io *io, struct bio *clone)
  513. {
  514. struct crypt_config *cc = io->target->private;
  515. clone->bi_private = io;
  516. clone->bi_end_io = crypt_endio;
  517. clone->bi_bdev = cc->dev->bdev;
  518. clone->bi_rw = io->base_bio->bi_rw;
  519. clone->bi_destructor = dm_crypt_bio_destructor;
  520. }
  521. static void kcryptd_io_read(struct dm_crypt_io *io)
  522. {
  523. struct crypt_config *cc = io->target->private;
  524. struct bio *base_bio = io->base_bio;
  525. struct bio *clone;
  526. crypt_inc_pending(io);
  527. /*
  528. * The block layer might modify the bvec array, so always
  529. * copy the required bvecs because we need the original
  530. * one in order to decrypt the whole bio data *afterwards*.
  531. */
  532. clone = bio_alloc_bioset(GFP_NOIO, bio_segments(base_bio), cc->bs);
  533. if (unlikely(!clone)) {
  534. io->error = -ENOMEM;
  535. crypt_dec_pending(io);
  536. return;
  537. }
  538. clone_init(io, clone);
  539. clone->bi_idx = 0;
  540. clone->bi_vcnt = bio_segments(base_bio);
  541. clone->bi_size = base_bio->bi_size;
  542. clone->bi_sector = cc->start + io->sector;
  543. memcpy(clone->bi_io_vec, bio_iovec(base_bio),
  544. sizeof(struct bio_vec) * clone->bi_vcnt);
  545. generic_make_request(clone);
  546. }
  547. static void kcryptd_io_write(struct dm_crypt_io *io)
  548. {
  549. struct bio *clone = io->ctx.bio_out;
  550. generic_make_request(clone);
  551. }
  552. static void kcryptd_io(struct work_struct *work)
  553. {
  554. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  555. if (bio_data_dir(io->base_bio) == READ)
  556. kcryptd_io_read(io);
  557. else
  558. kcryptd_io_write(io);
  559. }
  560. static void kcryptd_queue_io(struct dm_crypt_io *io)
  561. {
  562. struct crypt_config *cc = io->target->private;
  563. INIT_WORK(&io->work, kcryptd_io);
  564. queue_work(cc->io_queue, &io->work);
  565. }
  566. static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io,
  567. int error, int async)
  568. {
  569. struct bio *clone = io->ctx.bio_out;
  570. struct crypt_config *cc = io->target->private;
  571. if (unlikely(error < 0)) {
  572. crypt_free_buffer_pages(cc, clone);
  573. bio_put(clone);
  574. io->error = -EIO;
  575. crypt_dec_pending(io);
  576. return;
  577. }
  578. /* crypt_convert should have filled the clone bio */
  579. BUG_ON(io->ctx.idx_out < clone->bi_vcnt);
  580. clone->bi_sector = cc->start + io->sector;
  581. if (async)
  582. kcryptd_queue_io(io);
  583. else
  584. generic_make_request(clone);
  585. }
  586. static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
  587. {
  588. struct crypt_config *cc = io->target->private;
  589. struct bio *clone;
  590. struct dm_crypt_io *new_io;
  591. int crypt_finished;
  592. unsigned out_of_pages = 0;
  593. unsigned remaining = io->base_bio->bi_size;
  594. sector_t sector = io->sector;
  595. int r;
  596. /*
  597. * Prevent io from disappearing until this function completes.
  598. */
  599. crypt_inc_pending(io);
  600. crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
  601. /*
  602. * The allocated buffers can be smaller than the whole bio,
  603. * so repeat the whole process until all the data can be handled.
  604. */
  605. while (remaining) {
  606. clone = crypt_alloc_buffer(io, remaining, &out_of_pages);
  607. if (unlikely(!clone)) {
  608. io->error = -ENOMEM;
  609. break;
  610. }
  611. io->ctx.bio_out = clone;
  612. io->ctx.idx_out = 0;
  613. remaining -= clone->bi_size;
  614. sector += bio_sectors(clone);
  615. crypt_inc_pending(io);
  616. r = crypt_convert(cc, &io->ctx);
  617. crypt_finished = atomic_dec_and_test(&io->ctx.pending);
  618. /* Encryption was already finished, submit io now */
  619. if (crypt_finished) {
  620. kcryptd_crypt_write_io_submit(io, r, 0);
  621. /*
  622. * If there was an error, do not try next fragments.
  623. * For async, error is processed in async handler.
  624. */
  625. if (unlikely(r < 0))
  626. break;
  627. io->sector = sector;
  628. }
  629. /*
  630. * Out of memory -> run queues
  631. * But don't wait if split was due to the io size restriction
  632. */
  633. if (unlikely(out_of_pages))
  634. congestion_wait(WRITE, HZ/100);
  635. /*
  636. * With async crypto it is unsafe to share the crypto context
  637. * between fragments, so switch to a new dm_crypt_io structure.
  638. */
  639. if (unlikely(!crypt_finished && remaining)) {
  640. new_io = crypt_io_alloc(io->target, io->base_bio,
  641. sector);
  642. crypt_inc_pending(new_io);
  643. crypt_convert_init(cc, &new_io->ctx, NULL,
  644. io->base_bio, sector);
  645. new_io->ctx.idx_in = io->ctx.idx_in;
  646. new_io->ctx.offset_in = io->ctx.offset_in;
  647. /*
  648. * Fragments after the first use the base_io
  649. * pending count.
  650. */
  651. if (!io->base_io)
  652. new_io->base_io = io;
  653. else {
  654. new_io->base_io = io->base_io;
  655. crypt_inc_pending(io->base_io);
  656. crypt_dec_pending(io);
  657. }
  658. io = new_io;
  659. }
  660. }
  661. crypt_dec_pending(io);
  662. }
  663. static void kcryptd_crypt_read_done(struct dm_crypt_io *io, int error)
  664. {
  665. if (unlikely(error < 0))
  666. io->error = -EIO;
  667. crypt_dec_pending(io);
  668. }
  669. static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
  670. {
  671. struct crypt_config *cc = io->target->private;
  672. int r = 0;
  673. crypt_inc_pending(io);
  674. crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
  675. io->sector);
  676. r = crypt_convert(cc, &io->ctx);
  677. if (atomic_dec_and_test(&io->ctx.pending))
  678. kcryptd_crypt_read_done(io, r);
  679. crypt_dec_pending(io);
  680. }
  681. static void kcryptd_async_done(struct crypto_async_request *async_req,
  682. int error)
  683. {
  684. struct convert_context *ctx = async_req->data;
  685. struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
  686. struct crypt_config *cc = io->target->private;
  687. if (error == -EINPROGRESS) {
  688. complete(&ctx->restart);
  689. return;
  690. }
  691. mempool_free(ablkcipher_request_cast(async_req), cc->req_pool);
  692. if (!atomic_dec_and_test(&ctx->pending))
  693. return;
  694. if (bio_data_dir(io->base_bio) == READ)
  695. kcryptd_crypt_read_done(io, error);
  696. else
  697. kcryptd_crypt_write_io_submit(io, error, 1);
  698. }
  699. static void kcryptd_crypt(struct work_struct *work)
  700. {
  701. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  702. if (bio_data_dir(io->base_bio) == READ)
  703. kcryptd_crypt_read_convert(io);
  704. else
  705. kcryptd_crypt_write_convert(io);
  706. }
  707. static void kcryptd_queue_crypt(struct dm_crypt_io *io)
  708. {
  709. struct crypt_config *cc = io->target->private;
  710. INIT_WORK(&io->work, kcryptd_crypt);
  711. queue_work(cc->crypt_queue, &io->work);
  712. }
  713. /*
  714. * Decode key from its hex representation
  715. */
  716. static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
  717. {
  718. char buffer[3];
  719. char *endp;
  720. unsigned int i;
  721. buffer[2] = '\0';
  722. for (i = 0; i < size; i++) {
  723. buffer[0] = *hex++;
  724. buffer[1] = *hex++;
  725. key[i] = (u8)simple_strtoul(buffer, &endp, 16);
  726. if (endp != &buffer[2])
  727. return -EINVAL;
  728. }
  729. if (*hex != '\0')
  730. return -EINVAL;
  731. return 0;
  732. }
  733. /*
  734. * Encode key into its hex representation
  735. */
  736. static void crypt_encode_key(char *hex, u8 *key, unsigned int size)
  737. {
  738. unsigned int i;
  739. for (i = 0; i < size; i++) {
  740. sprintf(hex, "%02x", *key);
  741. hex += 2;
  742. key++;
  743. }
  744. }
  745. static int crypt_set_key(struct crypt_config *cc, char *key)
  746. {
  747. unsigned key_size = strlen(key) >> 1;
  748. if (cc->key_size && cc->key_size != key_size)
  749. return -EINVAL;
  750. cc->key_size = key_size; /* initial settings */
  751. if ((!key_size && strcmp(key, "-")) ||
  752. (key_size && crypt_decode_key(cc->key, key, key_size) < 0))
  753. return -EINVAL;
  754. set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  755. return 0;
  756. }
  757. static int crypt_wipe_key(struct crypt_config *cc)
  758. {
  759. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  760. memset(&cc->key, 0, cc->key_size * sizeof(u8));
  761. return 0;
  762. }
  763. /*
  764. * Construct an encryption mapping:
  765. * <cipher> <key> <iv_offset> <dev_path> <start>
  766. */
  767. static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
  768. {
  769. struct crypt_config *cc;
  770. struct crypto_ablkcipher *tfm;
  771. char *tmp;
  772. char *cipher;
  773. char *chainmode;
  774. char *ivmode;
  775. char *ivopts;
  776. unsigned int key_size;
  777. unsigned long long tmpll;
  778. if (argc != 5) {
  779. ti->error = "Not enough arguments";
  780. return -EINVAL;
  781. }
  782. tmp = argv[0];
  783. cipher = strsep(&tmp, "-");
  784. chainmode = strsep(&tmp, "-");
  785. ivopts = strsep(&tmp, "-");
  786. ivmode = strsep(&ivopts, ":");
  787. if (tmp)
  788. DMWARN("Unexpected additional cipher options");
  789. key_size = strlen(argv[1]) >> 1;
  790. cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
  791. if (cc == NULL) {
  792. ti->error =
  793. "Cannot allocate transparent encryption context";
  794. return -ENOMEM;
  795. }
  796. if (crypt_set_key(cc, argv[1])) {
  797. ti->error = "Error decoding key";
  798. goto bad_cipher;
  799. }
  800. /* Compatiblity mode for old dm-crypt cipher strings */
  801. if (!chainmode || (strcmp(chainmode, "plain") == 0 && !ivmode)) {
  802. chainmode = "cbc";
  803. ivmode = "plain";
  804. }
  805. if (strcmp(chainmode, "ecb") && !ivmode) {
  806. ti->error = "This chaining mode requires an IV mechanism";
  807. goto bad_cipher;
  808. }
  809. if (snprintf(cc->cipher, CRYPTO_MAX_ALG_NAME, "%s(%s)",
  810. chainmode, cipher) >= CRYPTO_MAX_ALG_NAME) {
  811. ti->error = "Chain mode + cipher name is too long";
  812. goto bad_cipher;
  813. }
  814. tfm = crypto_alloc_ablkcipher(cc->cipher, 0, 0);
  815. if (IS_ERR(tfm)) {
  816. ti->error = "Error allocating crypto tfm";
  817. goto bad_cipher;
  818. }
  819. strcpy(cc->cipher, cipher);
  820. strcpy(cc->chainmode, chainmode);
  821. cc->tfm = tfm;
  822. /*
  823. * Choose ivmode. Valid modes: "plain", "essiv:<esshash>", "benbi".
  824. * See comments at iv code
  825. */
  826. if (ivmode == NULL)
  827. cc->iv_gen_ops = NULL;
  828. else if (strcmp(ivmode, "plain") == 0)
  829. cc->iv_gen_ops = &crypt_iv_plain_ops;
  830. else if (strcmp(ivmode, "essiv") == 0)
  831. cc->iv_gen_ops = &crypt_iv_essiv_ops;
  832. else if (strcmp(ivmode, "benbi") == 0)
  833. cc->iv_gen_ops = &crypt_iv_benbi_ops;
  834. else if (strcmp(ivmode, "null") == 0)
  835. cc->iv_gen_ops = &crypt_iv_null_ops;
  836. else {
  837. ti->error = "Invalid IV mode";
  838. goto bad_ivmode;
  839. }
  840. if (cc->iv_gen_ops && cc->iv_gen_ops->ctr &&
  841. cc->iv_gen_ops->ctr(cc, ti, ivopts) < 0)
  842. goto bad_ivmode;
  843. cc->iv_size = crypto_ablkcipher_ivsize(tfm);
  844. if (cc->iv_size)
  845. /* at least a 64 bit sector number should fit in our buffer */
  846. cc->iv_size = max(cc->iv_size,
  847. (unsigned int)(sizeof(u64) / sizeof(u8)));
  848. else {
  849. if (cc->iv_gen_ops) {
  850. DMWARN("Selected cipher does not support IVs");
  851. if (cc->iv_gen_ops->dtr)
  852. cc->iv_gen_ops->dtr(cc);
  853. cc->iv_gen_ops = NULL;
  854. }
  855. }
  856. cc->io_pool = mempool_create_slab_pool(MIN_IOS, _crypt_io_pool);
  857. if (!cc->io_pool) {
  858. ti->error = "Cannot allocate crypt io mempool";
  859. goto bad_slab_pool;
  860. }
  861. cc->dmreq_start = sizeof(struct ablkcipher_request);
  862. cc->dmreq_start += crypto_ablkcipher_reqsize(tfm);
  863. cc->dmreq_start = ALIGN(cc->dmreq_start, crypto_tfm_ctx_alignment());
  864. cc->dmreq_start += crypto_ablkcipher_alignmask(tfm) &
  865. ~(crypto_tfm_ctx_alignment() - 1);
  866. cc->req_pool = mempool_create_kmalloc_pool(MIN_IOS, cc->dmreq_start +
  867. sizeof(struct dm_crypt_request) + cc->iv_size);
  868. if (!cc->req_pool) {
  869. ti->error = "Cannot allocate crypt request mempool";
  870. goto bad_req_pool;
  871. }
  872. cc->req = NULL;
  873. cc->page_pool = mempool_create_page_pool(MIN_POOL_PAGES, 0);
  874. if (!cc->page_pool) {
  875. ti->error = "Cannot allocate page mempool";
  876. goto bad_page_pool;
  877. }
  878. cc->bs = bioset_create(MIN_IOS, 0);
  879. if (!cc->bs) {
  880. ti->error = "Cannot allocate crypt bioset";
  881. goto bad_bs;
  882. }
  883. if (crypto_ablkcipher_setkey(tfm, cc->key, key_size) < 0) {
  884. ti->error = "Error setting key";
  885. goto bad_device;
  886. }
  887. if (sscanf(argv[2], "%llu", &tmpll) != 1) {
  888. ti->error = "Invalid iv_offset sector";
  889. goto bad_device;
  890. }
  891. cc->iv_offset = tmpll;
  892. if (sscanf(argv[4], "%llu", &tmpll) != 1) {
  893. ti->error = "Invalid device sector";
  894. goto bad_device;
  895. }
  896. cc->start = tmpll;
  897. if (dm_get_device(ti, argv[3], cc->start, ti->len,
  898. dm_table_get_mode(ti->table), &cc->dev)) {
  899. ti->error = "Device lookup failed";
  900. goto bad_device;
  901. }
  902. if (ivmode && cc->iv_gen_ops) {
  903. if (ivopts)
  904. *(ivopts - 1) = ':';
  905. cc->iv_mode = kmalloc(strlen(ivmode) + 1, GFP_KERNEL);
  906. if (!cc->iv_mode) {
  907. ti->error = "Error kmallocing iv_mode string";
  908. goto bad_ivmode_string;
  909. }
  910. strcpy(cc->iv_mode, ivmode);
  911. } else
  912. cc->iv_mode = NULL;
  913. cc->io_queue = create_singlethread_workqueue("kcryptd_io");
  914. if (!cc->io_queue) {
  915. ti->error = "Couldn't create kcryptd io queue";
  916. goto bad_io_queue;
  917. }
  918. cc->crypt_queue = create_singlethread_workqueue("kcryptd");
  919. if (!cc->crypt_queue) {
  920. ti->error = "Couldn't create kcryptd queue";
  921. goto bad_crypt_queue;
  922. }
  923. ti->private = cc;
  924. return 0;
  925. bad_crypt_queue:
  926. destroy_workqueue(cc->io_queue);
  927. bad_io_queue:
  928. kfree(cc->iv_mode);
  929. bad_ivmode_string:
  930. dm_put_device(ti, cc->dev);
  931. bad_device:
  932. bioset_free(cc->bs);
  933. bad_bs:
  934. mempool_destroy(cc->page_pool);
  935. bad_page_pool:
  936. mempool_destroy(cc->req_pool);
  937. bad_req_pool:
  938. mempool_destroy(cc->io_pool);
  939. bad_slab_pool:
  940. if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
  941. cc->iv_gen_ops->dtr(cc);
  942. bad_ivmode:
  943. crypto_free_ablkcipher(tfm);
  944. bad_cipher:
  945. /* Must zero key material before freeing */
  946. memset(cc, 0, sizeof(*cc) + cc->key_size * sizeof(u8));
  947. kfree(cc);
  948. return -EINVAL;
  949. }
  950. static void crypt_dtr(struct dm_target *ti)
  951. {
  952. struct crypt_config *cc = (struct crypt_config *) ti->private;
  953. destroy_workqueue(cc->io_queue);
  954. destroy_workqueue(cc->crypt_queue);
  955. if (cc->req)
  956. mempool_free(cc->req, cc->req_pool);
  957. bioset_free(cc->bs);
  958. mempool_destroy(cc->page_pool);
  959. mempool_destroy(cc->req_pool);
  960. mempool_destroy(cc->io_pool);
  961. kfree(cc->iv_mode);
  962. if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
  963. cc->iv_gen_ops->dtr(cc);
  964. crypto_free_ablkcipher(cc->tfm);
  965. dm_put_device(ti, cc->dev);
  966. /* Must zero key material before freeing */
  967. memset(cc, 0, sizeof(*cc) + cc->key_size * sizeof(u8));
  968. kfree(cc);
  969. }
  970. static int crypt_map(struct dm_target *ti, struct bio *bio,
  971. union map_info *map_context)
  972. {
  973. struct dm_crypt_io *io;
  974. io = crypt_io_alloc(ti, bio, bio->bi_sector - ti->begin);
  975. if (bio_data_dir(io->base_bio) == READ)
  976. kcryptd_queue_io(io);
  977. else
  978. kcryptd_queue_crypt(io);
  979. return DM_MAPIO_SUBMITTED;
  980. }
  981. static int crypt_status(struct dm_target *ti, status_type_t type,
  982. char *result, unsigned int maxlen)
  983. {
  984. struct crypt_config *cc = (struct crypt_config *) ti->private;
  985. unsigned int sz = 0;
  986. switch (type) {
  987. case STATUSTYPE_INFO:
  988. result[0] = '\0';
  989. break;
  990. case STATUSTYPE_TABLE:
  991. if (cc->iv_mode)
  992. DMEMIT("%s-%s-%s ", cc->cipher, cc->chainmode,
  993. cc->iv_mode);
  994. else
  995. DMEMIT("%s-%s ", cc->cipher, cc->chainmode);
  996. if (cc->key_size > 0) {
  997. if ((maxlen - sz) < ((cc->key_size << 1) + 1))
  998. return -ENOMEM;
  999. crypt_encode_key(result + sz, cc->key, cc->key_size);
  1000. sz += cc->key_size << 1;
  1001. } else {
  1002. if (sz >= maxlen)
  1003. return -ENOMEM;
  1004. result[sz++] = '-';
  1005. }
  1006. DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
  1007. cc->dev->name, (unsigned long long)cc->start);
  1008. break;
  1009. }
  1010. return 0;
  1011. }
  1012. static void crypt_postsuspend(struct dm_target *ti)
  1013. {
  1014. struct crypt_config *cc = ti->private;
  1015. set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  1016. }
  1017. static int crypt_preresume(struct dm_target *ti)
  1018. {
  1019. struct crypt_config *cc = ti->private;
  1020. if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
  1021. DMERR("aborting resume - crypt key is not set.");
  1022. return -EAGAIN;
  1023. }
  1024. return 0;
  1025. }
  1026. static void crypt_resume(struct dm_target *ti)
  1027. {
  1028. struct crypt_config *cc = ti->private;
  1029. clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  1030. }
  1031. /* Message interface
  1032. * key set <key>
  1033. * key wipe
  1034. */
  1035. static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
  1036. {
  1037. struct crypt_config *cc = ti->private;
  1038. if (argc < 2)
  1039. goto error;
  1040. if (!strnicmp(argv[0], MESG_STR("key"))) {
  1041. if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
  1042. DMWARN("not suspended during key manipulation.");
  1043. return -EINVAL;
  1044. }
  1045. if (argc == 3 && !strnicmp(argv[1], MESG_STR("set")))
  1046. return crypt_set_key(cc, argv[2]);
  1047. if (argc == 2 && !strnicmp(argv[1], MESG_STR("wipe")))
  1048. return crypt_wipe_key(cc);
  1049. }
  1050. error:
  1051. DMWARN("unrecognised message received.");
  1052. return -EINVAL;
  1053. }
  1054. static int crypt_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
  1055. struct bio_vec *biovec, int max_size)
  1056. {
  1057. struct crypt_config *cc = ti->private;
  1058. struct request_queue *q = bdev_get_queue(cc->dev->bdev);
  1059. if (!q->merge_bvec_fn)
  1060. return max_size;
  1061. bvm->bi_bdev = cc->dev->bdev;
  1062. bvm->bi_sector = cc->start + bvm->bi_sector - ti->begin;
  1063. return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
  1064. }
  1065. static struct target_type crypt_target = {
  1066. .name = "crypt",
  1067. .version= {1, 6, 0},
  1068. .module = THIS_MODULE,
  1069. .ctr = crypt_ctr,
  1070. .dtr = crypt_dtr,
  1071. .map = crypt_map,
  1072. .status = crypt_status,
  1073. .postsuspend = crypt_postsuspend,
  1074. .preresume = crypt_preresume,
  1075. .resume = crypt_resume,
  1076. .message = crypt_message,
  1077. .merge = crypt_merge,
  1078. };
  1079. static int __init dm_crypt_init(void)
  1080. {
  1081. int r;
  1082. _crypt_io_pool = KMEM_CACHE(dm_crypt_io, 0);
  1083. if (!_crypt_io_pool)
  1084. return -ENOMEM;
  1085. r = dm_register_target(&crypt_target);
  1086. if (r < 0) {
  1087. DMERR("register failed %d", r);
  1088. kmem_cache_destroy(_crypt_io_pool);
  1089. }
  1090. return r;
  1091. }
  1092. static void __exit dm_crypt_exit(void)
  1093. {
  1094. int r = dm_unregister_target(&crypt_target);
  1095. if (r < 0)
  1096. DMERR("unregister failed %d", r);
  1097. kmem_cache_destroy(_crypt_io_pool);
  1098. }
  1099. module_init(dm_crypt_init);
  1100. module_exit(dm_crypt_exit);
  1101. MODULE_AUTHOR("Christophe Saout <christophe@saout.de>");
  1102. MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
  1103. MODULE_LICENSE("GPL");