dm-crypt.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304
  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. }
  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. atomic_set(&io->pending, 0);
  451. return io;
  452. }
  453. static void crypt_inc_pending(struct dm_crypt_io *io)
  454. {
  455. atomic_inc(&io->pending);
  456. }
  457. /*
  458. * One of the bios was finished. Check for completion of
  459. * the whole request and correctly clean up the buffer.
  460. */
  461. static void crypt_dec_pending(struct dm_crypt_io *io)
  462. {
  463. struct crypt_config *cc = io->target->private;
  464. if (!atomic_dec_and_test(&io->pending))
  465. return;
  466. bio_endio(io->base_bio, io->error);
  467. mempool_free(io, cc->io_pool);
  468. }
  469. /*
  470. * kcryptd/kcryptd_io:
  471. *
  472. * Needed because it would be very unwise to do decryption in an
  473. * interrupt context.
  474. *
  475. * kcryptd performs the actual encryption or decryption.
  476. *
  477. * kcryptd_io performs the IO submission.
  478. *
  479. * They must be separated as otherwise the final stages could be
  480. * starved by new requests which can block in the first stages due
  481. * to memory allocation.
  482. */
  483. static void crypt_endio(struct bio *clone, int error)
  484. {
  485. struct dm_crypt_io *io = clone->bi_private;
  486. struct crypt_config *cc = io->target->private;
  487. unsigned rw = bio_data_dir(clone);
  488. if (unlikely(!bio_flagged(clone, BIO_UPTODATE) && !error))
  489. error = -EIO;
  490. /*
  491. * free the processed pages
  492. */
  493. if (rw == WRITE)
  494. crypt_free_buffer_pages(cc, clone);
  495. bio_put(clone);
  496. if (rw == READ && !error) {
  497. kcryptd_queue_crypt(io);
  498. return;
  499. }
  500. if (unlikely(error))
  501. io->error = error;
  502. crypt_dec_pending(io);
  503. }
  504. static void clone_init(struct dm_crypt_io *io, struct bio *clone)
  505. {
  506. struct crypt_config *cc = io->target->private;
  507. clone->bi_private = io;
  508. clone->bi_end_io = crypt_endio;
  509. clone->bi_bdev = cc->dev->bdev;
  510. clone->bi_rw = io->base_bio->bi_rw;
  511. clone->bi_destructor = dm_crypt_bio_destructor;
  512. }
  513. static void kcryptd_io_read(struct dm_crypt_io *io)
  514. {
  515. struct crypt_config *cc = io->target->private;
  516. struct bio *base_bio = io->base_bio;
  517. struct bio *clone;
  518. crypt_inc_pending(io);
  519. /*
  520. * The block layer might modify the bvec array, so always
  521. * copy the required bvecs because we need the original
  522. * one in order to decrypt the whole bio data *afterwards*.
  523. */
  524. clone = bio_alloc_bioset(GFP_NOIO, bio_segments(base_bio), cc->bs);
  525. if (unlikely(!clone)) {
  526. io->error = -ENOMEM;
  527. crypt_dec_pending(io);
  528. return;
  529. }
  530. clone_init(io, clone);
  531. clone->bi_idx = 0;
  532. clone->bi_vcnt = bio_segments(base_bio);
  533. clone->bi_size = base_bio->bi_size;
  534. clone->bi_sector = cc->start + io->sector;
  535. memcpy(clone->bi_io_vec, bio_iovec(base_bio),
  536. sizeof(struct bio_vec) * clone->bi_vcnt);
  537. generic_make_request(clone);
  538. }
  539. static void kcryptd_io_write(struct dm_crypt_io *io)
  540. {
  541. struct bio *clone = io->ctx.bio_out;
  542. struct crypt_config *cc = io->target->private;
  543. generic_make_request(clone);
  544. wake_up(&cc->writeq);
  545. }
  546. static void kcryptd_io(struct work_struct *work)
  547. {
  548. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  549. if (bio_data_dir(io->base_bio) == READ)
  550. kcryptd_io_read(io);
  551. else
  552. kcryptd_io_write(io);
  553. }
  554. static void kcryptd_queue_io(struct dm_crypt_io *io)
  555. {
  556. struct crypt_config *cc = io->target->private;
  557. INIT_WORK(&io->work, kcryptd_io);
  558. queue_work(cc->io_queue, &io->work);
  559. }
  560. static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io,
  561. int error, int async)
  562. {
  563. struct bio *clone = io->ctx.bio_out;
  564. struct crypt_config *cc = io->target->private;
  565. if (unlikely(error < 0)) {
  566. crypt_free_buffer_pages(cc, clone);
  567. bio_put(clone);
  568. io->error = -EIO;
  569. crypt_dec_pending(io);
  570. return;
  571. }
  572. /* crypt_convert should have filled the clone bio */
  573. BUG_ON(io->ctx.idx_out < clone->bi_vcnt);
  574. clone->bi_sector = cc->start + io->sector;
  575. io->sector += bio_sectors(clone);
  576. if (async)
  577. kcryptd_queue_io(io);
  578. else
  579. generic_make_request(clone);
  580. }
  581. static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
  582. {
  583. struct crypt_config *cc = io->target->private;
  584. struct bio *clone;
  585. int crypt_finished;
  586. unsigned out_of_pages = 0;
  587. unsigned remaining = io->base_bio->bi_size;
  588. int r;
  589. /*
  590. * Prevent io from disappearing until this function completes.
  591. */
  592. crypt_inc_pending(io);
  593. crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, io->sector);
  594. /*
  595. * The allocated buffers can be smaller than the whole bio,
  596. * so repeat the whole process until all the data can be handled.
  597. */
  598. while (remaining) {
  599. clone = crypt_alloc_buffer(io, remaining, &out_of_pages);
  600. if (unlikely(!clone)) {
  601. io->error = -ENOMEM;
  602. break;
  603. }
  604. io->ctx.bio_out = clone;
  605. io->ctx.idx_out = 0;
  606. remaining -= clone->bi_size;
  607. crypt_inc_pending(io);
  608. r = crypt_convert(cc, &io->ctx);
  609. crypt_finished = atomic_dec_and_test(&io->ctx.pending);
  610. /* Encryption was already finished, submit io now */
  611. if (crypt_finished) {
  612. kcryptd_crypt_write_io_submit(io, r, 0);
  613. /*
  614. * If there was an error, do not try next fragments.
  615. * For async, error is processed in async handler.
  616. */
  617. if (unlikely(r < 0))
  618. break;
  619. }
  620. /*
  621. * Out of memory -> run queues
  622. * But don't wait if split was due to the io size restriction
  623. */
  624. if (unlikely(out_of_pages))
  625. congestion_wait(WRITE, HZ/100);
  626. if (unlikely(remaining))
  627. wait_event(cc->writeq, !atomic_read(&io->ctx.pending));
  628. }
  629. crypt_dec_pending(io);
  630. }
  631. static void kcryptd_crypt_read_done(struct dm_crypt_io *io, int error)
  632. {
  633. if (unlikely(error < 0))
  634. io->error = -EIO;
  635. crypt_dec_pending(io);
  636. }
  637. static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
  638. {
  639. struct crypt_config *cc = io->target->private;
  640. int r = 0;
  641. crypt_inc_pending(io);
  642. crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
  643. io->sector);
  644. r = crypt_convert(cc, &io->ctx);
  645. if (atomic_dec_and_test(&io->ctx.pending))
  646. kcryptd_crypt_read_done(io, r);
  647. crypt_dec_pending(io);
  648. }
  649. static void kcryptd_async_done(struct crypto_async_request *async_req,
  650. int error)
  651. {
  652. struct convert_context *ctx = async_req->data;
  653. struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
  654. struct crypt_config *cc = io->target->private;
  655. if (error == -EINPROGRESS) {
  656. complete(&ctx->restart);
  657. return;
  658. }
  659. mempool_free(ablkcipher_request_cast(async_req), cc->req_pool);
  660. if (!atomic_dec_and_test(&ctx->pending))
  661. return;
  662. if (bio_data_dir(io->base_bio) == READ)
  663. kcryptd_crypt_read_done(io, error);
  664. else
  665. kcryptd_crypt_write_io_submit(io, error, 1);
  666. }
  667. static void kcryptd_crypt(struct work_struct *work)
  668. {
  669. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  670. if (bio_data_dir(io->base_bio) == READ)
  671. kcryptd_crypt_read_convert(io);
  672. else
  673. kcryptd_crypt_write_convert(io);
  674. }
  675. static void kcryptd_queue_crypt(struct dm_crypt_io *io)
  676. {
  677. struct crypt_config *cc = io->target->private;
  678. INIT_WORK(&io->work, kcryptd_crypt);
  679. queue_work(cc->crypt_queue, &io->work);
  680. }
  681. /*
  682. * Decode key from its hex representation
  683. */
  684. static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
  685. {
  686. char buffer[3];
  687. char *endp;
  688. unsigned int i;
  689. buffer[2] = '\0';
  690. for (i = 0; i < size; i++) {
  691. buffer[0] = *hex++;
  692. buffer[1] = *hex++;
  693. key[i] = (u8)simple_strtoul(buffer, &endp, 16);
  694. if (endp != &buffer[2])
  695. return -EINVAL;
  696. }
  697. if (*hex != '\0')
  698. return -EINVAL;
  699. return 0;
  700. }
  701. /*
  702. * Encode key into its hex representation
  703. */
  704. static void crypt_encode_key(char *hex, u8 *key, unsigned int size)
  705. {
  706. unsigned int i;
  707. for (i = 0; i < size; i++) {
  708. sprintf(hex, "%02x", *key);
  709. hex += 2;
  710. key++;
  711. }
  712. }
  713. static int crypt_set_key(struct crypt_config *cc, char *key)
  714. {
  715. unsigned key_size = strlen(key) >> 1;
  716. if (cc->key_size && cc->key_size != key_size)
  717. return -EINVAL;
  718. cc->key_size = key_size; /* initial settings */
  719. if ((!key_size && strcmp(key, "-")) ||
  720. (key_size && crypt_decode_key(cc->key, key, key_size) < 0))
  721. return -EINVAL;
  722. set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  723. return 0;
  724. }
  725. static int crypt_wipe_key(struct crypt_config *cc)
  726. {
  727. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  728. memset(&cc->key, 0, cc->key_size * sizeof(u8));
  729. return 0;
  730. }
  731. /*
  732. * Construct an encryption mapping:
  733. * <cipher> <key> <iv_offset> <dev_path> <start>
  734. */
  735. static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
  736. {
  737. struct crypt_config *cc;
  738. struct crypto_ablkcipher *tfm;
  739. char *tmp;
  740. char *cipher;
  741. char *chainmode;
  742. char *ivmode;
  743. char *ivopts;
  744. unsigned int key_size;
  745. unsigned long long tmpll;
  746. if (argc != 5) {
  747. ti->error = "Not enough arguments";
  748. return -EINVAL;
  749. }
  750. tmp = argv[0];
  751. cipher = strsep(&tmp, "-");
  752. chainmode = strsep(&tmp, "-");
  753. ivopts = strsep(&tmp, "-");
  754. ivmode = strsep(&ivopts, ":");
  755. if (tmp)
  756. DMWARN("Unexpected additional cipher options");
  757. key_size = strlen(argv[1]) >> 1;
  758. cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
  759. if (cc == NULL) {
  760. ti->error =
  761. "Cannot allocate transparent encryption context";
  762. return -ENOMEM;
  763. }
  764. if (crypt_set_key(cc, argv[1])) {
  765. ti->error = "Error decoding key";
  766. goto bad_cipher;
  767. }
  768. /* Compatiblity mode for old dm-crypt cipher strings */
  769. if (!chainmode || (strcmp(chainmode, "plain") == 0 && !ivmode)) {
  770. chainmode = "cbc";
  771. ivmode = "plain";
  772. }
  773. if (strcmp(chainmode, "ecb") && !ivmode) {
  774. ti->error = "This chaining mode requires an IV mechanism";
  775. goto bad_cipher;
  776. }
  777. if (snprintf(cc->cipher, CRYPTO_MAX_ALG_NAME, "%s(%s)",
  778. chainmode, cipher) >= CRYPTO_MAX_ALG_NAME) {
  779. ti->error = "Chain mode + cipher name is too long";
  780. goto bad_cipher;
  781. }
  782. tfm = crypto_alloc_ablkcipher(cc->cipher, 0, 0);
  783. if (IS_ERR(tfm)) {
  784. ti->error = "Error allocating crypto tfm";
  785. goto bad_cipher;
  786. }
  787. strcpy(cc->cipher, cipher);
  788. strcpy(cc->chainmode, chainmode);
  789. cc->tfm = tfm;
  790. /*
  791. * Choose ivmode. Valid modes: "plain", "essiv:<esshash>", "benbi".
  792. * See comments at iv code
  793. */
  794. if (ivmode == NULL)
  795. cc->iv_gen_ops = NULL;
  796. else if (strcmp(ivmode, "plain") == 0)
  797. cc->iv_gen_ops = &crypt_iv_plain_ops;
  798. else if (strcmp(ivmode, "essiv") == 0)
  799. cc->iv_gen_ops = &crypt_iv_essiv_ops;
  800. else if (strcmp(ivmode, "benbi") == 0)
  801. cc->iv_gen_ops = &crypt_iv_benbi_ops;
  802. else if (strcmp(ivmode, "null") == 0)
  803. cc->iv_gen_ops = &crypt_iv_null_ops;
  804. else {
  805. ti->error = "Invalid IV mode";
  806. goto bad_ivmode;
  807. }
  808. if (cc->iv_gen_ops && cc->iv_gen_ops->ctr &&
  809. cc->iv_gen_ops->ctr(cc, ti, ivopts) < 0)
  810. goto bad_ivmode;
  811. cc->iv_size = crypto_ablkcipher_ivsize(tfm);
  812. if (cc->iv_size)
  813. /* at least a 64 bit sector number should fit in our buffer */
  814. cc->iv_size = max(cc->iv_size,
  815. (unsigned int)(sizeof(u64) / sizeof(u8)));
  816. else {
  817. if (cc->iv_gen_ops) {
  818. DMWARN("Selected cipher does not support IVs");
  819. if (cc->iv_gen_ops->dtr)
  820. cc->iv_gen_ops->dtr(cc);
  821. cc->iv_gen_ops = NULL;
  822. }
  823. }
  824. cc->io_pool = mempool_create_slab_pool(MIN_IOS, _crypt_io_pool);
  825. if (!cc->io_pool) {
  826. ti->error = "Cannot allocate crypt io mempool";
  827. goto bad_slab_pool;
  828. }
  829. cc->dmreq_start = sizeof(struct ablkcipher_request);
  830. cc->dmreq_start += crypto_ablkcipher_reqsize(tfm);
  831. cc->dmreq_start = ALIGN(cc->dmreq_start, crypto_tfm_ctx_alignment());
  832. cc->dmreq_start += crypto_ablkcipher_alignmask(tfm) &
  833. ~(crypto_tfm_ctx_alignment() - 1);
  834. cc->req_pool = mempool_create_kmalloc_pool(MIN_IOS, cc->dmreq_start +
  835. sizeof(struct dm_crypt_request) + cc->iv_size);
  836. if (!cc->req_pool) {
  837. ti->error = "Cannot allocate crypt request mempool";
  838. goto bad_req_pool;
  839. }
  840. cc->req = NULL;
  841. cc->page_pool = mempool_create_page_pool(MIN_POOL_PAGES, 0);
  842. if (!cc->page_pool) {
  843. ti->error = "Cannot allocate page mempool";
  844. goto bad_page_pool;
  845. }
  846. cc->bs = bioset_create(MIN_IOS, MIN_IOS);
  847. if (!cc->bs) {
  848. ti->error = "Cannot allocate crypt bioset";
  849. goto bad_bs;
  850. }
  851. if (crypto_ablkcipher_setkey(tfm, cc->key, key_size) < 0) {
  852. ti->error = "Error setting key";
  853. goto bad_device;
  854. }
  855. if (sscanf(argv[2], "%llu", &tmpll) != 1) {
  856. ti->error = "Invalid iv_offset sector";
  857. goto bad_device;
  858. }
  859. cc->iv_offset = tmpll;
  860. if (sscanf(argv[4], "%llu", &tmpll) != 1) {
  861. ti->error = "Invalid device sector";
  862. goto bad_device;
  863. }
  864. cc->start = tmpll;
  865. if (dm_get_device(ti, argv[3], cc->start, ti->len,
  866. dm_table_get_mode(ti->table), &cc->dev)) {
  867. ti->error = "Device lookup failed";
  868. goto bad_device;
  869. }
  870. if (ivmode && cc->iv_gen_ops) {
  871. if (ivopts)
  872. *(ivopts - 1) = ':';
  873. cc->iv_mode = kmalloc(strlen(ivmode) + 1, GFP_KERNEL);
  874. if (!cc->iv_mode) {
  875. ti->error = "Error kmallocing iv_mode string";
  876. goto bad_ivmode_string;
  877. }
  878. strcpy(cc->iv_mode, ivmode);
  879. } else
  880. cc->iv_mode = NULL;
  881. cc->io_queue = create_singlethread_workqueue("kcryptd_io");
  882. if (!cc->io_queue) {
  883. ti->error = "Couldn't create kcryptd io queue";
  884. goto bad_io_queue;
  885. }
  886. cc->crypt_queue = create_singlethread_workqueue("kcryptd");
  887. if (!cc->crypt_queue) {
  888. ti->error = "Couldn't create kcryptd queue";
  889. goto bad_crypt_queue;
  890. }
  891. init_waitqueue_head(&cc->writeq);
  892. ti->private = cc;
  893. return 0;
  894. bad_crypt_queue:
  895. destroy_workqueue(cc->io_queue);
  896. bad_io_queue:
  897. kfree(cc->iv_mode);
  898. bad_ivmode_string:
  899. dm_put_device(ti, cc->dev);
  900. bad_device:
  901. bioset_free(cc->bs);
  902. bad_bs:
  903. mempool_destroy(cc->page_pool);
  904. bad_page_pool:
  905. mempool_destroy(cc->req_pool);
  906. bad_req_pool:
  907. mempool_destroy(cc->io_pool);
  908. bad_slab_pool:
  909. if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
  910. cc->iv_gen_ops->dtr(cc);
  911. bad_ivmode:
  912. crypto_free_ablkcipher(tfm);
  913. bad_cipher:
  914. /* Must zero key material before freeing */
  915. memset(cc, 0, sizeof(*cc) + cc->key_size * sizeof(u8));
  916. kfree(cc);
  917. return -EINVAL;
  918. }
  919. static void crypt_dtr(struct dm_target *ti)
  920. {
  921. struct crypt_config *cc = (struct crypt_config *) ti->private;
  922. destroy_workqueue(cc->io_queue);
  923. destroy_workqueue(cc->crypt_queue);
  924. if (cc->req)
  925. mempool_free(cc->req, cc->req_pool);
  926. bioset_free(cc->bs);
  927. mempool_destroy(cc->page_pool);
  928. mempool_destroy(cc->req_pool);
  929. mempool_destroy(cc->io_pool);
  930. kfree(cc->iv_mode);
  931. if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
  932. cc->iv_gen_ops->dtr(cc);
  933. crypto_free_ablkcipher(cc->tfm);
  934. dm_put_device(ti, cc->dev);
  935. /* Must zero key material before freeing */
  936. memset(cc, 0, sizeof(*cc) + cc->key_size * sizeof(u8));
  937. kfree(cc);
  938. }
  939. static int crypt_map(struct dm_target *ti, struct bio *bio,
  940. union map_info *map_context)
  941. {
  942. struct dm_crypt_io *io;
  943. io = crypt_io_alloc(ti, bio, bio->bi_sector - ti->begin);
  944. if (bio_data_dir(io->base_bio) == READ)
  945. kcryptd_queue_io(io);
  946. else
  947. kcryptd_queue_crypt(io);
  948. return DM_MAPIO_SUBMITTED;
  949. }
  950. static int crypt_status(struct dm_target *ti, status_type_t type,
  951. char *result, unsigned int maxlen)
  952. {
  953. struct crypt_config *cc = (struct crypt_config *) ti->private;
  954. unsigned int sz = 0;
  955. switch (type) {
  956. case STATUSTYPE_INFO:
  957. result[0] = '\0';
  958. break;
  959. case STATUSTYPE_TABLE:
  960. if (cc->iv_mode)
  961. DMEMIT("%s-%s-%s ", cc->cipher, cc->chainmode,
  962. cc->iv_mode);
  963. else
  964. DMEMIT("%s-%s ", cc->cipher, cc->chainmode);
  965. if (cc->key_size > 0) {
  966. if ((maxlen - sz) < ((cc->key_size << 1) + 1))
  967. return -ENOMEM;
  968. crypt_encode_key(result + sz, cc->key, cc->key_size);
  969. sz += cc->key_size << 1;
  970. } else {
  971. if (sz >= maxlen)
  972. return -ENOMEM;
  973. result[sz++] = '-';
  974. }
  975. DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
  976. cc->dev->name, (unsigned long long)cc->start);
  977. break;
  978. }
  979. return 0;
  980. }
  981. static void crypt_postsuspend(struct dm_target *ti)
  982. {
  983. struct crypt_config *cc = ti->private;
  984. set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  985. }
  986. static int crypt_preresume(struct dm_target *ti)
  987. {
  988. struct crypt_config *cc = ti->private;
  989. if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
  990. DMERR("aborting resume - crypt key is not set.");
  991. return -EAGAIN;
  992. }
  993. return 0;
  994. }
  995. static void crypt_resume(struct dm_target *ti)
  996. {
  997. struct crypt_config *cc = ti->private;
  998. clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  999. }
  1000. /* Message interface
  1001. * key set <key>
  1002. * key wipe
  1003. */
  1004. static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
  1005. {
  1006. struct crypt_config *cc = ti->private;
  1007. if (argc < 2)
  1008. goto error;
  1009. if (!strnicmp(argv[0], MESG_STR("key"))) {
  1010. if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
  1011. DMWARN("not suspended during key manipulation.");
  1012. return -EINVAL;
  1013. }
  1014. if (argc == 3 && !strnicmp(argv[1], MESG_STR("set")))
  1015. return crypt_set_key(cc, argv[2]);
  1016. if (argc == 2 && !strnicmp(argv[1], MESG_STR("wipe")))
  1017. return crypt_wipe_key(cc);
  1018. }
  1019. error:
  1020. DMWARN("unrecognised message received.");
  1021. return -EINVAL;
  1022. }
  1023. static int crypt_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
  1024. struct bio_vec *biovec, int max_size)
  1025. {
  1026. struct crypt_config *cc = ti->private;
  1027. struct request_queue *q = bdev_get_queue(cc->dev->bdev);
  1028. if (!q->merge_bvec_fn)
  1029. return max_size;
  1030. bvm->bi_bdev = cc->dev->bdev;
  1031. bvm->bi_sector = cc->start + bvm->bi_sector - ti->begin;
  1032. return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
  1033. }
  1034. static struct target_type crypt_target = {
  1035. .name = "crypt",
  1036. .version= {1, 6, 0},
  1037. .module = THIS_MODULE,
  1038. .ctr = crypt_ctr,
  1039. .dtr = crypt_dtr,
  1040. .map = crypt_map,
  1041. .status = crypt_status,
  1042. .postsuspend = crypt_postsuspend,
  1043. .preresume = crypt_preresume,
  1044. .resume = crypt_resume,
  1045. .message = crypt_message,
  1046. .merge = crypt_merge,
  1047. };
  1048. static int __init dm_crypt_init(void)
  1049. {
  1050. int r;
  1051. _crypt_io_pool = KMEM_CACHE(dm_crypt_io, 0);
  1052. if (!_crypt_io_pool)
  1053. return -ENOMEM;
  1054. r = dm_register_target(&crypt_target);
  1055. if (r < 0) {
  1056. DMERR("register failed %d", r);
  1057. kmem_cache_destroy(_crypt_io_pool);
  1058. }
  1059. return r;
  1060. }
  1061. static void __exit dm_crypt_exit(void)
  1062. {
  1063. int r = dm_unregister_target(&crypt_target);
  1064. if (r < 0)
  1065. DMERR("unregister failed %d", r);
  1066. kmem_cache_destroy(_crypt_io_pool);
  1067. }
  1068. module_init(dm_crypt_init);
  1069. module_exit(dm_crypt_exit);
  1070. MODULE_AUTHOR("Christophe Saout <christophe@saout.de>");
  1071. MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
  1072. MODULE_LICENSE("GPL");