dm-crypt.c 51 KB

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