dm-crypt.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102
  1. /*
  2. * Copyright (C) 2003 Jana Saout <jana@saout.de>
  3. * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
  4. * Copyright (C) 2006-2015 Red Hat, Inc. All rights reserved.
  5. * Copyright (C) 2013 Milan Broz <gmazyland@gmail.com>
  6. *
  7. * This file is released under the GPL.
  8. */
  9. #include <linux/completion.h>
  10. #include <linux/err.h>
  11. #include <linux/module.h>
  12. #include <linux/init.h>
  13. #include <linux/kernel.h>
  14. #include <linux/bio.h>
  15. #include <linux/blkdev.h>
  16. #include <linux/mempool.h>
  17. #include <linux/slab.h>
  18. #include <linux/crypto.h>
  19. #include <linux/workqueue.h>
  20. #include <linux/kthread.h>
  21. #include <linux/backing-dev.h>
  22. #include <linux/atomic.h>
  23. #include <linux/scatterlist.h>
  24. #include <linux/rbtree.h>
  25. #include <asm/page.h>
  26. #include <asm/unaligned.h>
  27. #include <crypto/hash.h>
  28. #include <crypto/md5.h>
  29. #include <crypto/algapi.h>
  30. #include <crypto/skcipher.h>
  31. #include <linux/device-mapper.h>
  32. #define DM_MSG_PREFIX "crypt"
  33. /*
  34. * context holding the current state of a multi-part conversion
  35. */
  36. struct convert_context {
  37. struct completion restart;
  38. struct bio *bio_in;
  39. struct bio *bio_out;
  40. struct bvec_iter iter_in;
  41. struct bvec_iter iter_out;
  42. sector_t cc_sector;
  43. atomic_t cc_pending;
  44. struct skcipher_request *req;
  45. };
  46. /*
  47. * per bio private data
  48. */
  49. struct dm_crypt_io {
  50. struct crypt_config *cc;
  51. struct bio *base_bio;
  52. struct work_struct work;
  53. struct convert_context ctx;
  54. atomic_t io_pending;
  55. int error;
  56. sector_t sector;
  57. struct rb_node rb_node;
  58. } CRYPTO_MINALIGN_ATTR;
  59. struct dm_crypt_request {
  60. struct convert_context *ctx;
  61. struct scatterlist sg_in;
  62. struct scatterlist sg_out;
  63. sector_t iv_sector;
  64. };
  65. struct crypt_config;
  66. struct crypt_iv_operations {
  67. int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
  68. const char *opts);
  69. void (*dtr)(struct crypt_config *cc);
  70. int (*init)(struct crypt_config *cc);
  71. int (*wipe)(struct crypt_config *cc);
  72. int (*generator)(struct crypt_config *cc, u8 *iv,
  73. struct dm_crypt_request *dmreq);
  74. int (*post)(struct crypt_config *cc, u8 *iv,
  75. struct dm_crypt_request *dmreq);
  76. };
  77. struct iv_essiv_private {
  78. struct crypto_ahash *hash_tfm;
  79. u8 *salt;
  80. };
  81. struct iv_benbi_private {
  82. int shift;
  83. };
  84. #define LMK_SEED_SIZE 64 /* hash + 0 */
  85. struct iv_lmk_private {
  86. struct crypto_shash *hash_tfm;
  87. u8 *seed;
  88. };
  89. #define TCW_WHITENING_SIZE 16
  90. struct iv_tcw_private {
  91. struct crypto_shash *crc32_tfm;
  92. u8 *iv_seed;
  93. u8 *whitening;
  94. };
  95. /*
  96. * Crypt: maps a linear range of a block device
  97. * and encrypts / decrypts at the same time.
  98. */
  99. enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
  100. DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD,
  101. DM_CRYPT_EXIT_THREAD};
  102. /*
  103. * The fields in here must be read only after initialization.
  104. */
  105. struct crypt_config {
  106. struct dm_dev *dev;
  107. sector_t start;
  108. /*
  109. * pool for per bio private data, crypto requests and
  110. * encryption requeusts/buffer pages
  111. */
  112. mempool_t *req_pool;
  113. mempool_t *page_pool;
  114. struct bio_set *bs;
  115. struct mutex bio_alloc_lock;
  116. struct workqueue_struct *io_queue;
  117. struct workqueue_struct *crypt_queue;
  118. struct task_struct *write_thread;
  119. wait_queue_head_t write_thread_wait;
  120. struct rb_root write_tree;
  121. char *cipher;
  122. char *cipher_string;
  123. struct crypt_iv_operations *iv_gen_ops;
  124. union {
  125. struct iv_essiv_private essiv;
  126. struct iv_benbi_private benbi;
  127. struct iv_lmk_private lmk;
  128. struct iv_tcw_private tcw;
  129. } iv_gen_private;
  130. sector_t iv_offset;
  131. unsigned int iv_size;
  132. /* ESSIV: struct crypto_cipher *essiv_tfm */
  133. void *iv_private;
  134. struct crypto_skcipher **tfms;
  135. unsigned tfms_count;
  136. /*
  137. * Layout of each crypto request:
  138. *
  139. * struct skcipher_request
  140. * context
  141. * padding
  142. * struct dm_crypt_request
  143. * padding
  144. * IV
  145. *
  146. * The padding is added so that dm_crypt_request and the IV are
  147. * correctly aligned.
  148. */
  149. unsigned int dmreq_start;
  150. unsigned int per_bio_data_size;
  151. unsigned long flags;
  152. unsigned int key_size;
  153. unsigned int key_parts; /* independent parts in key buffer */
  154. unsigned int key_extra_size; /* additional keys length */
  155. u8 key[0];
  156. };
  157. #define MIN_IOS 16
  158. static void clone_init(struct dm_crypt_io *, struct bio *);
  159. static void kcryptd_queue_crypt(struct dm_crypt_io *io);
  160. static u8 *iv_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq);
  161. /*
  162. * Use this to access cipher attributes that are the same for each CPU.
  163. */
  164. static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
  165. {
  166. return cc->tfms[0];
  167. }
  168. /*
  169. * Different IV generation algorithms:
  170. *
  171. * plain: the initial vector is the 32-bit little-endian version of the sector
  172. * number, padded with zeros if necessary.
  173. *
  174. * plain64: the initial vector is the 64-bit little-endian version of the sector
  175. * number, padded with zeros if necessary.
  176. *
  177. * essiv: "encrypted sector|salt initial vector", the sector number is
  178. * encrypted with the bulk cipher using a salt as key. The salt
  179. * should be derived from the bulk cipher's key via hashing.
  180. *
  181. * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
  182. * (needed for LRW-32-AES and possible other narrow block modes)
  183. *
  184. * null: the initial vector is always zero. Provides compatibility with
  185. * obsolete loop_fish2 devices. Do not use for new devices.
  186. *
  187. * lmk: Compatible implementation of the block chaining mode used
  188. * by the Loop-AES block device encryption system
  189. * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
  190. * It operates on full 512 byte sectors and uses CBC
  191. * with an IV derived from the sector number, the data and
  192. * optionally extra IV seed.
  193. * This means that after decryption the first block
  194. * of sector must be tweaked according to decrypted data.
  195. * Loop-AES can use three encryption schemes:
  196. * version 1: is plain aes-cbc mode
  197. * version 2: uses 64 multikey scheme with lmk IV generator
  198. * version 3: the same as version 2 with additional IV seed
  199. * (it uses 65 keys, last key is used as IV seed)
  200. *
  201. * tcw: Compatible implementation of the block chaining mode used
  202. * by the TrueCrypt device encryption system (prior to version 4.1).
  203. * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
  204. * It operates on full 512 byte sectors and uses CBC
  205. * with an IV derived from initial key and the sector number.
  206. * In addition, whitening value is applied on every sector, whitening
  207. * is calculated from initial key, sector number and mixed using CRC32.
  208. * Note that this encryption scheme is vulnerable to watermarking attacks
  209. * and should be used for old compatible containers access only.
  210. *
  211. * plumb: unimplemented, see:
  212. * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
  213. */
  214. static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
  215. struct dm_crypt_request *dmreq)
  216. {
  217. memset(iv, 0, cc->iv_size);
  218. *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
  219. return 0;
  220. }
  221. static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
  222. struct dm_crypt_request *dmreq)
  223. {
  224. memset(iv, 0, cc->iv_size);
  225. *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
  226. return 0;
  227. }
  228. /* Initialise ESSIV - compute salt but no local memory allocations */
  229. static int crypt_iv_essiv_init(struct crypt_config *cc)
  230. {
  231. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  232. AHASH_REQUEST_ON_STACK(req, essiv->hash_tfm);
  233. struct scatterlist sg;
  234. struct crypto_cipher *essiv_tfm;
  235. int err;
  236. sg_init_one(&sg, cc->key, cc->key_size);
  237. ahash_request_set_tfm(req, essiv->hash_tfm);
  238. ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP, NULL, NULL);
  239. ahash_request_set_crypt(req, &sg, essiv->salt, cc->key_size);
  240. err = crypto_ahash_digest(req);
  241. ahash_request_zero(req);
  242. if (err)
  243. return err;
  244. essiv_tfm = cc->iv_private;
  245. err = crypto_cipher_setkey(essiv_tfm, essiv->salt,
  246. crypto_ahash_digestsize(essiv->hash_tfm));
  247. if (err)
  248. return err;
  249. return 0;
  250. }
  251. /* Wipe salt and reset key derived from volume key */
  252. static int crypt_iv_essiv_wipe(struct crypt_config *cc)
  253. {
  254. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  255. unsigned salt_size = crypto_ahash_digestsize(essiv->hash_tfm);
  256. struct crypto_cipher *essiv_tfm;
  257. int r, err = 0;
  258. memset(essiv->salt, 0, salt_size);
  259. essiv_tfm = cc->iv_private;
  260. r = crypto_cipher_setkey(essiv_tfm, essiv->salt, salt_size);
  261. if (r)
  262. err = r;
  263. return err;
  264. }
  265. /* Set up per cpu cipher state */
  266. static struct crypto_cipher *setup_essiv_cpu(struct crypt_config *cc,
  267. struct dm_target *ti,
  268. u8 *salt, unsigned saltsize)
  269. {
  270. struct crypto_cipher *essiv_tfm;
  271. int err;
  272. /* Setup the essiv_tfm with the given salt */
  273. essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
  274. if (IS_ERR(essiv_tfm)) {
  275. ti->error = "Error allocating crypto tfm for ESSIV";
  276. return essiv_tfm;
  277. }
  278. if (crypto_cipher_blocksize(essiv_tfm) !=
  279. crypto_skcipher_ivsize(any_tfm(cc))) {
  280. ti->error = "Block size of ESSIV cipher does "
  281. "not match IV size of block cipher";
  282. crypto_free_cipher(essiv_tfm);
  283. return ERR_PTR(-EINVAL);
  284. }
  285. err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
  286. if (err) {
  287. ti->error = "Failed to set key for ESSIV cipher";
  288. crypto_free_cipher(essiv_tfm);
  289. return ERR_PTR(err);
  290. }
  291. return essiv_tfm;
  292. }
  293. static void crypt_iv_essiv_dtr(struct crypt_config *cc)
  294. {
  295. struct crypto_cipher *essiv_tfm;
  296. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  297. crypto_free_ahash(essiv->hash_tfm);
  298. essiv->hash_tfm = NULL;
  299. kzfree(essiv->salt);
  300. essiv->salt = NULL;
  301. essiv_tfm = cc->iv_private;
  302. if (essiv_tfm)
  303. crypto_free_cipher(essiv_tfm);
  304. cc->iv_private = NULL;
  305. }
  306. static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
  307. const char *opts)
  308. {
  309. struct crypto_cipher *essiv_tfm = NULL;
  310. struct crypto_ahash *hash_tfm = NULL;
  311. u8 *salt = NULL;
  312. int err;
  313. if (!opts) {
  314. ti->error = "Digest algorithm missing for ESSIV mode";
  315. return -EINVAL;
  316. }
  317. /* Allocate hash algorithm */
  318. hash_tfm = crypto_alloc_ahash(opts, 0, CRYPTO_ALG_ASYNC);
  319. if (IS_ERR(hash_tfm)) {
  320. ti->error = "Error initializing ESSIV hash";
  321. err = PTR_ERR(hash_tfm);
  322. goto bad;
  323. }
  324. salt = kzalloc(crypto_ahash_digestsize(hash_tfm), GFP_KERNEL);
  325. if (!salt) {
  326. ti->error = "Error kmallocing salt storage in ESSIV";
  327. err = -ENOMEM;
  328. goto bad;
  329. }
  330. cc->iv_gen_private.essiv.salt = salt;
  331. cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
  332. essiv_tfm = setup_essiv_cpu(cc, ti, salt,
  333. crypto_ahash_digestsize(hash_tfm));
  334. if (IS_ERR(essiv_tfm)) {
  335. crypt_iv_essiv_dtr(cc);
  336. return PTR_ERR(essiv_tfm);
  337. }
  338. cc->iv_private = essiv_tfm;
  339. return 0;
  340. bad:
  341. if (hash_tfm && !IS_ERR(hash_tfm))
  342. crypto_free_ahash(hash_tfm);
  343. kfree(salt);
  344. return err;
  345. }
  346. static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
  347. struct dm_crypt_request *dmreq)
  348. {
  349. struct crypto_cipher *essiv_tfm = cc->iv_private;
  350. memset(iv, 0, cc->iv_size);
  351. *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
  352. crypto_cipher_encrypt_one(essiv_tfm, iv, iv);
  353. return 0;
  354. }
  355. static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
  356. const char *opts)
  357. {
  358. unsigned bs = crypto_skcipher_blocksize(any_tfm(cc));
  359. int log = ilog2(bs);
  360. /* we need to calculate how far we must shift the sector count
  361. * to get the cipher block count, we use this shift in _gen */
  362. if (1 << log != bs) {
  363. ti->error = "cypher blocksize is not a power of 2";
  364. return -EINVAL;
  365. }
  366. if (log > 9) {
  367. ti->error = "cypher blocksize is > 512";
  368. return -EINVAL;
  369. }
  370. cc->iv_gen_private.benbi.shift = 9 - log;
  371. return 0;
  372. }
  373. static void crypt_iv_benbi_dtr(struct crypt_config *cc)
  374. {
  375. }
  376. static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
  377. struct dm_crypt_request *dmreq)
  378. {
  379. __be64 val;
  380. memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
  381. val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
  382. put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
  383. return 0;
  384. }
  385. static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
  386. struct dm_crypt_request *dmreq)
  387. {
  388. memset(iv, 0, cc->iv_size);
  389. return 0;
  390. }
  391. static void crypt_iv_lmk_dtr(struct crypt_config *cc)
  392. {
  393. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  394. if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
  395. crypto_free_shash(lmk->hash_tfm);
  396. lmk->hash_tfm = NULL;
  397. kzfree(lmk->seed);
  398. lmk->seed = NULL;
  399. }
  400. static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
  401. const char *opts)
  402. {
  403. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  404. lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
  405. if (IS_ERR(lmk->hash_tfm)) {
  406. ti->error = "Error initializing LMK hash";
  407. return PTR_ERR(lmk->hash_tfm);
  408. }
  409. /* No seed in LMK version 2 */
  410. if (cc->key_parts == cc->tfms_count) {
  411. lmk->seed = NULL;
  412. return 0;
  413. }
  414. lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
  415. if (!lmk->seed) {
  416. crypt_iv_lmk_dtr(cc);
  417. ti->error = "Error kmallocing seed storage in LMK";
  418. return -ENOMEM;
  419. }
  420. return 0;
  421. }
  422. static int crypt_iv_lmk_init(struct crypt_config *cc)
  423. {
  424. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  425. int subkey_size = cc->key_size / cc->key_parts;
  426. /* LMK seed is on the position of LMK_KEYS + 1 key */
  427. if (lmk->seed)
  428. memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
  429. crypto_shash_digestsize(lmk->hash_tfm));
  430. return 0;
  431. }
  432. static int crypt_iv_lmk_wipe(struct crypt_config *cc)
  433. {
  434. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  435. if (lmk->seed)
  436. memset(lmk->seed, 0, LMK_SEED_SIZE);
  437. return 0;
  438. }
  439. static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
  440. struct dm_crypt_request *dmreq,
  441. u8 *data)
  442. {
  443. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  444. SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
  445. struct md5_state md5state;
  446. __le32 buf[4];
  447. int i, r;
  448. desc->tfm = lmk->hash_tfm;
  449. desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
  450. r = crypto_shash_init(desc);
  451. if (r)
  452. return r;
  453. if (lmk->seed) {
  454. r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
  455. if (r)
  456. return r;
  457. }
  458. /* Sector is always 512B, block size 16, add data of blocks 1-31 */
  459. r = crypto_shash_update(desc, data + 16, 16 * 31);
  460. if (r)
  461. return r;
  462. /* Sector is cropped to 56 bits here */
  463. buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
  464. buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
  465. buf[2] = cpu_to_le32(4024);
  466. buf[3] = 0;
  467. r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
  468. if (r)
  469. return r;
  470. /* No MD5 padding here */
  471. r = crypto_shash_export(desc, &md5state);
  472. if (r)
  473. return r;
  474. for (i = 0; i < MD5_HASH_WORDS; i++)
  475. __cpu_to_le32s(&md5state.hash[i]);
  476. memcpy(iv, &md5state.hash, cc->iv_size);
  477. return 0;
  478. }
  479. static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
  480. struct dm_crypt_request *dmreq)
  481. {
  482. u8 *src;
  483. int r = 0;
  484. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
  485. src = kmap_atomic(sg_page(&dmreq->sg_in));
  486. r = crypt_iv_lmk_one(cc, iv, dmreq, src + dmreq->sg_in.offset);
  487. kunmap_atomic(src);
  488. } else
  489. memset(iv, 0, cc->iv_size);
  490. return r;
  491. }
  492. static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
  493. struct dm_crypt_request *dmreq)
  494. {
  495. u8 *dst;
  496. int r;
  497. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
  498. return 0;
  499. dst = kmap_atomic(sg_page(&dmreq->sg_out));
  500. r = crypt_iv_lmk_one(cc, iv, dmreq, dst + dmreq->sg_out.offset);
  501. /* Tweak the first block of plaintext sector */
  502. if (!r)
  503. crypto_xor(dst + dmreq->sg_out.offset, iv, cc->iv_size);
  504. kunmap_atomic(dst);
  505. return r;
  506. }
  507. static void crypt_iv_tcw_dtr(struct crypt_config *cc)
  508. {
  509. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  510. kzfree(tcw->iv_seed);
  511. tcw->iv_seed = NULL;
  512. kzfree(tcw->whitening);
  513. tcw->whitening = NULL;
  514. if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
  515. crypto_free_shash(tcw->crc32_tfm);
  516. tcw->crc32_tfm = NULL;
  517. }
  518. static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
  519. const char *opts)
  520. {
  521. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  522. if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
  523. ti->error = "Wrong key size for TCW";
  524. return -EINVAL;
  525. }
  526. tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
  527. if (IS_ERR(tcw->crc32_tfm)) {
  528. ti->error = "Error initializing CRC32 in TCW";
  529. return PTR_ERR(tcw->crc32_tfm);
  530. }
  531. tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
  532. tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
  533. if (!tcw->iv_seed || !tcw->whitening) {
  534. crypt_iv_tcw_dtr(cc);
  535. ti->error = "Error allocating seed storage in TCW";
  536. return -ENOMEM;
  537. }
  538. return 0;
  539. }
  540. static int crypt_iv_tcw_init(struct crypt_config *cc)
  541. {
  542. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  543. int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
  544. memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
  545. memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
  546. TCW_WHITENING_SIZE);
  547. return 0;
  548. }
  549. static int crypt_iv_tcw_wipe(struct crypt_config *cc)
  550. {
  551. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  552. memset(tcw->iv_seed, 0, cc->iv_size);
  553. memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
  554. return 0;
  555. }
  556. static int crypt_iv_tcw_whitening(struct crypt_config *cc,
  557. struct dm_crypt_request *dmreq,
  558. u8 *data)
  559. {
  560. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  561. u64 sector = cpu_to_le64((u64)dmreq->iv_sector);
  562. u8 buf[TCW_WHITENING_SIZE];
  563. SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
  564. int i, r;
  565. /* xor whitening with sector number */
  566. memcpy(buf, tcw->whitening, TCW_WHITENING_SIZE);
  567. crypto_xor(buf, (u8 *)&sector, 8);
  568. crypto_xor(&buf[8], (u8 *)&sector, 8);
  569. /* calculate crc32 for every 32bit part and xor it */
  570. desc->tfm = tcw->crc32_tfm;
  571. desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
  572. for (i = 0; i < 4; i++) {
  573. r = crypto_shash_init(desc);
  574. if (r)
  575. goto out;
  576. r = crypto_shash_update(desc, &buf[i * 4], 4);
  577. if (r)
  578. goto out;
  579. r = crypto_shash_final(desc, &buf[i * 4]);
  580. if (r)
  581. goto out;
  582. }
  583. crypto_xor(&buf[0], &buf[12], 4);
  584. crypto_xor(&buf[4], &buf[8], 4);
  585. /* apply whitening (8 bytes) to whole sector */
  586. for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
  587. crypto_xor(data + i * 8, buf, 8);
  588. out:
  589. memzero_explicit(buf, sizeof(buf));
  590. return r;
  591. }
  592. static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
  593. struct dm_crypt_request *dmreq)
  594. {
  595. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  596. u64 sector = cpu_to_le64((u64)dmreq->iv_sector);
  597. u8 *src;
  598. int r = 0;
  599. /* Remove whitening from ciphertext */
  600. if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
  601. src = kmap_atomic(sg_page(&dmreq->sg_in));
  602. r = crypt_iv_tcw_whitening(cc, dmreq, src + dmreq->sg_in.offset);
  603. kunmap_atomic(src);
  604. }
  605. /* Calculate IV */
  606. memcpy(iv, tcw->iv_seed, cc->iv_size);
  607. crypto_xor(iv, (u8 *)&sector, 8);
  608. if (cc->iv_size > 8)
  609. crypto_xor(&iv[8], (u8 *)&sector, cc->iv_size - 8);
  610. return r;
  611. }
  612. static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
  613. struct dm_crypt_request *dmreq)
  614. {
  615. u8 *dst;
  616. int r;
  617. if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
  618. return 0;
  619. /* Apply whitening on ciphertext */
  620. dst = kmap_atomic(sg_page(&dmreq->sg_out));
  621. r = crypt_iv_tcw_whitening(cc, dmreq, dst + dmreq->sg_out.offset);
  622. kunmap_atomic(dst);
  623. return r;
  624. }
  625. static struct crypt_iv_operations crypt_iv_plain_ops = {
  626. .generator = crypt_iv_plain_gen
  627. };
  628. static struct crypt_iv_operations crypt_iv_plain64_ops = {
  629. .generator = crypt_iv_plain64_gen
  630. };
  631. static struct crypt_iv_operations crypt_iv_essiv_ops = {
  632. .ctr = crypt_iv_essiv_ctr,
  633. .dtr = crypt_iv_essiv_dtr,
  634. .init = crypt_iv_essiv_init,
  635. .wipe = crypt_iv_essiv_wipe,
  636. .generator = crypt_iv_essiv_gen
  637. };
  638. static struct crypt_iv_operations crypt_iv_benbi_ops = {
  639. .ctr = crypt_iv_benbi_ctr,
  640. .dtr = crypt_iv_benbi_dtr,
  641. .generator = crypt_iv_benbi_gen
  642. };
  643. static struct crypt_iv_operations crypt_iv_null_ops = {
  644. .generator = crypt_iv_null_gen
  645. };
  646. static struct crypt_iv_operations crypt_iv_lmk_ops = {
  647. .ctr = crypt_iv_lmk_ctr,
  648. .dtr = crypt_iv_lmk_dtr,
  649. .init = crypt_iv_lmk_init,
  650. .wipe = crypt_iv_lmk_wipe,
  651. .generator = crypt_iv_lmk_gen,
  652. .post = crypt_iv_lmk_post
  653. };
  654. static struct crypt_iv_operations crypt_iv_tcw_ops = {
  655. .ctr = crypt_iv_tcw_ctr,
  656. .dtr = crypt_iv_tcw_dtr,
  657. .init = crypt_iv_tcw_init,
  658. .wipe = crypt_iv_tcw_wipe,
  659. .generator = crypt_iv_tcw_gen,
  660. .post = crypt_iv_tcw_post
  661. };
  662. static void crypt_convert_init(struct crypt_config *cc,
  663. struct convert_context *ctx,
  664. struct bio *bio_out, struct bio *bio_in,
  665. sector_t sector)
  666. {
  667. ctx->bio_in = bio_in;
  668. ctx->bio_out = bio_out;
  669. if (bio_in)
  670. ctx->iter_in = bio_in->bi_iter;
  671. if (bio_out)
  672. ctx->iter_out = bio_out->bi_iter;
  673. ctx->cc_sector = sector + cc->iv_offset;
  674. init_completion(&ctx->restart);
  675. }
  676. static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
  677. struct skcipher_request *req)
  678. {
  679. return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
  680. }
  681. static struct skcipher_request *req_of_dmreq(struct crypt_config *cc,
  682. struct dm_crypt_request *dmreq)
  683. {
  684. return (struct skcipher_request *)((char *)dmreq - cc->dmreq_start);
  685. }
  686. static u8 *iv_of_dmreq(struct crypt_config *cc,
  687. struct dm_crypt_request *dmreq)
  688. {
  689. return (u8 *)ALIGN((unsigned long)(dmreq + 1),
  690. crypto_skcipher_alignmask(any_tfm(cc)) + 1);
  691. }
  692. static int crypt_convert_block(struct crypt_config *cc,
  693. struct convert_context *ctx,
  694. struct skcipher_request *req)
  695. {
  696. struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
  697. struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
  698. struct dm_crypt_request *dmreq;
  699. u8 *iv;
  700. int r;
  701. dmreq = dmreq_of_req(cc, req);
  702. iv = iv_of_dmreq(cc, dmreq);
  703. dmreq->iv_sector = ctx->cc_sector;
  704. dmreq->ctx = ctx;
  705. sg_init_table(&dmreq->sg_in, 1);
  706. sg_set_page(&dmreq->sg_in, bv_in.bv_page, 1 << SECTOR_SHIFT,
  707. bv_in.bv_offset);
  708. sg_init_table(&dmreq->sg_out, 1);
  709. sg_set_page(&dmreq->sg_out, bv_out.bv_page, 1 << SECTOR_SHIFT,
  710. bv_out.bv_offset);
  711. bio_advance_iter(ctx->bio_in, &ctx->iter_in, 1 << SECTOR_SHIFT);
  712. bio_advance_iter(ctx->bio_out, &ctx->iter_out, 1 << SECTOR_SHIFT);
  713. if (cc->iv_gen_ops) {
  714. r = cc->iv_gen_ops->generator(cc, iv, dmreq);
  715. if (r < 0)
  716. return r;
  717. }
  718. skcipher_request_set_crypt(req, &dmreq->sg_in, &dmreq->sg_out,
  719. 1 << SECTOR_SHIFT, iv);
  720. if (bio_data_dir(ctx->bio_in) == WRITE)
  721. r = crypto_skcipher_encrypt(req);
  722. else
  723. r = crypto_skcipher_decrypt(req);
  724. if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
  725. r = cc->iv_gen_ops->post(cc, iv, dmreq);
  726. return r;
  727. }
  728. static void kcryptd_async_done(struct crypto_async_request *async_req,
  729. int error);
  730. static void crypt_alloc_req(struct crypt_config *cc,
  731. struct convert_context *ctx)
  732. {
  733. unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
  734. if (!ctx->req)
  735. ctx->req = mempool_alloc(cc->req_pool, GFP_NOIO);
  736. skcipher_request_set_tfm(ctx->req, cc->tfms[key_index]);
  737. /*
  738. * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
  739. * requests if driver request queue is full.
  740. */
  741. skcipher_request_set_callback(ctx->req,
  742. CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
  743. kcryptd_async_done, dmreq_of_req(cc, ctx->req));
  744. }
  745. static void crypt_free_req(struct crypt_config *cc,
  746. struct skcipher_request *req, struct bio *base_bio)
  747. {
  748. struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
  749. if ((struct skcipher_request *)(io + 1) != req)
  750. mempool_free(req, cc->req_pool);
  751. }
  752. /*
  753. * Encrypt / decrypt data from one bio to another one (can be the same one)
  754. */
  755. static int crypt_convert(struct crypt_config *cc,
  756. struct convert_context *ctx)
  757. {
  758. int r;
  759. atomic_set(&ctx->cc_pending, 1);
  760. while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
  761. crypt_alloc_req(cc, ctx);
  762. atomic_inc(&ctx->cc_pending);
  763. r = crypt_convert_block(cc, ctx, ctx->req);
  764. switch (r) {
  765. /*
  766. * The request was queued by a crypto driver
  767. * but the driver request queue is full, let's wait.
  768. */
  769. case -EBUSY:
  770. wait_for_completion(&ctx->restart);
  771. reinit_completion(&ctx->restart);
  772. /* fall through */
  773. /*
  774. * The request is queued and processed asynchronously,
  775. * completion function kcryptd_async_done() will be called.
  776. */
  777. case -EINPROGRESS:
  778. ctx->req = NULL;
  779. ctx->cc_sector++;
  780. continue;
  781. /*
  782. * The request was already processed (synchronously).
  783. */
  784. case 0:
  785. atomic_dec(&ctx->cc_pending);
  786. ctx->cc_sector++;
  787. cond_resched();
  788. continue;
  789. /* There was an error while processing the request. */
  790. default:
  791. atomic_dec(&ctx->cc_pending);
  792. return r;
  793. }
  794. }
  795. return 0;
  796. }
  797. static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
  798. /*
  799. * Generate a new unfragmented bio with the given size
  800. * This should never violate the device limitations (but only because
  801. * max_segment_size is being constrained to PAGE_SIZE).
  802. *
  803. * This function may be called concurrently. If we allocate from the mempool
  804. * concurrently, there is a possibility of deadlock. For example, if we have
  805. * mempool of 256 pages, two processes, each wanting 256, pages allocate from
  806. * the mempool concurrently, it may deadlock in a situation where both processes
  807. * have allocated 128 pages and the mempool is exhausted.
  808. *
  809. * In order to avoid this scenario we allocate the pages under a mutex.
  810. *
  811. * In order to not degrade performance with excessive locking, we try
  812. * non-blocking allocations without a mutex first but on failure we fallback
  813. * to blocking allocations with a mutex.
  814. */
  815. static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
  816. {
  817. struct crypt_config *cc = io->cc;
  818. struct bio *clone;
  819. unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
  820. gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
  821. unsigned i, len, remaining_size;
  822. struct page *page;
  823. struct bio_vec *bvec;
  824. retry:
  825. if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
  826. mutex_lock(&cc->bio_alloc_lock);
  827. clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, cc->bs);
  828. if (!clone)
  829. goto return_clone;
  830. clone_init(io, clone);
  831. remaining_size = size;
  832. for (i = 0; i < nr_iovecs; i++) {
  833. page = mempool_alloc(cc->page_pool, gfp_mask);
  834. if (!page) {
  835. crypt_free_buffer_pages(cc, clone);
  836. bio_put(clone);
  837. gfp_mask |= __GFP_DIRECT_RECLAIM;
  838. goto retry;
  839. }
  840. len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
  841. bvec = &clone->bi_io_vec[clone->bi_vcnt++];
  842. bvec->bv_page = page;
  843. bvec->bv_len = len;
  844. bvec->bv_offset = 0;
  845. clone->bi_iter.bi_size += len;
  846. remaining_size -= len;
  847. }
  848. return_clone:
  849. if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
  850. mutex_unlock(&cc->bio_alloc_lock);
  851. return clone;
  852. }
  853. static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
  854. {
  855. unsigned int i;
  856. struct bio_vec *bv;
  857. bio_for_each_segment_all(bv, clone, i) {
  858. BUG_ON(!bv->bv_page);
  859. mempool_free(bv->bv_page, cc->page_pool);
  860. bv->bv_page = NULL;
  861. }
  862. }
  863. static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
  864. struct bio *bio, sector_t sector)
  865. {
  866. io->cc = cc;
  867. io->base_bio = bio;
  868. io->sector = sector;
  869. io->error = 0;
  870. io->ctx.req = NULL;
  871. atomic_set(&io->io_pending, 0);
  872. }
  873. static void crypt_inc_pending(struct dm_crypt_io *io)
  874. {
  875. atomic_inc(&io->io_pending);
  876. }
  877. /*
  878. * One of the bios was finished. Check for completion of
  879. * the whole request and correctly clean up the buffer.
  880. */
  881. static void crypt_dec_pending(struct dm_crypt_io *io)
  882. {
  883. struct crypt_config *cc = io->cc;
  884. struct bio *base_bio = io->base_bio;
  885. int error = io->error;
  886. if (!atomic_dec_and_test(&io->io_pending))
  887. return;
  888. if (io->ctx.req)
  889. crypt_free_req(cc, io->ctx.req, base_bio);
  890. base_bio->bi_error = error;
  891. bio_endio(base_bio);
  892. }
  893. /*
  894. * kcryptd/kcryptd_io:
  895. *
  896. * Needed because it would be very unwise to do decryption in an
  897. * interrupt context.
  898. *
  899. * kcryptd performs the actual encryption or decryption.
  900. *
  901. * kcryptd_io performs the IO submission.
  902. *
  903. * They must be separated as otherwise the final stages could be
  904. * starved by new requests which can block in the first stages due
  905. * to memory allocation.
  906. *
  907. * The work is done per CPU global for all dm-crypt instances.
  908. * They should not depend on each other and do not block.
  909. */
  910. static void crypt_endio(struct bio *clone)
  911. {
  912. struct dm_crypt_io *io = clone->bi_private;
  913. struct crypt_config *cc = io->cc;
  914. unsigned rw = bio_data_dir(clone);
  915. int error;
  916. /*
  917. * free the processed pages
  918. */
  919. if (rw == WRITE)
  920. crypt_free_buffer_pages(cc, clone);
  921. error = clone->bi_error;
  922. bio_put(clone);
  923. if (rw == READ && !error) {
  924. kcryptd_queue_crypt(io);
  925. return;
  926. }
  927. if (unlikely(error))
  928. io->error = error;
  929. crypt_dec_pending(io);
  930. }
  931. static void clone_init(struct dm_crypt_io *io, struct bio *clone)
  932. {
  933. struct crypt_config *cc = io->cc;
  934. clone->bi_private = io;
  935. clone->bi_end_io = crypt_endio;
  936. clone->bi_bdev = cc->dev->bdev;
  937. clone->bi_rw = io->base_bio->bi_rw;
  938. }
  939. static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
  940. {
  941. struct crypt_config *cc = io->cc;
  942. struct bio *clone;
  943. /*
  944. * We need the original biovec array in order to decrypt
  945. * the whole bio data *afterwards* -- thanks to immutable
  946. * biovecs we don't need to worry about the block layer
  947. * modifying the biovec array; so leverage bio_clone_fast().
  948. */
  949. clone = bio_clone_fast(io->base_bio, gfp, cc->bs);
  950. if (!clone)
  951. return 1;
  952. crypt_inc_pending(io);
  953. clone_init(io, clone);
  954. clone->bi_iter.bi_sector = cc->start + io->sector;
  955. generic_make_request(clone);
  956. return 0;
  957. }
  958. static void kcryptd_io_read_work(struct work_struct *work)
  959. {
  960. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  961. crypt_inc_pending(io);
  962. if (kcryptd_io_read(io, GFP_NOIO))
  963. io->error = -ENOMEM;
  964. crypt_dec_pending(io);
  965. }
  966. static void kcryptd_queue_read(struct dm_crypt_io *io)
  967. {
  968. struct crypt_config *cc = io->cc;
  969. INIT_WORK(&io->work, kcryptd_io_read_work);
  970. queue_work(cc->io_queue, &io->work);
  971. }
  972. static void kcryptd_io_write(struct dm_crypt_io *io)
  973. {
  974. struct bio *clone = io->ctx.bio_out;
  975. generic_make_request(clone);
  976. }
  977. #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
  978. static int dmcrypt_write(void *data)
  979. {
  980. struct crypt_config *cc = data;
  981. struct dm_crypt_io *io;
  982. while (1) {
  983. struct rb_root write_tree;
  984. struct blk_plug plug;
  985. DECLARE_WAITQUEUE(wait, current);
  986. spin_lock_irq(&cc->write_thread_wait.lock);
  987. continue_locked:
  988. if (!RB_EMPTY_ROOT(&cc->write_tree))
  989. goto pop_from_list;
  990. if (unlikely(test_bit(DM_CRYPT_EXIT_THREAD, &cc->flags))) {
  991. spin_unlock_irq(&cc->write_thread_wait.lock);
  992. break;
  993. }
  994. __set_current_state(TASK_INTERRUPTIBLE);
  995. __add_wait_queue(&cc->write_thread_wait, &wait);
  996. spin_unlock_irq(&cc->write_thread_wait.lock);
  997. schedule();
  998. spin_lock_irq(&cc->write_thread_wait.lock);
  999. __remove_wait_queue(&cc->write_thread_wait, &wait);
  1000. goto continue_locked;
  1001. pop_from_list:
  1002. write_tree = cc->write_tree;
  1003. cc->write_tree = RB_ROOT;
  1004. spin_unlock_irq(&cc->write_thread_wait.lock);
  1005. BUG_ON(rb_parent(write_tree.rb_node));
  1006. /*
  1007. * Note: we cannot walk the tree here with rb_next because
  1008. * the structures may be freed when kcryptd_io_write is called.
  1009. */
  1010. blk_start_plug(&plug);
  1011. do {
  1012. io = crypt_io_from_node(rb_first(&write_tree));
  1013. rb_erase(&io->rb_node, &write_tree);
  1014. kcryptd_io_write(io);
  1015. } while (!RB_EMPTY_ROOT(&write_tree));
  1016. blk_finish_plug(&plug);
  1017. }
  1018. return 0;
  1019. }
  1020. static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
  1021. {
  1022. struct bio *clone = io->ctx.bio_out;
  1023. struct crypt_config *cc = io->cc;
  1024. unsigned long flags;
  1025. sector_t sector;
  1026. struct rb_node **rbp, *parent;
  1027. if (unlikely(io->error < 0)) {
  1028. crypt_free_buffer_pages(cc, clone);
  1029. bio_put(clone);
  1030. crypt_dec_pending(io);
  1031. return;
  1032. }
  1033. /* crypt_convert should have filled the clone bio */
  1034. BUG_ON(io->ctx.iter_out.bi_size);
  1035. clone->bi_iter.bi_sector = cc->start + io->sector;
  1036. if (likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) {
  1037. generic_make_request(clone);
  1038. return;
  1039. }
  1040. spin_lock_irqsave(&cc->write_thread_wait.lock, flags);
  1041. rbp = &cc->write_tree.rb_node;
  1042. parent = NULL;
  1043. sector = io->sector;
  1044. while (*rbp) {
  1045. parent = *rbp;
  1046. if (sector < crypt_io_from_node(parent)->sector)
  1047. rbp = &(*rbp)->rb_left;
  1048. else
  1049. rbp = &(*rbp)->rb_right;
  1050. }
  1051. rb_link_node(&io->rb_node, parent, rbp);
  1052. rb_insert_color(&io->rb_node, &cc->write_tree);
  1053. wake_up_locked(&cc->write_thread_wait);
  1054. spin_unlock_irqrestore(&cc->write_thread_wait.lock, flags);
  1055. }
  1056. static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
  1057. {
  1058. struct crypt_config *cc = io->cc;
  1059. struct bio *clone;
  1060. int crypt_finished;
  1061. sector_t sector = io->sector;
  1062. int r;
  1063. /*
  1064. * Prevent io from disappearing until this function completes.
  1065. */
  1066. crypt_inc_pending(io);
  1067. crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
  1068. clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
  1069. if (unlikely(!clone)) {
  1070. io->error = -EIO;
  1071. goto dec;
  1072. }
  1073. io->ctx.bio_out = clone;
  1074. io->ctx.iter_out = clone->bi_iter;
  1075. sector += bio_sectors(clone);
  1076. crypt_inc_pending(io);
  1077. r = crypt_convert(cc, &io->ctx);
  1078. if (r)
  1079. io->error = -EIO;
  1080. crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
  1081. /* Encryption was already finished, submit io now */
  1082. if (crypt_finished) {
  1083. kcryptd_crypt_write_io_submit(io, 0);
  1084. io->sector = sector;
  1085. }
  1086. dec:
  1087. crypt_dec_pending(io);
  1088. }
  1089. static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
  1090. {
  1091. crypt_dec_pending(io);
  1092. }
  1093. static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
  1094. {
  1095. struct crypt_config *cc = io->cc;
  1096. int r = 0;
  1097. crypt_inc_pending(io);
  1098. crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
  1099. io->sector);
  1100. r = crypt_convert(cc, &io->ctx);
  1101. if (r < 0)
  1102. io->error = -EIO;
  1103. if (atomic_dec_and_test(&io->ctx.cc_pending))
  1104. kcryptd_crypt_read_done(io);
  1105. crypt_dec_pending(io);
  1106. }
  1107. static void kcryptd_async_done(struct crypto_async_request *async_req,
  1108. int error)
  1109. {
  1110. struct dm_crypt_request *dmreq = async_req->data;
  1111. struct convert_context *ctx = dmreq->ctx;
  1112. struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
  1113. struct crypt_config *cc = io->cc;
  1114. /*
  1115. * A request from crypto driver backlog is going to be processed now,
  1116. * finish the completion and continue in crypt_convert().
  1117. * (Callback will be called for the second time for this request.)
  1118. */
  1119. if (error == -EINPROGRESS) {
  1120. complete(&ctx->restart);
  1121. return;
  1122. }
  1123. if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
  1124. error = cc->iv_gen_ops->post(cc, iv_of_dmreq(cc, dmreq), dmreq);
  1125. if (error < 0)
  1126. io->error = -EIO;
  1127. crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
  1128. if (!atomic_dec_and_test(&ctx->cc_pending))
  1129. return;
  1130. if (bio_data_dir(io->base_bio) == READ)
  1131. kcryptd_crypt_read_done(io);
  1132. else
  1133. kcryptd_crypt_write_io_submit(io, 1);
  1134. }
  1135. static void kcryptd_crypt(struct work_struct *work)
  1136. {
  1137. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  1138. if (bio_data_dir(io->base_bio) == READ)
  1139. kcryptd_crypt_read_convert(io);
  1140. else
  1141. kcryptd_crypt_write_convert(io);
  1142. }
  1143. static void kcryptd_queue_crypt(struct dm_crypt_io *io)
  1144. {
  1145. struct crypt_config *cc = io->cc;
  1146. INIT_WORK(&io->work, kcryptd_crypt);
  1147. queue_work(cc->crypt_queue, &io->work);
  1148. }
  1149. /*
  1150. * Decode key from its hex representation
  1151. */
  1152. static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
  1153. {
  1154. char buffer[3];
  1155. unsigned int i;
  1156. buffer[2] = '\0';
  1157. for (i = 0; i < size; i++) {
  1158. buffer[0] = *hex++;
  1159. buffer[1] = *hex++;
  1160. if (kstrtou8(buffer, 16, &key[i]))
  1161. return -EINVAL;
  1162. }
  1163. if (*hex != '\0')
  1164. return -EINVAL;
  1165. return 0;
  1166. }
  1167. static void crypt_free_tfms(struct crypt_config *cc)
  1168. {
  1169. unsigned i;
  1170. if (!cc->tfms)
  1171. return;
  1172. for (i = 0; i < cc->tfms_count; i++)
  1173. if (cc->tfms[i] && !IS_ERR(cc->tfms[i])) {
  1174. crypto_free_skcipher(cc->tfms[i]);
  1175. cc->tfms[i] = NULL;
  1176. }
  1177. kfree(cc->tfms);
  1178. cc->tfms = NULL;
  1179. }
  1180. static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
  1181. {
  1182. unsigned i;
  1183. int err;
  1184. cc->tfms = kmalloc(cc->tfms_count * sizeof(struct crypto_skcipher *),
  1185. GFP_KERNEL);
  1186. if (!cc->tfms)
  1187. return -ENOMEM;
  1188. for (i = 0; i < cc->tfms_count; i++) {
  1189. cc->tfms[i] = crypto_alloc_skcipher(ciphermode, 0, 0);
  1190. if (IS_ERR(cc->tfms[i])) {
  1191. err = PTR_ERR(cc->tfms[i]);
  1192. crypt_free_tfms(cc);
  1193. return err;
  1194. }
  1195. }
  1196. return 0;
  1197. }
  1198. static int crypt_setkey_allcpus(struct crypt_config *cc)
  1199. {
  1200. unsigned subkey_size;
  1201. int err = 0, i, r;
  1202. /* Ignore extra keys (which are used for IV etc) */
  1203. subkey_size = (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
  1204. for (i = 0; i < cc->tfms_count; i++) {
  1205. r = crypto_skcipher_setkey(cc->tfms[i],
  1206. cc->key + (i * subkey_size),
  1207. subkey_size);
  1208. if (r)
  1209. err = r;
  1210. }
  1211. return err;
  1212. }
  1213. static int crypt_set_key(struct crypt_config *cc, char *key)
  1214. {
  1215. int r = -EINVAL;
  1216. int key_string_len = strlen(key);
  1217. /* The key size may not be changed. */
  1218. if (cc->key_size != (key_string_len >> 1))
  1219. goto out;
  1220. /* Hyphen (which gives a key_size of zero) means there is no key. */
  1221. if (!cc->key_size && strcmp(key, "-"))
  1222. goto out;
  1223. if (cc->key_size && crypt_decode_key(cc->key, key, cc->key_size) < 0)
  1224. goto out;
  1225. set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1226. r = crypt_setkey_allcpus(cc);
  1227. out:
  1228. /* Hex key string not needed after here, so wipe it. */
  1229. memset(key, '0', key_string_len);
  1230. return r;
  1231. }
  1232. static int crypt_wipe_key(struct crypt_config *cc)
  1233. {
  1234. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1235. memset(&cc->key, 0, cc->key_size * sizeof(u8));
  1236. return crypt_setkey_allcpus(cc);
  1237. }
  1238. static void crypt_dtr(struct dm_target *ti)
  1239. {
  1240. struct crypt_config *cc = ti->private;
  1241. ti->private = NULL;
  1242. if (!cc)
  1243. return;
  1244. if (cc->write_thread) {
  1245. spin_lock_irq(&cc->write_thread_wait.lock);
  1246. set_bit(DM_CRYPT_EXIT_THREAD, &cc->flags);
  1247. wake_up_locked(&cc->write_thread_wait);
  1248. spin_unlock_irq(&cc->write_thread_wait.lock);
  1249. kthread_stop(cc->write_thread);
  1250. }
  1251. if (cc->io_queue)
  1252. destroy_workqueue(cc->io_queue);
  1253. if (cc->crypt_queue)
  1254. destroy_workqueue(cc->crypt_queue);
  1255. crypt_free_tfms(cc);
  1256. if (cc->bs)
  1257. bioset_free(cc->bs);
  1258. mempool_destroy(cc->page_pool);
  1259. mempool_destroy(cc->req_pool);
  1260. if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
  1261. cc->iv_gen_ops->dtr(cc);
  1262. if (cc->dev)
  1263. dm_put_device(ti, cc->dev);
  1264. kzfree(cc->cipher);
  1265. kzfree(cc->cipher_string);
  1266. /* Must zero key material before freeing */
  1267. kzfree(cc);
  1268. }
  1269. static int crypt_ctr_cipher(struct dm_target *ti,
  1270. char *cipher_in, char *key)
  1271. {
  1272. struct crypt_config *cc = ti->private;
  1273. char *tmp, *cipher, *chainmode, *ivmode, *ivopts, *keycount;
  1274. char *cipher_api = NULL;
  1275. int ret = -EINVAL;
  1276. char dummy;
  1277. /* Convert to crypto api definition? */
  1278. if (strchr(cipher_in, '(')) {
  1279. ti->error = "Bad cipher specification";
  1280. return -EINVAL;
  1281. }
  1282. cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
  1283. if (!cc->cipher_string)
  1284. goto bad_mem;
  1285. /*
  1286. * Legacy dm-crypt cipher specification
  1287. * cipher[:keycount]-mode-iv:ivopts
  1288. */
  1289. tmp = cipher_in;
  1290. keycount = strsep(&tmp, "-");
  1291. cipher = strsep(&keycount, ":");
  1292. if (!keycount)
  1293. cc->tfms_count = 1;
  1294. else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
  1295. !is_power_of_2(cc->tfms_count)) {
  1296. ti->error = "Bad cipher key count specification";
  1297. return -EINVAL;
  1298. }
  1299. cc->key_parts = cc->tfms_count;
  1300. cc->key_extra_size = 0;
  1301. cc->cipher = kstrdup(cipher, GFP_KERNEL);
  1302. if (!cc->cipher)
  1303. goto bad_mem;
  1304. chainmode = strsep(&tmp, "-");
  1305. ivopts = strsep(&tmp, "-");
  1306. ivmode = strsep(&ivopts, ":");
  1307. if (tmp)
  1308. DMWARN("Ignoring unexpected additional cipher options");
  1309. /*
  1310. * For compatibility with the original dm-crypt mapping format, if
  1311. * only the cipher name is supplied, use cbc-plain.
  1312. */
  1313. if (!chainmode || (!strcmp(chainmode, "plain") && !ivmode)) {
  1314. chainmode = "cbc";
  1315. ivmode = "plain";
  1316. }
  1317. if (strcmp(chainmode, "ecb") && !ivmode) {
  1318. ti->error = "IV mechanism required";
  1319. return -EINVAL;
  1320. }
  1321. cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
  1322. if (!cipher_api)
  1323. goto bad_mem;
  1324. ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
  1325. "%s(%s)", chainmode, cipher);
  1326. if (ret < 0) {
  1327. kfree(cipher_api);
  1328. goto bad_mem;
  1329. }
  1330. /* Allocate cipher */
  1331. ret = crypt_alloc_tfms(cc, cipher_api);
  1332. if (ret < 0) {
  1333. ti->error = "Error allocating crypto tfm";
  1334. goto bad;
  1335. }
  1336. /* Initialize IV */
  1337. cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
  1338. if (cc->iv_size)
  1339. /* at least a 64 bit sector number should fit in our buffer */
  1340. cc->iv_size = max(cc->iv_size,
  1341. (unsigned int)(sizeof(u64) / sizeof(u8)));
  1342. else if (ivmode) {
  1343. DMWARN("Selected cipher does not support IVs");
  1344. ivmode = NULL;
  1345. }
  1346. /* Choose ivmode, see comments at iv code. */
  1347. if (ivmode == NULL)
  1348. cc->iv_gen_ops = NULL;
  1349. else if (strcmp(ivmode, "plain") == 0)
  1350. cc->iv_gen_ops = &crypt_iv_plain_ops;
  1351. else if (strcmp(ivmode, "plain64") == 0)
  1352. cc->iv_gen_ops = &crypt_iv_plain64_ops;
  1353. else if (strcmp(ivmode, "essiv") == 0)
  1354. cc->iv_gen_ops = &crypt_iv_essiv_ops;
  1355. else if (strcmp(ivmode, "benbi") == 0)
  1356. cc->iv_gen_ops = &crypt_iv_benbi_ops;
  1357. else if (strcmp(ivmode, "null") == 0)
  1358. cc->iv_gen_ops = &crypt_iv_null_ops;
  1359. else if (strcmp(ivmode, "lmk") == 0) {
  1360. cc->iv_gen_ops = &crypt_iv_lmk_ops;
  1361. /*
  1362. * Version 2 and 3 is recognised according
  1363. * to length of provided multi-key string.
  1364. * If present (version 3), last key is used as IV seed.
  1365. * All keys (including IV seed) are always the same size.
  1366. */
  1367. if (cc->key_size % cc->key_parts) {
  1368. cc->key_parts++;
  1369. cc->key_extra_size = cc->key_size / cc->key_parts;
  1370. }
  1371. } else if (strcmp(ivmode, "tcw") == 0) {
  1372. cc->iv_gen_ops = &crypt_iv_tcw_ops;
  1373. cc->key_parts += 2; /* IV + whitening */
  1374. cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
  1375. } else {
  1376. ret = -EINVAL;
  1377. ti->error = "Invalid IV mode";
  1378. goto bad;
  1379. }
  1380. /* Initialize and set key */
  1381. ret = crypt_set_key(cc, key);
  1382. if (ret < 0) {
  1383. ti->error = "Error decoding and setting key";
  1384. goto bad;
  1385. }
  1386. /* Allocate IV */
  1387. if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
  1388. ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
  1389. if (ret < 0) {
  1390. ti->error = "Error creating IV";
  1391. goto bad;
  1392. }
  1393. }
  1394. /* Initialize IV (set keys for ESSIV etc) */
  1395. if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
  1396. ret = cc->iv_gen_ops->init(cc);
  1397. if (ret < 0) {
  1398. ti->error = "Error initialising IV";
  1399. goto bad;
  1400. }
  1401. }
  1402. ret = 0;
  1403. bad:
  1404. kfree(cipher_api);
  1405. return ret;
  1406. bad_mem:
  1407. ti->error = "Cannot allocate cipher strings";
  1408. return -ENOMEM;
  1409. }
  1410. /*
  1411. * Construct an encryption mapping:
  1412. * <cipher> <key> <iv_offset> <dev_path> <start>
  1413. */
  1414. static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
  1415. {
  1416. struct crypt_config *cc;
  1417. unsigned int key_size, opt_params;
  1418. unsigned long long tmpll;
  1419. int ret;
  1420. size_t iv_size_padding;
  1421. struct dm_arg_set as;
  1422. const char *opt_string;
  1423. char dummy;
  1424. static struct dm_arg _args[] = {
  1425. {0, 3, "Invalid number of feature args"},
  1426. };
  1427. if (argc < 5) {
  1428. ti->error = "Not enough arguments";
  1429. return -EINVAL;
  1430. }
  1431. key_size = strlen(argv[1]) >> 1;
  1432. cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
  1433. if (!cc) {
  1434. ti->error = "Cannot allocate encryption context";
  1435. return -ENOMEM;
  1436. }
  1437. cc->key_size = key_size;
  1438. ti->private = cc;
  1439. ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
  1440. if (ret < 0)
  1441. goto bad;
  1442. cc->dmreq_start = sizeof(struct skcipher_request);
  1443. cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
  1444. cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
  1445. if (crypto_skcipher_alignmask(any_tfm(cc)) < CRYPTO_MINALIGN) {
  1446. /* Allocate the padding exactly */
  1447. iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
  1448. & crypto_skcipher_alignmask(any_tfm(cc));
  1449. } else {
  1450. /*
  1451. * If the cipher requires greater alignment than kmalloc
  1452. * alignment, we don't know the exact position of the
  1453. * initialization vector. We must assume worst case.
  1454. */
  1455. iv_size_padding = crypto_skcipher_alignmask(any_tfm(cc));
  1456. }
  1457. ret = -ENOMEM;
  1458. cc->req_pool = mempool_create_kmalloc_pool(MIN_IOS, cc->dmreq_start +
  1459. sizeof(struct dm_crypt_request) + iv_size_padding + cc->iv_size);
  1460. if (!cc->req_pool) {
  1461. ti->error = "Cannot allocate crypt request mempool";
  1462. goto bad;
  1463. }
  1464. cc->per_bio_data_size = ti->per_io_data_size =
  1465. ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start +
  1466. sizeof(struct dm_crypt_request) + iv_size_padding + cc->iv_size,
  1467. ARCH_KMALLOC_MINALIGN);
  1468. cc->page_pool = mempool_create_page_pool(BIO_MAX_PAGES, 0);
  1469. if (!cc->page_pool) {
  1470. ti->error = "Cannot allocate page mempool";
  1471. goto bad;
  1472. }
  1473. cc->bs = bioset_create(MIN_IOS, 0);
  1474. if (!cc->bs) {
  1475. ti->error = "Cannot allocate crypt bioset";
  1476. goto bad;
  1477. }
  1478. mutex_init(&cc->bio_alloc_lock);
  1479. ret = -EINVAL;
  1480. if (sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) {
  1481. ti->error = "Invalid iv_offset sector";
  1482. goto bad;
  1483. }
  1484. cc->iv_offset = tmpll;
  1485. ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
  1486. if (ret) {
  1487. ti->error = "Device lookup failed";
  1488. goto bad;
  1489. }
  1490. ret = -EINVAL;
  1491. if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1) {
  1492. ti->error = "Invalid device sector";
  1493. goto bad;
  1494. }
  1495. cc->start = tmpll;
  1496. argv += 5;
  1497. argc -= 5;
  1498. /* Optional parameters */
  1499. if (argc) {
  1500. as.argc = argc;
  1501. as.argv = argv;
  1502. ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
  1503. if (ret)
  1504. goto bad;
  1505. ret = -EINVAL;
  1506. while (opt_params--) {
  1507. opt_string = dm_shift_arg(&as);
  1508. if (!opt_string) {
  1509. ti->error = "Not enough feature arguments";
  1510. goto bad;
  1511. }
  1512. if (!strcasecmp(opt_string, "allow_discards"))
  1513. ti->num_discard_bios = 1;
  1514. else if (!strcasecmp(opt_string, "same_cpu_crypt"))
  1515. set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
  1516. else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
  1517. set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
  1518. else {
  1519. ti->error = "Invalid feature arguments";
  1520. goto bad;
  1521. }
  1522. }
  1523. }
  1524. ret = -ENOMEM;
  1525. cc->io_queue = alloc_workqueue("kcryptd_io", WQ_MEM_RECLAIM, 1);
  1526. if (!cc->io_queue) {
  1527. ti->error = "Couldn't create kcryptd io queue";
  1528. goto bad;
  1529. }
  1530. if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
  1531. cc->crypt_queue = alloc_workqueue("kcryptd", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 1);
  1532. else
  1533. cc->crypt_queue = alloc_workqueue("kcryptd", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
  1534. num_online_cpus());
  1535. if (!cc->crypt_queue) {
  1536. ti->error = "Couldn't create kcryptd queue";
  1537. goto bad;
  1538. }
  1539. init_waitqueue_head(&cc->write_thread_wait);
  1540. cc->write_tree = RB_ROOT;
  1541. cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write");
  1542. if (IS_ERR(cc->write_thread)) {
  1543. ret = PTR_ERR(cc->write_thread);
  1544. cc->write_thread = NULL;
  1545. ti->error = "Couldn't spawn write thread";
  1546. goto bad;
  1547. }
  1548. wake_up_process(cc->write_thread);
  1549. ti->num_flush_bios = 1;
  1550. ti->discard_zeroes_data_unsupported = true;
  1551. return 0;
  1552. bad:
  1553. crypt_dtr(ti);
  1554. return ret;
  1555. }
  1556. static int crypt_map(struct dm_target *ti, struct bio *bio)
  1557. {
  1558. struct dm_crypt_io *io;
  1559. struct crypt_config *cc = ti->private;
  1560. /*
  1561. * If bio is REQ_FLUSH or REQ_DISCARD, just bypass crypt queues.
  1562. * - for REQ_FLUSH device-mapper core ensures that no IO is in-flight
  1563. * - for REQ_DISCARD caller must use flush if IO ordering matters
  1564. */
  1565. if (unlikely(bio->bi_rw & (REQ_FLUSH | REQ_DISCARD))) {
  1566. bio->bi_bdev = cc->dev->bdev;
  1567. if (bio_sectors(bio))
  1568. bio->bi_iter.bi_sector = cc->start +
  1569. dm_target_offset(ti, bio->bi_iter.bi_sector);
  1570. return DM_MAPIO_REMAPPED;
  1571. }
  1572. io = dm_per_bio_data(bio, cc->per_bio_data_size);
  1573. crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
  1574. io->ctx.req = (struct skcipher_request *)(io + 1);
  1575. if (bio_data_dir(io->base_bio) == READ) {
  1576. if (kcryptd_io_read(io, GFP_NOWAIT))
  1577. kcryptd_queue_read(io);
  1578. } else
  1579. kcryptd_queue_crypt(io);
  1580. return DM_MAPIO_SUBMITTED;
  1581. }
  1582. static void crypt_status(struct dm_target *ti, status_type_t type,
  1583. unsigned status_flags, char *result, unsigned maxlen)
  1584. {
  1585. struct crypt_config *cc = ti->private;
  1586. unsigned i, sz = 0;
  1587. int num_feature_args = 0;
  1588. switch (type) {
  1589. case STATUSTYPE_INFO:
  1590. result[0] = '\0';
  1591. break;
  1592. case STATUSTYPE_TABLE:
  1593. DMEMIT("%s ", cc->cipher_string);
  1594. if (cc->key_size > 0)
  1595. for (i = 0; i < cc->key_size; i++)
  1596. DMEMIT("%02x", cc->key[i]);
  1597. else
  1598. DMEMIT("-");
  1599. DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
  1600. cc->dev->name, (unsigned long long)cc->start);
  1601. num_feature_args += !!ti->num_discard_bios;
  1602. num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
  1603. num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
  1604. if (num_feature_args) {
  1605. DMEMIT(" %d", num_feature_args);
  1606. if (ti->num_discard_bios)
  1607. DMEMIT(" allow_discards");
  1608. if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
  1609. DMEMIT(" same_cpu_crypt");
  1610. if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
  1611. DMEMIT(" submit_from_crypt_cpus");
  1612. }
  1613. break;
  1614. }
  1615. }
  1616. static void crypt_postsuspend(struct dm_target *ti)
  1617. {
  1618. struct crypt_config *cc = ti->private;
  1619. set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  1620. }
  1621. static int crypt_preresume(struct dm_target *ti)
  1622. {
  1623. struct crypt_config *cc = ti->private;
  1624. if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
  1625. DMERR("aborting resume - crypt key is not set.");
  1626. return -EAGAIN;
  1627. }
  1628. return 0;
  1629. }
  1630. static void crypt_resume(struct dm_target *ti)
  1631. {
  1632. struct crypt_config *cc = ti->private;
  1633. clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  1634. }
  1635. /* Message interface
  1636. * key set <key>
  1637. * key wipe
  1638. */
  1639. static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
  1640. {
  1641. struct crypt_config *cc = ti->private;
  1642. int ret = -EINVAL;
  1643. if (argc < 2)
  1644. goto error;
  1645. if (!strcasecmp(argv[0], "key")) {
  1646. if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
  1647. DMWARN("not suspended during key manipulation.");
  1648. return -EINVAL;
  1649. }
  1650. if (argc == 3 && !strcasecmp(argv[1], "set")) {
  1651. ret = crypt_set_key(cc, argv[2]);
  1652. if (ret)
  1653. return ret;
  1654. if (cc->iv_gen_ops && cc->iv_gen_ops->init)
  1655. ret = cc->iv_gen_ops->init(cc);
  1656. return ret;
  1657. }
  1658. if (argc == 2 && !strcasecmp(argv[1], "wipe")) {
  1659. if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
  1660. ret = cc->iv_gen_ops->wipe(cc);
  1661. if (ret)
  1662. return ret;
  1663. }
  1664. return crypt_wipe_key(cc);
  1665. }
  1666. }
  1667. error:
  1668. DMWARN("unrecognised message received.");
  1669. return -EINVAL;
  1670. }
  1671. static int crypt_iterate_devices(struct dm_target *ti,
  1672. iterate_devices_callout_fn fn, void *data)
  1673. {
  1674. struct crypt_config *cc = ti->private;
  1675. return fn(ti, cc->dev, cc->start, ti->len, data);
  1676. }
  1677. static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
  1678. {
  1679. /*
  1680. * Unfortunate constraint that is required to avoid the potential
  1681. * for exceeding underlying device's max_segments limits -- due to
  1682. * crypt_alloc_buffer() possibly allocating pages for the encryption
  1683. * bio that are not as physically contiguous as the original bio.
  1684. */
  1685. limits->max_segment_size = PAGE_SIZE;
  1686. }
  1687. static struct target_type crypt_target = {
  1688. .name = "crypt",
  1689. .version = {1, 14, 1},
  1690. .module = THIS_MODULE,
  1691. .ctr = crypt_ctr,
  1692. .dtr = crypt_dtr,
  1693. .map = crypt_map,
  1694. .status = crypt_status,
  1695. .postsuspend = crypt_postsuspend,
  1696. .preresume = crypt_preresume,
  1697. .resume = crypt_resume,
  1698. .message = crypt_message,
  1699. .iterate_devices = crypt_iterate_devices,
  1700. .io_hints = crypt_io_hints,
  1701. };
  1702. static int __init dm_crypt_init(void)
  1703. {
  1704. int r;
  1705. r = dm_register_target(&crypt_target);
  1706. if (r < 0)
  1707. DMERR("register failed %d", r);
  1708. return r;
  1709. }
  1710. static void __exit dm_crypt_exit(void)
  1711. {
  1712. dm_unregister_target(&crypt_target);
  1713. }
  1714. module_init(dm_crypt_init);
  1715. module_exit(dm_crypt_exit);
  1716. MODULE_AUTHOR("Jana Saout <jana@saout.de>");
  1717. MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
  1718. MODULE_LICENSE("GPL");