dm-crypt.c 51 KB

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