dm-crypt.c 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108
  1. /*
  2. * Copyright (C) 2003 Jana Saout <jana@saout.de>
  3. * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
  4. * Copyright (C) 2006-2017 Red Hat, Inc. All rights reserved.
  5. * Copyright (C) 2013-2017 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/key.h>
  15. #include <linux/bio.h>
  16. #include <linux/blkdev.h>
  17. #include <linux/mempool.h>
  18. #include <linux/slab.h>
  19. #include <linux/crypto.h>
  20. #include <linux/workqueue.h>
  21. #include <linux/kthread.h>
  22. #include <linux/backing-dev.h>
  23. #include <linux/atomic.h>
  24. #include <linux/scatterlist.h>
  25. #include <linux/rbtree.h>
  26. #include <linux/ctype.h>
  27. #include <asm/page.h>
  28. #include <asm/unaligned.h>
  29. #include <crypto/hash.h>
  30. #include <crypto/md5.h>
  31. #include <crypto/algapi.h>
  32. #include <crypto/skcipher.h>
  33. #include <crypto/aead.h>
  34. #include <crypto/authenc.h>
  35. #include <linux/rtnetlink.h> /* for struct rtattr and RTA macros only */
  36. #include <keys/user-type.h>
  37. #include <linux/device-mapper.h>
  38. #define DM_MSG_PREFIX "crypt"
  39. /*
  40. * context holding the current state of a multi-part conversion
  41. */
  42. struct convert_context {
  43. struct completion restart;
  44. struct bio *bio_in;
  45. struct bio *bio_out;
  46. struct bvec_iter iter_in;
  47. struct bvec_iter iter_out;
  48. sector_t cc_sector;
  49. atomic_t cc_pending;
  50. union {
  51. struct skcipher_request *req;
  52. struct aead_request *req_aead;
  53. } r;
  54. };
  55. /*
  56. * per bio private data
  57. */
  58. struct dm_crypt_io {
  59. struct crypt_config *cc;
  60. struct bio *base_bio;
  61. u8 *integrity_metadata;
  62. bool integrity_metadata_from_pool;
  63. struct work_struct work;
  64. struct convert_context ctx;
  65. atomic_t io_pending;
  66. blk_status_t error;
  67. sector_t sector;
  68. struct rb_node rb_node;
  69. } CRYPTO_MINALIGN_ATTR;
  70. struct dm_crypt_request {
  71. struct convert_context *ctx;
  72. struct scatterlist sg_in[4];
  73. struct scatterlist sg_out[4];
  74. sector_t iv_sector;
  75. };
  76. struct crypt_config;
  77. struct crypt_iv_operations {
  78. int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
  79. const char *opts);
  80. void (*dtr)(struct crypt_config *cc);
  81. int (*init)(struct crypt_config *cc);
  82. int (*wipe)(struct crypt_config *cc);
  83. int (*generator)(struct crypt_config *cc, u8 *iv,
  84. struct dm_crypt_request *dmreq);
  85. int (*post)(struct crypt_config *cc, u8 *iv,
  86. struct dm_crypt_request *dmreq);
  87. };
  88. struct iv_essiv_private {
  89. struct crypto_shash *hash_tfm;
  90. u8 *salt;
  91. };
  92. struct iv_benbi_private {
  93. int shift;
  94. };
  95. #define LMK_SEED_SIZE 64 /* hash + 0 */
  96. struct iv_lmk_private {
  97. struct crypto_shash *hash_tfm;
  98. u8 *seed;
  99. };
  100. #define TCW_WHITENING_SIZE 16
  101. struct iv_tcw_private {
  102. struct crypto_shash *crc32_tfm;
  103. u8 *iv_seed;
  104. u8 *whitening;
  105. };
  106. /*
  107. * Crypt: maps a linear range of a block device
  108. * and encrypts / decrypts at the same time.
  109. */
  110. enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
  111. DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD };
  112. enum cipher_flags {
  113. CRYPT_MODE_INTEGRITY_AEAD, /* Use authenticated mode for cihper */
  114. CRYPT_IV_LARGE_SECTORS, /* Calculate IV from sector_size, not 512B sectors */
  115. };
  116. /*
  117. * The fields in here must be read only after initialization.
  118. */
  119. struct crypt_config {
  120. struct dm_dev *dev;
  121. sector_t start;
  122. struct percpu_counter n_allocated_pages;
  123. struct workqueue_struct *io_queue;
  124. struct workqueue_struct *crypt_queue;
  125. spinlock_t write_thread_lock;
  126. struct task_struct *write_thread;
  127. struct rb_root write_tree;
  128. char *cipher;
  129. char *cipher_string;
  130. char *cipher_auth;
  131. char *key_string;
  132. const struct crypt_iv_operations *iv_gen_ops;
  133. union {
  134. struct iv_essiv_private essiv;
  135. struct iv_benbi_private benbi;
  136. struct iv_lmk_private lmk;
  137. struct iv_tcw_private tcw;
  138. } iv_gen_private;
  139. sector_t iv_offset;
  140. unsigned int iv_size;
  141. unsigned short int sector_size;
  142. unsigned char sector_shift;
  143. /* ESSIV: struct crypto_cipher *essiv_tfm */
  144. void *iv_private;
  145. union {
  146. struct crypto_skcipher **tfms;
  147. struct crypto_aead **tfms_aead;
  148. } cipher_tfm;
  149. unsigned tfms_count;
  150. unsigned long cipher_flags;
  151. /*
  152. * Layout of each crypto request:
  153. *
  154. * struct skcipher_request
  155. * context
  156. * padding
  157. * struct dm_crypt_request
  158. * padding
  159. * IV
  160. *
  161. * The padding is added so that dm_crypt_request and the IV are
  162. * correctly aligned.
  163. */
  164. unsigned int dmreq_start;
  165. unsigned int per_bio_data_size;
  166. unsigned long flags;
  167. unsigned int key_size;
  168. unsigned int key_parts; /* independent parts in key buffer */
  169. unsigned int key_extra_size; /* additional keys length */
  170. unsigned int key_mac_size; /* MAC key size for authenc(...) */
  171. unsigned int integrity_tag_size;
  172. unsigned int integrity_iv_size;
  173. unsigned int on_disk_tag_size;
  174. /*
  175. * pool for per bio private data, crypto requests,
  176. * encryption requeusts/buffer pages and integrity tags
  177. */
  178. unsigned tag_pool_max_sectors;
  179. mempool_t tag_pool;
  180. mempool_t req_pool;
  181. mempool_t page_pool;
  182. struct bio_set bs;
  183. struct mutex bio_alloc_lock;
  184. u8 *authenc_key; /* space for keys in authenc() format (if used) */
  185. u8 key[0];
  186. };
  187. #define MIN_IOS 64
  188. #define MAX_TAG_SIZE 480
  189. #define POOL_ENTRY_SIZE 512
  190. static DEFINE_SPINLOCK(dm_crypt_clients_lock);
  191. static unsigned dm_crypt_clients_n = 0;
  192. static volatile unsigned long dm_crypt_pages_per_client;
  193. #define DM_CRYPT_MEMORY_PERCENT 2
  194. #define DM_CRYPT_MIN_PAGES_PER_CLIENT (BIO_MAX_PAGES * 16)
  195. static void clone_init(struct dm_crypt_io *, struct bio *);
  196. static void kcryptd_queue_crypt(struct dm_crypt_io *io);
  197. static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
  198. struct scatterlist *sg);
  199. /*
  200. * Use this to access cipher attributes that are independent of the key.
  201. */
  202. static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
  203. {
  204. return cc->cipher_tfm.tfms[0];
  205. }
  206. static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
  207. {
  208. return cc->cipher_tfm.tfms_aead[0];
  209. }
  210. /*
  211. * Different IV generation algorithms:
  212. *
  213. * plain: the initial vector is the 32-bit little-endian version of the sector
  214. * number, padded with zeros if necessary.
  215. *
  216. * plain64: the initial vector is the 64-bit little-endian version of the sector
  217. * number, padded with zeros if necessary.
  218. *
  219. * plain64be: the initial vector is the 64-bit big-endian version of the sector
  220. * number, padded with zeros if necessary.
  221. *
  222. * essiv: "encrypted sector|salt initial vector", the sector number is
  223. * encrypted with the bulk cipher using a salt as key. The salt
  224. * should be derived from the bulk cipher's key via hashing.
  225. *
  226. * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
  227. * (needed for LRW-32-AES and possible other narrow block modes)
  228. *
  229. * null: the initial vector is always zero. Provides compatibility with
  230. * obsolete loop_fish2 devices. Do not use for new devices.
  231. *
  232. * lmk: Compatible implementation of the block chaining mode used
  233. * by the Loop-AES block device encryption system
  234. * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
  235. * It operates on full 512 byte sectors and uses CBC
  236. * with an IV derived from the sector number, the data and
  237. * optionally extra IV seed.
  238. * This means that after decryption the first block
  239. * of sector must be tweaked according to decrypted data.
  240. * Loop-AES can use three encryption schemes:
  241. * version 1: is plain aes-cbc mode
  242. * version 2: uses 64 multikey scheme with lmk IV generator
  243. * version 3: the same as version 2 with additional IV seed
  244. * (it uses 65 keys, last key is used as IV seed)
  245. *
  246. * tcw: Compatible implementation of the block chaining mode used
  247. * by the TrueCrypt device encryption system (prior to version 4.1).
  248. * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
  249. * It operates on full 512 byte sectors and uses CBC
  250. * with an IV derived from initial key and the sector number.
  251. * In addition, whitening value is applied on every sector, whitening
  252. * is calculated from initial key, sector number and mixed using CRC32.
  253. * Note that this encryption scheme is vulnerable to watermarking attacks
  254. * and should be used for old compatible containers access only.
  255. *
  256. * plumb: unimplemented, see:
  257. * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
  258. */
  259. static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
  260. struct dm_crypt_request *dmreq)
  261. {
  262. memset(iv, 0, cc->iv_size);
  263. *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
  264. return 0;
  265. }
  266. static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
  267. struct dm_crypt_request *dmreq)
  268. {
  269. memset(iv, 0, cc->iv_size);
  270. *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
  271. return 0;
  272. }
  273. static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
  274. struct dm_crypt_request *dmreq)
  275. {
  276. memset(iv, 0, cc->iv_size);
  277. /* iv_size is at least of size u64; usually it is 16 bytes */
  278. *(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
  279. return 0;
  280. }
  281. /* Initialise ESSIV - compute salt but no local memory allocations */
  282. static int crypt_iv_essiv_init(struct crypt_config *cc)
  283. {
  284. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  285. SHASH_DESC_ON_STACK(desc, essiv->hash_tfm);
  286. struct crypto_cipher *essiv_tfm;
  287. int err;
  288. desc->tfm = essiv->hash_tfm;
  289. desc->flags = 0;
  290. err = crypto_shash_digest(desc, cc->key, cc->key_size, essiv->salt);
  291. shash_desc_zero(desc);
  292. if (err)
  293. return err;
  294. essiv_tfm = cc->iv_private;
  295. err = crypto_cipher_setkey(essiv_tfm, essiv->salt,
  296. crypto_shash_digestsize(essiv->hash_tfm));
  297. if (err)
  298. return err;
  299. return 0;
  300. }
  301. /* Wipe salt and reset key derived from volume key */
  302. static int crypt_iv_essiv_wipe(struct crypt_config *cc)
  303. {
  304. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  305. unsigned salt_size = crypto_shash_digestsize(essiv->hash_tfm);
  306. struct crypto_cipher *essiv_tfm;
  307. int r, err = 0;
  308. memset(essiv->salt, 0, salt_size);
  309. essiv_tfm = cc->iv_private;
  310. r = crypto_cipher_setkey(essiv_tfm, essiv->salt, salt_size);
  311. if (r)
  312. err = r;
  313. return err;
  314. }
  315. /* Allocate the cipher for ESSIV */
  316. static struct crypto_cipher *alloc_essiv_cipher(struct crypt_config *cc,
  317. struct dm_target *ti,
  318. const u8 *salt,
  319. unsigned int saltsize)
  320. {
  321. struct crypto_cipher *essiv_tfm;
  322. int err;
  323. /* Setup the essiv_tfm with the given salt */
  324. essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
  325. if (IS_ERR(essiv_tfm)) {
  326. ti->error = "Error allocating crypto tfm for ESSIV";
  327. return essiv_tfm;
  328. }
  329. if (crypto_cipher_blocksize(essiv_tfm) != cc->iv_size) {
  330. ti->error = "Block size of ESSIV cipher does "
  331. "not match IV size of block cipher";
  332. crypto_free_cipher(essiv_tfm);
  333. return ERR_PTR(-EINVAL);
  334. }
  335. err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
  336. if (err) {
  337. ti->error = "Failed to set key for ESSIV cipher";
  338. crypto_free_cipher(essiv_tfm);
  339. return ERR_PTR(err);
  340. }
  341. return essiv_tfm;
  342. }
  343. static void crypt_iv_essiv_dtr(struct crypt_config *cc)
  344. {
  345. struct crypto_cipher *essiv_tfm;
  346. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  347. crypto_free_shash(essiv->hash_tfm);
  348. essiv->hash_tfm = NULL;
  349. kzfree(essiv->salt);
  350. essiv->salt = NULL;
  351. essiv_tfm = cc->iv_private;
  352. if (essiv_tfm)
  353. crypto_free_cipher(essiv_tfm);
  354. cc->iv_private = NULL;
  355. }
  356. static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
  357. const char *opts)
  358. {
  359. struct crypto_cipher *essiv_tfm = NULL;
  360. struct crypto_shash *hash_tfm = NULL;
  361. u8 *salt = NULL;
  362. int err;
  363. if (!opts) {
  364. ti->error = "Digest algorithm missing for ESSIV mode";
  365. return -EINVAL;
  366. }
  367. /* Allocate hash algorithm */
  368. hash_tfm = crypto_alloc_shash(opts, 0, 0);
  369. if (IS_ERR(hash_tfm)) {
  370. ti->error = "Error initializing ESSIV hash";
  371. err = PTR_ERR(hash_tfm);
  372. goto bad;
  373. }
  374. salt = kzalloc(crypto_shash_digestsize(hash_tfm), GFP_KERNEL);
  375. if (!salt) {
  376. ti->error = "Error kmallocing salt storage in ESSIV";
  377. err = -ENOMEM;
  378. goto bad;
  379. }
  380. cc->iv_gen_private.essiv.salt = salt;
  381. cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
  382. essiv_tfm = alloc_essiv_cipher(cc, ti, salt,
  383. crypto_shash_digestsize(hash_tfm));
  384. if (IS_ERR(essiv_tfm)) {
  385. crypt_iv_essiv_dtr(cc);
  386. return PTR_ERR(essiv_tfm);
  387. }
  388. cc->iv_private = essiv_tfm;
  389. return 0;
  390. bad:
  391. if (hash_tfm && !IS_ERR(hash_tfm))
  392. crypto_free_shash(hash_tfm);
  393. kfree(salt);
  394. return err;
  395. }
  396. static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
  397. struct dm_crypt_request *dmreq)
  398. {
  399. struct crypto_cipher *essiv_tfm = cc->iv_private;
  400. memset(iv, 0, cc->iv_size);
  401. *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
  402. crypto_cipher_encrypt_one(essiv_tfm, iv, iv);
  403. return 0;
  404. }
  405. static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
  406. const char *opts)
  407. {
  408. unsigned bs = crypto_skcipher_blocksize(any_tfm(cc));
  409. int log = ilog2(bs);
  410. /* we need to calculate how far we must shift the sector count
  411. * to get the cipher block count, we use this shift in _gen */
  412. if (1 << log != bs) {
  413. ti->error = "cypher blocksize is not a power of 2";
  414. return -EINVAL;
  415. }
  416. if (log > 9) {
  417. ti->error = "cypher blocksize is > 512";
  418. return -EINVAL;
  419. }
  420. cc->iv_gen_private.benbi.shift = 9 - log;
  421. return 0;
  422. }
  423. static void crypt_iv_benbi_dtr(struct crypt_config *cc)
  424. {
  425. }
  426. static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
  427. struct dm_crypt_request *dmreq)
  428. {
  429. __be64 val;
  430. memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
  431. val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
  432. put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
  433. return 0;
  434. }
  435. static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
  436. struct dm_crypt_request *dmreq)
  437. {
  438. memset(iv, 0, cc->iv_size);
  439. return 0;
  440. }
  441. static void crypt_iv_lmk_dtr(struct crypt_config *cc)
  442. {
  443. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  444. if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
  445. crypto_free_shash(lmk->hash_tfm);
  446. lmk->hash_tfm = NULL;
  447. kzfree(lmk->seed);
  448. lmk->seed = NULL;
  449. }
  450. static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
  451. const char *opts)
  452. {
  453. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  454. if (cc->sector_size != (1 << SECTOR_SHIFT)) {
  455. ti->error = "Unsupported sector size for LMK";
  456. return -EINVAL;
  457. }
  458. lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
  459. if (IS_ERR(lmk->hash_tfm)) {
  460. ti->error = "Error initializing LMK hash";
  461. return PTR_ERR(lmk->hash_tfm);
  462. }
  463. /* No seed in LMK version 2 */
  464. if (cc->key_parts == cc->tfms_count) {
  465. lmk->seed = NULL;
  466. return 0;
  467. }
  468. lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
  469. if (!lmk->seed) {
  470. crypt_iv_lmk_dtr(cc);
  471. ti->error = "Error kmallocing seed storage in LMK";
  472. return -ENOMEM;
  473. }
  474. return 0;
  475. }
  476. static int crypt_iv_lmk_init(struct crypt_config *cc)
  477. {
  478. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  479. int subkey_size = cc->key_size / cc->key_parts;
  480. /* LMK seed is on the position of LMK_KEYS + 1 key */
  481. if (lmk->seed)
  482. memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
  483. crypto_shash_digestsize(lmk->hash_tfm));
  484. return 0;
  485. }
  486. static int crypt_iv_lmk_wipe(struct crypt_config *cc)
  487. {
  488. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  489. if (lmk->seed)
  490. memset(lmk->seed, 0, LMK_SEED_SIZE);
  491. return 0;
  492. }
  493. static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
  494. struct dm_crypt_request *dmreq,
  495. u8 *data)
  496. {
  497. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  498. SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
  499. struct md5_state md5state;
  500. __le32 buf[4];
  501. int i, r;
  502. desc->tfm = lmk->hash_tfm;
  503. desc->flags = 0;
  504. r = crypto_shash_init(desc);
  505. if (r)
  506. return r;
  507. if (lmk->seed) {
  508. r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
  509. if (r)
  510. return r;
  511. }
  512. /* Sector is always 512B, block size 16, add data of blocks 1-31 */
  513. r = crypto_shash_update(desc, data + 16, 16 * 31);
  514. if (r)
  515. return r;
  516. /* Sector is cropped to 56 bits here */
  517. buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
  518. buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
  519. buf[2] = cpu_to_le32(4024);
  520. buf[3] = 0;
  521. r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
  522. if (r)
  523. return r;
  524. /* No MD5 padding here */
  525. r = crypto_shash_export(desc, &md5state);
  526. if (r)
  527. return r;
  528. for (i = 0; i < MD5_HASH_WORDS; i++)
  529. __cpu_to_le32s(&md5state.hash[i]);
  530. memcpy(iv, &md5state.hash, cc->iv_size);
  531. return 0;
  532. }
  533. static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
  534. struct dm_crypt_request *dmreq)
  535. {
  536. struct scatterlist *sg;
  537. u8 *src;
  538. int r = 0;
  539. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
  540. sg = crypt_get_sg_data(cc, dmreq->sg_in);
  541. src = kmap_atomic(sg_page(sg));
  542. r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
  543. kunmap_atomic(src);
  544. } else
  545. memset(iv, 0, cc->iv_size);
  546. return r;
  547. }
  548. static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
  549. struct dm_crypt_request *dmreq)
  550. {
  551. struct scatterlist *sg;
  552. u8 *dst;
  553. int r;
  554. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
  555. return 0;
  556. sg = crypt_get_sg_data(cc, dmreq->sg_out);
  557. dst = kmap_atomic(sg_page(sg));
  558. r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
  559. /* Tweak the first block of plaintext sector */
  560. if (!r)
  561. crypto_xor(dst + sg->offset, iv, cc->iv_size);
  562. kunmap_atomic(dst);
  563. return r;
  564. }
  565. static void crypt_iv_tcw_dtr(struct crypt_config *cc)
  566. {
  567. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  568. kzfree(tcw->iv_seed);
  569. tcw->iv_seed = NULL;
  570. kzfree(tcw->whitening);
  571. tcw->whitening = NULL;
  572. if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
  573. crypto_free_shash(tcw->crc32_tfm);
  574. tcw->crc32_tfm = NULL;
  575. }
  576. static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
  577. const char *opts)
  578. {
  579. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  580. if (cc->sector_size != (1 << SECTOR_SHIFT)) {
  581. ti->error = "Unsupported sector size for TCW";
  582. return -EINVAL;
  583. }
  584. if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
  585. ti->error = "Wrong key size for TCW";
  586. return -EINVAL;
  587. }
  588. tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
  589. if (IS_ERR(tcw->crc32_tfm)) {
  590. ti->error = "Error initializing CRC32 in TCW";
  591. return PTR_ERR(tcw->crc32_tfm);
  592. }
  593. tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
  594. tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
  595. if (!tcw->iv_seed || !tcw->whitening) {
  596. crypt_iv_tcw_dtr(cc);
  597. ti->error = "Error allocating seed storage in TCW";
  598. return -ENOMEM;
  599. }
  600. return 0;
  601. }
  602. static int crypt_iv_tcw_init(struct crypt_config *cc)
  603. {
  604. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  605. int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
  606. memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
  607. memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
  608. TCW_WHITENING_SIZE);
  609. return 0;
  610. }
  611. static int crypt_iv_tcw_wipe(struct crypt_config *cc)
  612. {
  613. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  614. memset(tcw->iv_seed, 0, cc->iv_size);
  615. memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
  616. return 0;
  617. }
  618. static int crypt_iv_tcw_whitening(struct crypt_config *cc,
  619. struct dm_crypt_request *dmreq,
  620. u8 *data)
  621. {
  622. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  623. __le64 sector = cpu_to_le64(dmreq->iv_sector);
  624. u8 buf[TCW_WHITENING_SIZE];
  625. SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
  626. int i, r;
  627. /* xor whitening with sector number */
  628. crypto_xor_cpy(buf, tcw->whitening, (u8 *)&sector, 8);
  629. crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)&sector, 8);
  630. /* calculate crc32 for every 32bit part and xor it */
  631. desc->tfm = tcw->crc32_tfm;
  632. desc->flags = 0;
  633. for (i = 0; i < 4; i++) {
  634. r = crypto_shash_init(desc);
  635. if (r)
  636. goto out;
  637. r = crypto_shash_update(desc, &buf[i * 4], 4);
  638. if (r)
  639. goto out;
  640. r = crypto_shash_final(desc, &buf[i * 4]);
  641. if (r)
  642. goto out;
  643. }
  644. crypto_xor(&buf[0], &buf[12], 4);
  645. crypto_xor(&buf[4], &buf[8], 4);
  646. /* apply whitening (8 bytes) to whole sector */
  647. for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
  648. crypto_xor(data + i * 8, buf, 8);
  649. out:
  650. memzero_explicit(buf, sizeof(buf));
  651. return r;
  652. }
  653. static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
  654. struct dm_crypt_request *dmreq)
  655. {
  656. struct scatterlist *sg;
  657. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  658. __le64 sector = cpu_to_le64(dmreq->iv_sector);
  659. u8 *src;
  660. int r = 0;
  661. /* Remove whitening from ciphertext */
  662. if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
  663. sg = crypt_get_sg_data(cc, dmreq->sg_in);
  664. src = kmap_atomic(sg_page(sg));
  665. r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
  666. kunmap_atomic(src);
  667. }
  668. /* Calculate IV */
  669. crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)&sector, 8);
  670. if (cc->iv_size > 8)
  671. crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)&sector,
  672. cc->iv_size - 8);
  673. return r;
  674. }
  675. static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
  676. struct dm_crypt_request *dmreq)
  677. {
  678. struct scatterlist *sg;
  679. u8 *dst;
  680. int r;
  681. if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
  682. return 0;
  683. /* Apply whitening on ciphertext */
  684. sg = crypt_get_sg_data(cc, dmreq->sg_out);
  685. dst = kmap_atomic(sg_page(sg));
  686. r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
  687. kunmap_atomic(dst);
  688. return r;
  689. }
  690. static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
  691. struct dm_crypt_request *dmreq)
  692. {
  693. /* Used only for writes, there must be an additional space to store IV */
  694. get_random_bytes(iv, cc->iv_size);
  695. return 0;
  696. }
  697. static const struct crypt_iv_operations crypt_iv_plain_ops = {
  698. .generator = crypt_iv_plain_gen
  699. };
  700. static const struct crypt_iv_operations crypt_iv_plain64_ops = {
  701. .generator = crypt_iv_plain64_gen
  702. };
  703. static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
  704. .generator = crypt_iv_plain64be_gen
  705. };
  706. static const struct crypt_iv_operations crypt_iv_essiv_ops = {
  707. .ctr = crypt_iv_essiv_ctr,
  708. .dtr = crypt_iv_essiv_dtr,
  709. .init = crypt_iv_essiv_init,
  710. .wipe = crypt_iv_essiv_wipe,
  711. .generator = crypt_iv_essiv_gen
  712. };
  713. static const struct crypt_iv_operations crypt_iv_benbi_ops = {
  714. .ctr = crypt_iv_benbi_ctr,
  715. .dtr = crypt_iv_benbi_dtr,
  716. .generator = crypt_iv_benbi_gen
  717. };
  718. static const struct crypt_iv_operations crypt_iv_null_ops = {
  719. .generator = crypt_iv_null_gen
  720. };
  721. static const struct crypt_iv_operations crypt_iv_lmk_ops = {
  722. .ctr = crypt_iv_lmk_ctr,
  723. .dtr = crypt_iv_lmk_dtr,
  724. .init = crypt_iv_lmk_init,
  725. .wipe = crypt_iv_lmk_wipe,
  726. .generator = crypt_iv_lmk_gen,
  727. .post = crypt_iv_lmk_post
  728. };
  729. static const struct crypt_iv_operations crypt_iv_tcw_ops = {
  730. .ctr = crypt_iv_tcw_ctr,
  731. .dtr = crypt_iv_tcw_dtr,
  732. .init = crypt_iv_tcw_init,
  733. .wipe = crypt_iv_tcw_wipe,
  734. .generator = crypt_iv_tcw_gen,
  735. .post = crypt_iv_tcw_post
  736. };
  737. static struct crypt_iv_operations crypt_iv_random_ops = {
  738. .generator = crypt_iv_random_gen
  739. };
  740. /*
  741. * Integrity extensions
  742. */
  743. static bool crypt_integrity_aead(struct crypt_config *cc)
  744. {
  745. return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
  746. }
  747. static bool crypt_integrity_hmac(struct crypt_config *cc)
  748. {
  749. return crypt_integrity_aead(cc) && cc->key_mac_size;
  750. }
  751. /* Get sg containing data */
  752. static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
  753. struct scatterlist *sg)
  754. {
  755. if (unlikely(crypt_integrity_aead(cc)))
  756. return &sg[2];
  757. return sg;
  758. }
  759. static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
  760. {
  761. struct bio_integrity_payload *bip;
  762. unsigned int tag_len;
  763. int ret;
  764. if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
  765. return 0;
  766. bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
  767. if (IS_ERR(bip))
  768. return PTR_ERR(bip);
  769. tag_len = io->cc->on_disk_tag_size * bio_sectors(bio);
  770. bip->bip_iter.bi_size = tag_len;
  771. bip->bip_iter.bi_sector = io->cc->start + io->sector;
  772. ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
  773. tag_len, offset_in_page(io->integrity_metadata));
  774. if (unlikely(ret != tag_len))
  775. return -ENOMEM;
  776. return 0;
  777. }
  778. static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
  779. {
  780. #ifdef CONFIG_BLK_DEV_INTEGRITY
  781. struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
  782. /* From now we require underlying device with our integrity profile */
  783. if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
  784. ti->error = "Integrity profile not supported.";
  785. return -EINVAL;
  786. }
  787. if (bi->tag_size != cc->on_disk_tag_size ||
  788. bi->tuple_size != cc->on_disk_tag_size) {
  789. ti->error = "Integrity profile tag size mismatch.";
  790. return -EINVAL;
  791. }
  792. if (1 << bi->interval_exp != cc->sector_size) {
  793. ti->error = "Integrity profile sector size mismatch.";
  794. return -EINVAL;
  795. }
  796. if (crypt_integrity_aead(cc)) {
  797. cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
  798. DMINFO("Integrity AEAD, tag size %u, IV size %u.",
  799. cc->integrity_tag_size, cc->integrity_iv_size);
  800. if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
  801. ti->error = "Integrity AEAD auth tag size is not supported.";
  802. return -EINVAL;
  803. }
  804. } else if (cc->integrity_iv_size)
  805. DMINFO("Additional per-sector space %u bytes for IV.",
  806. cc->integrity_iv_size);
  807. if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
  808. ti->error = "Not enough space for integrity tag in the profile.";
  809. return -EINVAL;
  810. }
  811. return 0;
  812. #else
  813. ti->error = "Integrity profile not supported.";
  814. return -EINVAL;
  815. #endif
  816. }
  817. static void crypt_convert_init(struct crypt_config *cc,
  818. struct convert_context *ctx,
  819. struct bio *bio_out, struct bio *bio_in,
  820. sector_t sector)
  821. {
  822. ctx->bio_in = bio_in;
  823. ctx->bio_out = bio_out;
  824. if (bio_in)
  825. ctx->iter_in = bio_in->bi_iter;
  826. if (bio_out)
  827. ctx->iter_out = bio_out->bi_iter;
  828. ctx->cc_sector = sector + cc->iv_offset;
  829. init_completion(&ctx->restart);
  830. }
  831. static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
  832. void *req)
  833. {
  834. return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
  835. }
  836. static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
  837. {
  838. return (void *)((char *)dmreq - cc->dmreq_start);
  839. }
  840. static u8 *iv_of_dmreq(struct crypt_config *cc,
  841. struct dm_crypt_request *dmreq)
  842. {
  843. if (crypt_integrity_aead(cc))
  844. return (u8 *)ALIGN((unsigned long)(dmreq + 1),
  845. crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
  846. else
  847. return (u8 *)ALIGN((unsigned long)(dmreq + 1),
  848. crypto_skcipher_alignmask(any_tfm(cc)) + 1);
  849. }
  850. static u8 *org_iv_of_dmreq(struct crypt_config *cc,
  851. struct dm_crypt_request *dmreq)
  852. {
  853. return iv_of_dmreq(cc, dmreq) + cc->iv_size;
  854. }
  855. static uint64_t *org_sector_of_dmreq(struct crypt_config *cc,
  856. struct dm_crypt_request *dmreq)
  857. {
  858. u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
  859. return (uint64_t*) ptr;
  860. }
  861. static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
  862. struct dm_crypt_request *dmreq)
  863. {
  864. u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
  865. cc->iv_size + sizeof(uint64_t);
  866. return (unsigned int*)ptr;
  867. }
  868. static void *tag_from_dmreq(struct crypt_config *cc,
  869. struct dm_crypt_request *dmreq)
  870. {
  871. struct convert_context *ctx = dmreq->ctx;
  872. struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
  873. return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
  874. cc->on_disk_tag_size];
  875. }
  876. static void *iv_tag_from_dmreq(struct crypt_config *cc,
  877. struct dm_crypt_request *dmreq)
  878. {
  879. return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
  880. }
  881. static int crypt_convert_block_aead(struct crypt_config *cc,
  882. struct convert_context *ctx,
  883. struct aead_request *req,
  884. unsigned int tag_offset)
  885. {
  886. struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
  887. struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
  888. struct dm_crypt_request *dmreq;
  889. u8 *iv, *org_iv, *tag_iv, *tag;
  890. uint64_t *sector;
  891. int r = 0;
  892. BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
  893. /* Reject unexpected unaligned bio. */
  894. if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
  895. return -EIO;
  896. dmreq = dmreq_of_req(cc, req);
  897. dmreq->iv_sector = ctx->cc_sector;
  898. if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
  899. dmreq->iv_sector >>= cc->sector_shift;
  900. dmreq->ctx = ctx;
  901. *org_tag_of_dmreq(cc, dmreq) = tag_offset;
  902. sector = org_sector_of_dmreq(cc, dmreq);
  903. *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
  904. iv = iv_of_dmreq(cc, dmreq);
  905. org_iv = org_iv_of_dmreq(cc, dmreq);
  906. tag = tag_from_dmreq(cc, dmreq);
  907. tag_iv = iv_tag_from_dmreq(cc, dmreq);
  908. /* AEAD request:
  909. * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
  910. * | (authenticated) | (auth+encryption) | |
  911. * | sector_LE | IV | sector in/out | tag in/out |
  912. */
  913. sg_init_table(dmreq->sg_in, 4);
  914. sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
  915. sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
  916. sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
  917. sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
  918. sg_init_table(dmreq->sg_out, 4);
  919. sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
  920. sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
  921. sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
  922. sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
  923. if (cc->iv_gen_ops) {
  924. /* For READs use IV stored in integrity metadata */
  925. if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
  926. memcpy(org_iv, tag_iv, cc->iv_size);
  927. } else {
  928. r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
  929. if (r < 0)
  930. return r;
  931. /* Store generated IV in integrity metadata */
  932. if (cc->integrity_iv_size)
  933. memcpy(tag_iv, org_iv, cc->iv_size);
  934. }
  935. /* Working copy of IV, to be modified in crypto API */
  936. memcpy(iv, org_iv, cc->iv_size);
  937. }
  938. aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
  939. if (bio_data_dir(ctx->bio_in) == WRITE) {
  940. aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
  941. cc->sector_size, iv);
  942. r = crypto_aead_encrypt(req);
  943. if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
  944. memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
  945. cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
  946. } else {
  947. aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
  948. cc->sector_size + cc->integrity_tag_size, iv);
  949. r = crypto_aead_decrypt(req);
  950. }
  951. if (r == -EBADMSG)
  952. DMERR_LIMIT("INTEGRITY AEAD ERROR, sector %llu",
  953. (unsigned long long)le64_to_cpu(*sector));
  954. if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
  955. r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
  956. bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
  957. bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
  958. return r;
  959. }
  960. static int crypt_convert_block_skcipher(struct crypt_config *cc,
  961. struct convert_context *ctx,
  962. struct skcipher_request *req,
  963. unsigned int tag_offset)
  964. {
  965. struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
  966. struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
  967. struct scatterlist *sg_in, *sg_out;
  968. struct dm_crypt_request *dmreq;
  969. u8 *iv, *org_iv, *tag_iv;
  970. uint64_t *sector;
  971. int r = 0;
  972. /* Reject unexpected unaligned bio. */
  973. if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
  974. return -EIO;
  975. dmreq = dmreq_of_req(cc, req);
  976. dmreq->iv_sector = ctx->cc_sector;
  977. if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
  978. dmreq->iv_sector >>= cc->sector_shift;
  979. dmreq->ctx = ctx;
  980. *org_tag_of_dmreq(cc, dmreq) = tag_offset;
  981. iv = iv_of_dmreq(cc, dmreq);
  982. org_iv = org_iv_of_dmreq(cc, dmreq);
  983. tag_iv = iv_tag_from_dmreq(cc, dmreq);
  984. sector = org_sector_of_dmreq(cc, dmreq);
  985. *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
  986. /* For skcipher we use only the first sg item */
  987. sg_in = &dmreq->sg_in[0];
  988. sg_out = &dmreq->sg_out[0];
  989. sg_init_table(sg_in, 1);
  990. sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
  991. sg_init_table(sg_out, 1);
  992. sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
  993. if (cc->iv_gen_ops) {
  994. /* For READs use IV stored in integrity metadata */
  995. if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
  996. memcpy(org_iv, tag_iv, cc->integrity_iv_size);
  997. } else {
  998. r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
  999. if (r < 0)
  1000. return r;
  1001. /* Store generated IV in integrity metadata */
  1002. if (cc->integrity_iv_size)
  1003. memcpy(tag_iv, org_iv, cc->integrity_iv_size);
  1004. }
  1005. /* Working copy of IV, to be modified in crypto API */
  1006. memcpy(iv, org_iv, cc->iv_size);
  1007. }
  1008. skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
  1009. if (bio_data_dir(ctx->bio_in) == WRITE)
  1010. r = crypto_skcipher_encrypt(req);
  1011. else
  1012. r = crypto_skcipher_decrypt(req);
  1013. if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
  1014. r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
  1015. bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
  1016. bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
  1017. return r;
  1018. }
  1019. static void kcryptd_async_done(struct crypto_async_request *async_req,
  1020. int error);
  1021. static void crypt_alloc_req_skcipher(struct crypt_config *cc,
  1022. struct convert_context *ctx)
  1023. {
  1024. unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
  1025. if (!ctx->r.req)
  1026. ctx->r.req = mempool_alloc(&cc->req_pool, GFP_NOIO);
  1027. skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
  1028. /*
  1029. * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
  1030. * requests if driver request queue is full.
  1031. */
  1032. skcipher_request_set_callback(ctx->r.req,
  1033. CRYPTO_TFM_REQ_MAY_BACKLOG,
  1034. kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
  1035. }
  1036. static void crypt_alloc_req_aead(struct crypt_config *cc,
  1037. struct convert_context *ctx)
  1038. {
  1039. if (!ctx->r.req_aead)
  1040. ctx->r.req_aead = mempool_alloc(&cc->req_pool, GFP_NOIO);
  1041. aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
  1042. /*
  1043. * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
  1044. * requests if driver request queue is full.
  1045. */
  1046. aead_request_set_callback(ctx->r.req_aead,
  1047. CRYPTO_TFM_REQ_MAY_BACKLOG,
  1048. kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
  1049. }
  1050. static void crypt_alloc_req(struct crypt_config *cc,
  1051. struct convert_context *ctx)
  1052. {
  1053. if (crypt_integrity_aead(cc))
  1054. crypt_alloc_req_aead(cc, ctx);
  1055. else
  1056. crypt_alloc_req_skcipher(cc, ctx);
  1057. }
  1058. static void crypt_free_req_skcipher(struct crypt_config *cc,
  1059. struct skcipher_request *req, struct bio *base_bio)
  1060. {
  1061. struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
  1062. if ((struct skcipher_request *)(io + 1) != req)
  1063. mempool_free(req, &cc->req_pool);
  1064. }
  1065. static void crypt_free_req_aead(struct crypt_config *cc,
  1066. struct aead_request *req, struct bio *base_bio)
  1067. {
  1068. struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
  1069. if ((struct aead_request *)(io + 1) != req)
  1070. mempool_free(req, &cc->req_pool);
  1071. }
  1072. static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
  1073. {
  1074. if (crypt_integrity_aead(cc))
  1075. crypt_free_req_aead(cc, req, base_bio);
  1076. else
  1077. crypt_free_req_skcipher(cc, req, base_bio);
  1078. }
  1079. /*
  1080. * Encrypt / decrypt data from one bio to another one (can be the same one)
  1081. */
  1082. static blk_status_t crypt_convert(struct crypt_config *cc,
  1083. struct convert_context *ctx)
  1084. {
  1085. unsigned int tag_offset = 0;
  1086. unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
  1087. int r;
  1088. atomic_set(&ctx->cc_pending, 1);
  1089. while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
  1090. crypt_alloc_req(cc, ctx);
  1091. atomic_inc(&ctx->cc_pending);
  1092. if (crypt_integrity_aead(cc))
  1093. r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
  1094. else
  1095. r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
  1096. switch (r) {
  1097. /*
  1098. * The request was queued by a crypto driver
  1099. * but the driver request queue is full, let's wait.
  1100. */
  1101. case -EBUSY:
  1102. wait_for_completion(&ctx->restart);
  1103. reinit_completion(&ctx->restart);
  1104. /* fall through */
  1105. /*
  1106. * The request is queued and processed asynchronously,
  1107. * completion function kcryptd_async_done() will be called.
  1108. */
  1109. case -EINPROGRESS:
  1110. ctx->r.req = NULL;
  1111. ctx->cc_sector += sector_step;
  1112. tag_offset++;
  1113. continue;
  1114. /*
  1115. * The request was already processed (synchronously).
  1116. */
  1117. case 0:
  1118. atomic_dec(&ctx->cc_pending);
  1119. ctx->cc_sector += sector_step;
  1120. tag_offset++;
  1121. cond_resched();
  1122. continue;
  1123. /*
  1124. * There was a data integrity error.
  1125. */
  1126. case -EBADMSG:
  1127. atomic_dec(&ctx->cc_pending);
  1128. return BLK_STS_PROTECTION;
  1129. /*
  1130. * There was an error while processing the request.
  1131. */
  1132. default:
  1133. atomic_dec(&ctx->cc_pending);
  1134. return BLK_STS_IOERR;
  1135. }
  1136. }
  1137. return 0;
  1138. }
  1139. static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
  1140. /*
  1141. * Generate a new unfragmented bio with the given size
  1142. * This should never violate the device limitations (but only because
  1143. * max_segment_size is being constrained to PAGE_SIZE).
  1144. *
  1145. * This function may be called concurrently. If we allocate from the mempool
  1146. * concurrently, there is a possibility of deadlock. For example, if we have
  1147. * mempool of 256 pages, two processes, each wanting 256, pages allocate from
  1148. * the mempool concurrently, it may deadlock in a situation where both processes
  1149. * have allocated 128 pages and the mempool is exhausted.
  1150. *
  1151. * In order to avoid this scenario we allocate the pages under a mutex.
  1152. *
  1153. * In order to not degrade performance with excessive locking, we try
  1154. * non-blocking allocations without a mutex first but on failure we fallback
  1155. * to blocking allocations with a mutex.
  1156. */
  1157. static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
  1158. {
  1159. struct crypt_config *cc = io->cc;
  1160. struct bio *clone;
  1161. unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
  1162. gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
  1163. unsigned i, len, remaining_size;
  1164. struct page *page;
  1165. retry:
  1166. if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
  1167. mutex_lock(&cc->bio_alloc_lock);
  1168. clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, &cc->bs);
  1169. if (!clone)
  1170. goto out;
  1171. clone_init(io, clone);
  1172. remaining_size = size;
  1173. for (i = 0; i < nr_iovecs; i++) {
  1174. page = mempool_alloc(&cc->page_pool, gfp_mask);
  1175. if (!page) {
  1176. crypt_free_buffer_pages(cc, clone);
  1177. bio_put(clone);
  1178. gfp_mask |= __GFP_DIRECT_RECLAIM;
  1179. goto retry;
  1180. }
  1181. len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
  1182. bio_add_page(clone, page, len, 0);
  1183. remaining_size -= len;
  1184. }
  1185. /* Allocate space for integrity tags */
  1186. if (dm_crypt_integrity_io_alloc(io, clone)) {
  1187. crypt_free_buffer_pages(cc, clone);
  1188. bio_put(clone);
  1189. clone = NULL;
  1190. }
  1191. out:
  1192. if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
  1193. mutex_unlock(&cc->bio_alloc_lock);
  1194. return clone;
  1195. }
  1196. static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
  1197. {
  1198. unsigned int i;
  1199. struct bio_vec *bv;
  1200. bio_for_each_segment_all(bv, clone, i) {
  1201. BUG_ON(!bv->bv_page);
  1202. mempool_free(bv->bv_page, &cc->page_pool);
  1203. }
  1204. }
  1205. static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
  1206. struct bio *bio, sector_t sector)
  1207. {
  1208. io->cc = cc;
  1209. io->base_bio = bio;
  1210. io->sector = sector;
  1211. io->error = 0;
  1212. io->ctx.r.req = NULL;
  1213. io->integrity_metadata = NULL;
  1214. io->integrity_metadata_from_pool = false;
  1215. atomic_set(&io->io_pending, 0);
  1216. }
  1217. static void crypt_inc_pending(struct dm_crypt_io *io)
  1218. {
  1219. atomic_inc(&io->io_pending);
  1220. }
  1221. /*
  1222. * One of the bios was finished. Check for completion of
  1223. * the whole request and correctly clean up the buffer.
  1224. */
  1225. static void crypt_dec_pending(struct dm_crypt_io *io)
  1226. {
  1227. struct crypt_config *cc = io->cc;
  1228. struct bio *base_bio = io->base_bio;
  1229. blk_status_t error = io->error;
  1230. if (!atomic_dec_and_test(&io->io_pending))
  1231. return;
  1232. if (io->ctx.r.req)
  1233. crypt_free_req(cc, io->ctx.r.req, base_bio);
  1234. if (unlikely(io->integrity_metadata_from_pool))
  1235. mempool_free(io->integrity_metadata, &io->cc->tag_pool);
  1236. else
  1237. kfree(io->integrity_metadata);
  1238. base_bio->bi_status = error;
  1239. bio_endio(base_bio);
  1240. }
  1241. /*
  1242. * kcryptd/kcryptd_io:
  1243. *
  1244. * Needed because it would be very unwise to do decryption in an
  1245. * interrupt context.
  1246. *
  1247. * kcryptd performs the actual encryption or decryption.
  1248. *
  1249. * kcryptd_io performs the IO submission.
  1250. *
  1251. * They must be separated as otherwise the final stages could be
  1252. * starved by new requests which can block in the first stages due
  1253. * to memory allocation.
  1254. *
  1255. * The work is done per CPU global for all dm-crypt instances.
  1256. * They should not depend on each other and do not block.
  1257. */
  1258. static void crypt_endio(struct bio *clone)
  1259. {
  1260. struct dm_crypt_io *io = clone->bi_private;
  1261. struct crypt_config *cc = io->cc;
  1262. unsigned rw = bio_data_dir(clone);
  1263. blk_status_t error;
  1264. /*
  1265. * free the processed pages
  1266. */
  1267. if (rw == WRITE)
  1268. crypt_free_buffer_pages(cc, clone);
  1269. error = clone->bi_status;
  1270. bio_put(clone);
  1271. if (rw == READ && !error) {
  1272. kcryptd_queue_crypt(io);
  1273. return;
  1274. }
  1275. if (unlikely(error))
  1276. io->error = error;
  1277. crypt_dec_pending(io);
  1278. }
  1279. static void clone_init(struct dm_crypt_io *io, struct bio *clone)
  1280. {
  1281. struct crypt_config *cc = io->cc;
  1282. clone->bi_private = io;
  1283. clone->bi_end_io = crypt_endio;
  1284. bio_set_dev(clone, cc->dev->bdev);
  1285. clone->bi_opf = io->base_bio->bi_opf;
  1286. }
  1287. static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
  1288. {
  1289. struct crypt_config *cc = io->cc;
  1290. struct bio *clone;
  1291. /*
  1292. * We need the original biovec array in order to decrypt
  1293. * the whole bio data *afterwards* -- thanks to immutable
  1294. * biovecs we don't need to worry about the block layer
  1295. * modifying the biovec array; so leverage bio_clone_fast().
  1296. */
  1297. clone = bio_clone_fast(io->base_bio, gfp, &cc->bs);
  1298. if (!clone)
  1299. return 1;
  1300. crypt_inc_pending(io);
  1301. clone_init(io, clone);
  1302. clone->bi_iter.bi_sector = cc->start + io->sector;
  1303. if (dm_crypt_integrity_io_alloc(io, clone)) {
  1304. crypt_dec_pending(io);
  1305. bio_put(clone);
  1306. return 1;
  1307. }
  1308. generic_make_request(clone);
  1309. return 0;
  1310. }
  1311. static void kcryptd_io_read_work(struct work_struct *work)
  1312. {
  1313. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  1314. crypt_inc_pending(io);
  1315. if (kcryptd_io_read(io, GFP_NOIO))
  1316. io->error = BLK_STS_RESOURCE;
  1317. crypt_dec_pending(io);
  1318. }
  1319. static void kcryptd_queue_read(struct dm_crypt_io *io)
  1320. {
  1321. struct crypt_config *cc = io->cc;
  1322. INIT_WORK(&io->work, kcryptd_io_read_work);
  1323. queue_work(cc->io_queue, &io->work);
  1324. }
  1325. static void kcryptd_io_write(struct dm_crypt_io *io)
  1326. {
  1327. struct bio *clone = io->ctx.bio_out;
  1328. generic_make_request(clone);
  1329. }
  1330. #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
  1331. static int dmcrypt_write(void *data)
  1332. {
  1333. struct crypt_config *cc = data;
  1334. struct dm_crypt_io *io;
  1335. while (1) {
  1336. struct rb_root write_tree;
  1337. struct blk_plug plug;
  1338. spin_lock_irq(&cc->write_thread_lock);
  1339. continue_locked:
  1340. if (!RB_EMPTY_ROOT(&cc->write_tree))
  1341. goto pop_from_list;
  1342. set_current_state(TASK_INTERRUPTIBLE);
  1343. spin_unlock_irq(&cc->write_thread_lock);
  1344. if (unlikely(kthread_should_stop())) {
  1345. set_current_state(TASK_RUNNING);
  1346. break;
  1347. }
  1348. schedule();
  1349. set_current_state(TASK_RUNNING);
  1350. spin_lock_irq(&cc->write_thread_lock);
  1351. goto continue_locked;
  1352. pop_from_list:
  1353. write_tree = cc->write_tree;
  1354. cc->write_tree = RB_ROOT;
  1355. spin_unlock_irq(&cc->write_thread_lock);
  1356. BUG_ON(rb_parent(write_tree.rb_node));
  1357. /*
  1358. * Note: we cannot walk the tree here with rb_next because
  1359. * the structures may be freed when kcryptd_io_write is called.
  1360. */
  1361. blk_start_plug(&plug);
  1362. do {
  1363. io = crypt_io_from_node(rb_first(&write_tree));
  1364. rb_erase(&io->rb_node, &write_tree);
  1365. kcryptd_io_write(io);
  1366. } while (!RB_EMPTY_ROOT(&write_tree));
  1367. blk_finish_plug(&plug);
  1368. }
  1369. return 0;
  1370. }
  1371. static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
  1372. {
  1373. struct bio *clone = io->ctx.bio_out;
  1374. struct crypt_config *cc = io->cc;
  1375. unsigned long flags;
  1376. sector_t sector;
  1377. struct rb_node **rbp, *parent;
  1378. if (unlikely(io->error)) {
  1379. crypt_free_buffer_pages(cc, clone);
  1380. bio_put(clone);
  1381. crypt_dec_pending(io);
  1382. return;
  1383. }
  1384. /* crypt_convert should have filled the clone bio */
  1385. BUG_ON(io->ctx.iter_out.bi_size);
  1386. clone->bi_iter.bi_sector = cc->start + io->sector;
  1387. if (likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) {
  1388. generic_make_request(clone);
  1389. return;
  1390. }
  1391. spin_lock_irqsave(&cc->write_thread_lock, flags);
  1392. if (RB_EMPTY_ROOT(&cc->write_tree))
  1393. wake_up_process(cc->write_thread);
  1394. rbp = &cc->write_tree.rb_node;
  1395. parent = NULL;
  1396. sector = io->sector;
  1397. while (*rbp) {
  1398. parent = *rbp;
  1399. if (sector < crypt_io_from_node(parent)->sector)
  1400. rbp = &(*rbp)->rb_left;
  1401. else
  1402. rbp = &(*rbp)->rb_right;
  1403. }
  1404. rb_link_node(&io->rb_node, parent, rbp);
  1405. rb_insert_color(&io->rb_node, &cc->write_tree);
  1406. spin_unlock_irqrestore(&cc->write_thread_lock, flags);
  1407. }
  1408. static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
  1409. {
  1410. struct crypt_config *cc = io->cc;
  1411. struct bio *clone;
  1412. int crypt_finished;
  1413. sector_t sector = io->sector;
  1414. blk_status_t r;
  1415. /*
  1416. * Prevent io from disappearing until this function completes.
  1417. */
  1418. crypt_inc_pending(io);
  1419. crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
  1420. clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
  1421. if (unlikely(!clone)) {
  1422. io->error = BLK_STS_IOERR;
  1423. goto dec;
  1424. }
  1425. io->ctx.bio_out = clone;
  1426. io->ctx.iter_out = clone->bi_iter;
  1427. sector += bio_sectors(clone);
  1428. crypt_inc_pending(io);
  1429. r = crypt_convert(cc, &io->ctx);
  1430. if (r)
  1431. io->error = r;
  1432. crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
  1433. /* Encryption was already finished, submit io now */
  1434. if (crypt_finished) {
  1435. kcryptd_crypt_write_io_submit(io, 0);
  1436. io->sector = sector;
  1437. }
  1438. dec:
  1439. crypt_dec_pending(io);
  1440. }
  1441. static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
  1442. {
  1443. crypt_dec_pending(io);
  1444. }
  1445. static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
  1446. {
  1447. struct crypt_config *cc = io->cc;
  1448. blk_status_t r;
  1449. crypt_inc_pending(io);
  1450. crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
  1451. io->sector);
  1452. r = crypt_convert(cc, &io->ctx);
  1453. if (r)
  1454. io->error = r;
  1455. if (atomic_dec_and_test(&io->ctx.cc_pending))
  1456. kcryptd_crypt_read_done(io);
  1457. crypt_dec_pending(io);
  1458. }
  1459. static void kcryptd_async_done(struct crypto_async_request *async_req,
  1460. int error)
  1461. {
  1462. struct dm_crypt_request *dmreq = async_req->data;
  1463. struct convert_context *ctx = dmreq->ctx;
  1464. struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
  1465. struct crypt_config *cc = io->cc;
  1466. /*
  1467. * A request from crypto driver backlog is going to be processed now,
  1468. * finish the completion and continue in crypt_convert().
  1469. * (Callback will be called for the second time for this request.)
  1470. */
  1471. if (error == -EINPROGRESS) {
  1472. complete(&ctx->restart);
  1473. return;
  1474. }
  1475. if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
  1476. error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
  1477. if (error == -EBADMSG) {
  1478. DMERR_LIMIT("INTEGRITY AEAD ERROR, sector %llu",
  1479. (unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc, dmreq)));
  1480. io->error = BLK_STS_PROTECTION;
  1481. } else if (error < 0)
  1482. io->error = BLK_STS_IOERR;
  1483. crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
  1484. if (!atomic_dec_and_test(&ctx->cc_pending))
  1485. return;
  1486. if (bio_data_dir(io->base_bio) == READ)
  1487. kcryptd_crypt_read_done(io);
  1488. else
  1489. kcryptd_crypt_write_io_submit(io, 1);
  1490. }
  1491. static void kcryptd_crypt(struct work_struct *work)
  1492. {
  1493. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  1494. if (bio_data_dir(io->base_bio) == READ)
  1495. kcryptd_crypt_read_convert(io);
  1496. else
  1497. kcryptd_crypt_write_convert(io);
  1498. }
  1499. static void kcryptd_queue_crypt(struct dm_crypt_io *io)
  1500. {
  1501. struct crypt_config *cc = io->cc;
  1502. INIT_WORK(&io->work, kcryptd_crypt);
  1503. queue_work(cc->crypt_queue, &io->work);
  1504. }
  1505. static void crypt_free_tfms_aead(struct crypt_config *cc)
  1506. {
  1507. if (!cc->cipher_tfm.tfms_aead)
  1508. return;
  1509. if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
  1510. crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
  1511. cc->cipher_tfm.tfms_aead[0] = NULL;
  1512. }
  1513. kfree(cc->cipher_tfm.tfms_aead);
  1514. cc->cipher_tfm.tfms_aead = NULL;
  1515. }
  1516. static void crypt_free_tfms_skcipher(struct crypt_config *cc)
  1517. {
  1518. unsigned i;
  1519. if (!cc->cipher_tfm.tfms)
  1520. return;
  1521. for (i = 0; i < cc->tfms_count; i++)
  1522. if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
  1523. crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
  1524. cc->cipher_tfm.tfms[i] = NULL;
  1525. }
  1526. kfree(cc->cipher_tfm.tfms);
  1527. cc->cipher_tfm.tfms = NULL;
  1528. }
  1529. static void crypt_free_tfms(struct crypt_config *cc)
  1530. {
  1531. if (crypt_integrity_aead(cc))
  1532. crypt_free_tfms_aead(cc);
  1533. else
  1534. crypt_free_tfms_skcipher(cc);
  1535. }
  1536. static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
  1537. {
  1538. unsigned i;
  1539. int err;
  1540. cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
  1541. sizeof(struct crypto_skcipher *),
  1542. GFP_KERNEL);
  1543. if (!cc->cipher_tfm.tfms)
  1544. return -ENOMEM;
  1545. for (i = 0; i < cc->tfms_count; i++) {
  1546. cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0, 0);
  1547. if (IS_ERR(cc->cipher_tfm.tfms[i])) {
  1548. err = PTR_ERR(cc->cipher_tfm.tfms[i]);
  1549. crypt_free_tfms(cc);
  1550. return err;
  1551. }
  1552. }
  1553. return 0;
  1554. }
  1555. static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
  1556. {
  1557. int err;
  1558. cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
  1559. if (!cc->cipher_tfm.tfms)
  1560. return -ENOMEM;
  1561. cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0, 0);
  1562. if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
  1563. err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
  1564. crypt_free_tfms(cc);
  1565. return err;
  1566. }
  1567. return 0;
  1568. }
  1569. static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
  1570. {
  1571. if (crypt_integrity_aead(cc))
  1572. return crypt_alloc_tfms_aead(cc, ciphermode);
  1573. else
  1574. return crypt_alloc_tfms_skcipher(cc, ciphermode);
  1575. }
  1576. static unsigned crypt_subkey_size(struct crypt_config *cc)
  1577. {
  1578. return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
  1579. }
  1580. static unsigned crypt_authenckey_size(struct crypt_config *cc)
  1581. {
  1582. return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
  1583. }
  1584. /*
  1585. * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
  1586. * the key must be for some reason in special format.
  1587. * This funcion converts cc->key to this special format.
  1588. */
  1589. static void crypt_copy_authenckey(char *p, const void *key,
  1590. unsigned enckeylen, unsigned authkeylen)
  1591. {
  1592. struct crypto_authenc_key_param *param;
  1593. struct rtattr *rta;
  1594. rta = (struct rtattr *)p;
  1595. param = RTA_DATA(rta);
  1596. param->enckeylen = cpu_to_be32(enckeylen);
  1597. rta->rta_len = RTA_LENGTH(sizeof(*param));
  1598. rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
  1599. p += RTA_SPACE(sizeof(*param));
  1600. memcpy(p, key + enckeylen, authkeylen);
  1601. p += authkeylen;
  1602. memcpy(p, key, enckeylen);
  1603. }
  1604. static int crypt_setkey(struct crypt_config *cc)
  1605. {
  1606. unsigned subkey_size;
  1607. int err = 0, i, r;
  1608. /* Ignore extra keys (which are used for IV etc) */
  1609. subkey_size = crypt_subkey_size(cc);
  1610. if (crypt_integrity_hmac(cc)) {
  1611. if (subkey_size < cc->key_mac_size)
  1612. return -EINVAL;
  1613. crypt_copy_authenckey(cc->authenc_key, cc->key,
  1614. subkey_size - cc->key_mac_size,
  1615. cc->key_mac_size);
  1616. }
  1617. for (i = 0; i < cc->tfms_count; i++) {
  1618. if (crypt_integrity_hmac(cc))
  1619. r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
  1620. cc->authenc_key, crypt_authenckey_size(cc));
  1621. else if (crypt_integrity_aead(cc))
  1622. r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
  1623. cc->key + (i * subkey_size),
  1624. subkey_size);
  1625. else
  1626. r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
  1627. cc->key + (i * subkey_size),
  1628. subkey_size);
  1629. if (r)
  1630. err = r;
  1631. }
  1632. if (crypt_integrity_hmac(cc))
  1633. memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
  1634. return err;
  1635. }
  1636. #ifdef CONFIG_KEYS
  1637. static bool contains_whitespace(const char *str)
  1638. {
  1639. while (*str)
  1640. if (isspace(*str++))
  1641. return true;
  1642. return false;
  1643. }
  1644. static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
  1645. {
  1646. char *new_key_string, *key_desc;
  1647. int ret;
  1648. struct key *key;
  1649. const struct user_key_payload *ukp;
  1650. /*
  1651. * Reject key_string with whitespace. dm core currently lacks code for
  1652. * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
  1653. */
  1654. if (contains_whitespace(key_string)) {
  1655. DMERR("whitespace chars not allowed in key string");
  1656. return -EINVAL;
  1657. }
  1658. /* look for next ':' separating key_type from key_description */
  1659. key_desc = strpbrk(key_string, ":");
  1660. if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
  1661. return -EINVAL;
  1662. if (strncmp(key_string, "logon:", key_desc - key_string + 1) &&
  1663. strncmp(key_string, "user:", key_desc - key_string + 1))
  1664. return -EINVAL;
  1665. new_key_string = kstrdup(key_string, GFP_KERNEL);
  1666. if (!new_key_string)
  1667. return -ENOMEM;
  1668. key = request_key(key_string[0] == 'l' ? &key_type_logon : &key_type_user,
  1669. key_desc + 1, NULL);
  1670. if (IS_ERR(key)) {
  1671. kzfree(new_key_string);
  1672. return PTR_ERR(key);
  1673. }
  1674. down_read(&key->sem);
  1675. ukp = user_key_payload_locked(key);
  1676. if (!ukp) {
  1677. up_read(&key->sem);
  1678. key_put(key);
  1679. kzfree(new_key_string);
  1680. return -EKEYREVOKED;
  1681. }
  1682. if (cc->key_size != ukp->datalen) {
  1683. up_read(&key->sem);
  1684. key_put(key);
  1685. kzfree(new_key_string);
  1686. return -EINVAL;
  1687. }
  1688. memcpy(cc->key, ukp->data, cc->key_size);
  1689. up_read(&key->sem);
  1690. key_put(key);
  1691. /* clear the flag since following operations may invalidate previously valid key */
  1692. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1693. ret = crypt_setkey(cc);
  1694. if (!ret) {
  1695. set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1696. kzfree(cc->key_string);
  1697. cc->key_string = new_key_string;
  1698. } else
  1699. kzfree(new_key_string);
  1700. return ret;
  1701. }
  1702. static int get_key_size(char **key_string)
  1703. {
  1704. char *colon, dummy;
  1705. int ret;
  1706. if (*key_string[0] != ':')
  1707. return strlen(*key_string) >> 1;
  1708. /* look for next ':' in key string */
  1709. colon = strpbrk(*key_string + 1, ":");
  1710. if (!colon)
  1711. return -EINVAL;
  1712. if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
  1713. return -EINVAL;
  1714. *key_string = colon;
  1715. /* remaining key string should be :<logon|user>:<key_desc> */
  1716. return ret;
  1717. }
  1718. #else
  1719. static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
  1720. {
  1721. return -EINVAL;
  1722. }
  1723. static int get_key_size(char **key_string)
  1724. {
  1725. return (*key_string[0] == ':') ? -EINVAL : strlen(*key_string) >> 1;
  1726. }
  1727. #endif
  1728. static int crypt_set_key(struct crypt_config *cc, char *key)
  1729. {
  1730. int r = -EINVAL;
  1731. int key_string_len = strlen(key);
  1732. /* Hyphen (which gives a key_size of zero) means there is no key. */
  1733. if (!cc->key_size && strcmp(key, "-"))
  1734. goto out;
  1735. /* ':' means the key is in kernel keyring, short-circuit normal key processing */
  1736. if (key[0] == ':') {
  1737. r = crypt_set_keyring_key(cc, key + 1);
  1738. goto out;
  1739. }
  1740. /* clear the flag since following operations may invalidate previously valid key */
  1741. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1742. /* wipe references to any kernel keyring key */
  1743. kzfree(cc->key_string);
  1744. cc->key_string = NULL;
  1745. /* Decode key from its hex representation. */
  1746. if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
  1747. goto out;
  1748. r = crypt_setkey(cc);
  1749. if (!r)
  1750. set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1751. out:
  1752. /* Hex key string not needed after here, so wipe it. */
  1753. memset(key, '0', key_string_len);
  1754. return r;
  1755. }
  1756. static int crypt_wipe_key(struct crypt_config *cc)
  1757. {
  1758. int r;
  1759. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1760. get_random_bytes(&cc->key, cc->key_size);
  1761. kzfree(cc->key_string);
  1762. cc->key_string = NULL;
  1763. r = crypt_setkey(cc);
  1764. memset(&cc->key, 0, cc->key_size * sizeof(u8));
  1765. return r;
  1766. }
  1767. static void crypt_calculate_pages_per_client(void)
  1768. {
  1769. unsigned long pages = (totalram_pages - totalhigh_pages) * DM_CRYPT_MEMORY_PERCENT / 100;
  1770. if (!dm_crypt_clients_n)
  1771. return;
  1772. pages /= dm_crypt_clients_n;
  1773. if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
  1774. pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
  1775. dm_crypt_pages_per_client = pages;
  1776. }
  1777. static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
  1778. {
  1779. struct crypt_config *cc = pool_data;
  1780. struct page *page;
  1781. if (unlikely(percpu_counter_compare(&cc->n_allocated_pages, dm_crypt_pages_per_client) >= 0) &&
  1782. likely(gfp_mask & __GFP_NORETRY))
  1783. return NULL;
  1784. page = alloc_page(gfp_mask);
  1785. if (likely(page != NULL))
  1786. percpu_counter_add(&cc->n_allocated_pages, 1);
  1787. return page;
  1788. }
  1789. static void crypt_page_free(void *page, void *pool_data)
  1790. {
  1791. struct crypt_config *cc = pool_data;
  1792. __free_page(page);
  1793. percpu_counter_sub(&cc->n_allocated_pages, 1);
  1794. }
  1795. static void crypt_dtr(struct dm_target *ti)
  1796. {
  1797. struct crypt_config *cc = ti->private;
  1798. ti->private = NULL;
  1799. if (!cc)
  1800. return;
  1801. if (cc->write_thread)
  1802. kthread_stop(cc->write_thread);
  1803. if (cc->io_queue)
  1804. destroy_workqueue(cc->io_queue);
  1805. if (cc->crypt_queue)
  1806. destroy_workqueue(cc->crypt_queue);
  1807. crypt_free_tfms(cc);
  1808. bioset_exit(&cc->bs);
  1809. mempool_exit(&cc->page_pool);
  1810. mempool_exit(&cc->req_pool);
  1811. mempool_exit(&cc->tag_pool);
  1812. WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
  1813. percpu_counter_destroy(&cc->n_allocated_pages);
  1814. if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
  1815. cc->iv_gen_ops->dtr(cc);
  1816. if (cc->dev)
  1817. dm_put_device(ti, cc->dev);
  1818. kzfree(cc->cipher);
  1819. kzfree(cc->cipher_string);
  1820. kzfree(cc->key_string);
  1821. kzfree(cc->cipher_auth);
  1822. kzfree(cc->authenc_key);
  1823. mutex_destroy(&cc->bio_alloc_lock);
  1824. /* Must zero key material before freeing */
  1825. kzfree(cc);
  1826. spin_lock(&dm_crypt_clients_lock);
  1827. WARN_ON(!dm_crypt_clients_n);
  1828. dm_crypt_clients_n--;
  1829. crypt_calculate_pages_per_client();
  1830. spin_unlock(&dm_crypt_clients_lock);
  1831. }
  1832. static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
  1833. {
  1834. struct crypt_config *cc = ti->private;
  1835. if (crypt_integrity_aead(cc))
  1836. cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
  1837. else
  1838. cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
  1839. if (cc->iv_size)
  1840. /* at least a 64 bit sector number should fit in our buffer */
  1841. cc->iv_size = max(cc->iv_size,
  1842. (unsigned int)(sizeof(u64) / sizeof(u8)));
  1843. else if (ivmode) {
  1844. DMWARN("Selected cipher does not support IVs");
  1845. ivmode = NULL;
  1846. }
  1847. /* Choose ivmode, see comments at iv code. */
  1848. if (ivmode == NULL)
  1849. cc->iv_gen_ops = NULL;
  1850. else if (strcmp(ivmode, "plain") == 0)
  1851. cc->iv_gen_ops = &crypt_iv_plain_ops;
  1852. else if (strcmp(ivmode, "plain64") == 0)
  1853. cc->iv_gen_ops = &crypt_iv_plain64_ops;
  1854. else if (strcmp(ivmode, "plain64be") == 0)
  1855. cc->iv_gen_ops = &crypt_iv_plain64be_ops;
  1856. else if (strcmp(ivmode, "essiv") == 0)
  1857. cc->iv_gen_ops = &crypt_iv_essiv_ops;
  1858. else if (strcmp(ivmode, "benbi") == 0)
  1859. cc->iv_gen_ops = &crypt_iv_benbi_ops;
  1860. else if (strcmp(ivmode, "null") == 0)
  1861. cc->iv_gen_ops = &crypt_iv_null_ops;
  1862. else if (strcmp(ivmode, "lmk") == 0) {
  1863. cc->iv_gen_ops = &crypt_iv_lmk_ops;
  1864. /*
  1865. * Version 2 and 3 is recognised according
  1866. * to length of provided multi-key string.
  1867. * If present (version 3), last key is used as IV seed.
  1868. * All keys (including IV seed) are always the same size.
  1869. */
  1870. if (cc->key_size % cc->key_parts) {
  1871. cc->key_parts++;
  1872. cc->key_extra_size = cc->key_size / cc->key_parts;
  1873. }
  1874. } else if (strcmp(ivmode, "tcw") == 0) {
  1875. cc->iv_gen_ops = &crypt_iv_tcw_ops;
  1876. cc->key_parts += 2; /* IV + whitening */
  1877. cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
  1878. } else if (strcmp(ivmode, "random") == 0) {
  1879. cc->iv_gen_ops = &crypt_iv_random_ops;
  1880. /* Need storage space in integrity fields. */
  1881. cc->integrity_iv_size = cc->iv_size;
  1882. } else {
  1883. ti->error = "Invalid IV mode";
  1884. return -EINVAL;
  1885. }
  1886. return 0;
  1887. }
  1888. /*
  1889. * Workaround to parse cipher algorithm from crypto API spec.
  1890. * The cc->cipher is currently used only in ESSIV.
  1891. * This should be probably done by crypto-api calls (once available...)
  1892. */
  1893. static int crypt_ctr_blkdev_cipher(struct crypt_config *cc)
  1894. {
  1895. const char *alg_name = NULL;
  1896. char *start, *end;
  1897. if (crypt_integrity_aead(cc)) {
  1898. alg_name = crypto_tfm_alg_name(crypto_aead_tfm(any_tfm_aead(cc)));
  1899. if (!alg_name)
  1900. return -EINVAL;
  1901. if (crypt_integrity_hmac(cc)) {
  1902. alg_name = strchr(alg_name, ',');
  1903. if (!alg_name)
  1904. return -EINVAL;
  1905. }
  1906. alg_name++;
  1907. } else {
  1908. alg_name = crypto_tfm_alg_name(crypto_skcipher_tfm(any_tfm(cc)));
  1909. if (!alg_name)
  1910. return -EINVAL;
  1911. }
  1912. start = strchr(alg_name, '(');
  1913. end = strchr(alg_name, ')');
  1914. if (!start && !end) {
  1915. cc->cipher = kstrdup(alg_name, GFP_KERNEL);
  1916. return cc->cipher ? 0 : -ENOMEM;
  1917. }
  1918. if (!start || !end || ++start >= end)
  1919. return -EINVAL;
  1920. cc->cipher = kzalloc(end - start + 1, GFP_KERNEL);
  1921. if (!cc->cipher)
  1922. return -ENOMEM;
  1923. strncpy(cc->cipher, start, end - start);
  1924. return 0;
  1925. }
  1926. /*
  1927. * Workaround to parse HMAC algorithm from AEAD crypto API spec.
  1928. * The HMAC is needed to calculate tag size (HMAC digest size).
  1929. * This should be probably done by crypto-api calls (once available...)
  1930. */
  1931. static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
  1932. {
  1933. char *start, *end, *mac_alg = NULL;
  1934. struct crypto_ahash *mac;
  1935. if (!strstarts(cipher_api, "authenc("))
  1936. return 0;
  1937. start = strchr(cipher_api, '(');
  1938. end = strchr(cipher_api, ',');
  1939. if (!start || !end || ++start > end)
  1940. return -EINVAL;
  1941. mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
  1942. if (!mac_alg)
  1943. return -ENOMEM;
  1944. strncpy(mac_alg, start, end - start);
  1945. mac = crypto_alloc_ahash(mac_alg, 0, 0);
  1946. kfree(mac_alg);
  1947. if (IS_ERR(mac))
  1948. return PTR_ERR(mac);
  1949. cc->key_mac_size = crypto_ahash_digestsize(mac);
  1950. crypto_free_ahash(mac);
  1951. cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
  1952. if (!cc->authenc_key)
  1953. return -ENOMEM;
  1954. return 0;
  1955. }
  1956. static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
  1957. char **ivmode, char **ivopts)
  1958. {
  1959. struct crypt_config *cc = ti->private;
  1960. char *tmp, *cipher_api;
  1961. int ret = -EINVAL;
  1962. cc->tfms_count = 1;
  1963. /*
  1964. * New format (capi: prefix)
  1965. * capi:cipher_api_spec-iv:ivopts
  1966. */
  1967. tmp = &cipher_in[strlen("capi:")];
  1968. cipher_api = strsep(&tmp, "-");
  1969. *ivmode = strsep(&tmp, ":");
  1970. *ivopts = tmp;
  1971. if (*ivmode && !strcmp(*ivmode, "lmk"))
  1972. cc->tfms_count = 64;
  1973. cc->key_parts = cc->tfms_count;
  1974. /* Allocate cipher */
  1975. ret = crypt_alloc_tfms(cc, cipher_api);
  1976. if (ret < 0) {
  1977. ti->error = "Error allocating crypto tfm";
  1978. return ret;
  1979. }
  1980. /* Alloc AEAD, can be used only in new format. */
  1981. if (crypt_integrity_aead(cc)) {
  1982. ret = crypt_ctr_auth_cipher(cc, cipher_api);
  1983. if (ret < 0) {
  1984. ti->error = "Invalid AEAD cipher spec";
  1985. return -ENOMEM;
  1986. }
  1987. cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
  1988. } else
  1989. cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
  1990. ret = crypt_ctr_blkdev_cipher(cc);
  1991. if (ret < 0) {
  1992. ti->error = "Cannot allocate cipher string";
  1993. return -ENOMEM;
  1994. }
  1995. return 0;
  1996. }
  1997. static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
  1998. char **ivmode, char **ivopts)
  1999. {
  2000. struct crypt_config *cc = ti->private;
  2001. char *tmp, *cipher, *chainmode, *keycount;
  2002. char *cipher_api = NULL;
  2003. int ret = -EINVAL;
  2004. char dummy;
  2005. if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
  2006. ti->error = "Bad cipher specification";
  2007. return -EINVAL;
  2008. }
  2009. /*
  2010. * Legacy dm-crypt cipher specification
  2011. * cipher[:keycount]-mode-iv:ivopts
  2012. */
  2013. tmp = cipher_in;
  2014. keycount = strsep(&tmp, "-");
  2015. cipher = strsep(&keycount, ":");
  2016. if (!keycount)
  2017. cc->tfms_count = 1;
  2018. else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
  2019. !is_power_of_2(cc->tfms_count)) {
  2020. ti->error = "Bad cipher key count specification";
  2021. return -EINVAL;
  2022. }
  2023. cc->key_parts = cc->tfms_count;
  2024. cc->cipher = kstrdup(cipher, GFP_KERNEL);
  2025. if (!cc->cipher)
  2026. goto bad_mem;
  2027. chainmode = strsep(&tmp, "-");
  2028. *ivopts = strsep(&tmp, "-");
  2029. *ivmode = strsep(&*ivopts, ":");
  2030. if (tmp)
  2031. DMWARN("Ignoring unexpected additional cipher options");
  2032. /*
  2033. * For compatibility with the original dm-crypt mapping format, if
  2034. * only the cipher name is supplied, use cbc-plain.
  2035. */
  2036. if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
  2037. chainmode = "cbc";
  2038. *ivmode = "plain";
  2039. }
  2040. if (strcmp(chainmode, "ecb") && !*ivmode) {
  2041. ti->error = "IV mechanism required";
  2042. return -EINVAL;
  2043. }
  2044. cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
  2045. if (!cipher_api)
  2046. goto bad_mem;
  2047. ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
  2048. "%s(%s)", chainmode, cipher);
  2049. if (ret < 0) {
  2050. kfree(cipher_api);
  2051. goto bad_mem;
  2052. }
  2053. /* Allocate cipher */
  2054. ret = crypt_alloc_tfms(cc, cipher_api);
  2055. if (ret < 0) {
  2056. ti->error = "Error allocating crypto tfm";
  2057. kfree(cipher_api);
  2058. return ret;
  2059. }
  2060. kfree(cipher_api);
  2061. return 0;
  2062. bad_mem:
  2063. ti->error = "Cannot allocate cipher strings";
  2064. return -ENOMEM;
  2065. }
  2066. static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
  2067. {
  2068. struct crypt_config *cc = ti->private;
  2069. char *ivmode = NULL, *ivopts = NULL;
  2070. int ret;
  2071. cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
  2072. if (!cc->cipher_string) {
  2073. ti->error = "Cannot allocate cipher strings";
  2074. return -ENOMEM;
  2075. }
  2076. if (strstarts(cipher_in, "capi:"))
  2077. ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
  2078. else
  2079. ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
  2080. if (ret)
  2081. return ret;
  2082. /* Initialize IV */
  2083. ret = crypt_ctr_ivmode(ti, ivmode);
  2084. if (ret < 0)
  2085. return ret;
  2086. /* Initialize and set key */
  2087. ret = crypt_set_key(cc, key);
  2088. if (ret < 0) {
  2089. ti->error = "Error decoding and setting key";
  2090. return ret;
  2091. }
  2092. /* Allocate IV */
  2093. if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
  2094. ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
  2095. if (ret < 0) {
  2096. ti->error = "Error creating IV";
  2097. return ret;
  2098. }
  2099. }
  2100. /* Initialize IV (set keys for ESSIV etc) */
  2101. if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
  2102. ret = cc->iv_gen_ops->init(cc);
  2103. if (ret < 0) {
  2104. ti->error = "Error initialising IV";
  2105. return ret;
  2106. }
  2107. }
  2108. /* wipe the kernel key payload copy */
  2109. if (cc->key_string)
  2110. memset(cc->key, 0, cc->key_size * sizeof(u8));
  2111. return ret;
  2112. }
  2113. static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
  2114. {
  2115. struct crypt_config *cc = ti->private;
  2116. struct dm_arg_set as;
  2117. static const struct dm_arg _args[] = {
  2118. {0, 6, "Invalid number of feature args"},
  2119. };
  2120. unsigned int opt_params, val;
  2121. const char *opt_string, *sval;
  2122. char dummy;
  2123. int ret;
  2124. /* Optional parameters */
  2125. as.argc = argc;
  2126. as.argv = argv;
  2127. ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
  2128. if (ret)
  2129. return ret;
  2130. while (opt_params--) {
  2131. opt_string = dm_shift_arg(&as);
  2132. if (!opt_string) {
  2133. ti->error = "Not enough feature arguments";
  2134. return -EINVAL;
  2135. }
  2136. if (!strcasecmp(opt_string, "allow_discards"))
  2137. ti->num_discard_bios = 1;
  2138. else if (!strcasecmp(opt_string, "same_cpu_crypt"))
  2139. set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
  2140. else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
  2141. set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
  2142. else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
  2143. if (val == 0 || val > MAX_TAG_SIZE) {
  2144. ti->error = "Invalid integrity arguments";
  2145. return -EINVAL;
  2146. }
  2147. cc->on_disk_tag_size = val;
  2148. sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
  2149. if (!strcasecmp(sval, "aead")) {
  2150. set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
  2151. } else if (strcasecmp(sval, "none")) {
  2152. ti->error = "Unknown integrity profile";
  2153. return -EINVAL;
  2154. }
  2155. cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
  2156. if (!cc->cipher_auth)
  2157. return -ENOMEM;
  2158. } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
  2159. if (cc->sector_size < (1 << SECTOR_SHIFT) ||
  2160. cc->sector_size > 4096 ||
  2161. (cc->sector_size & (cc->sector_size - 1))) {
  2162. ti->error = "Invalid feature value for sector_size";
  2163. return -EINVAL;
  2164. }
  2165. if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
  2166. ti->error = "Device size is not multiple of sector_size feature";
  2167. return -EINVAL;
  2168. }
  2169. cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
  2170. } else if (!strcasecmp(opt_string, "iv_large_sectors"))
  2171. set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
  2172. else {
  2173. ti->error = "Invalid feature arguments";
  2174. return -EINVAL;
  2175. }
  2176. }
  2177. return 0;
  2178. }
  2179. /*
  2180. * Construct an encryption mapping:
  2181. * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
  2182. */
  2183. static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
  2184. {
  2185. struct crypt_config *cc;
  2186. int key_size;
  2187. unsigned int align_mask;
  2188. unsigned long long tmpll;
  2189. int ret;
  2190. size_t iv_size_padding, additional_req_size;
  2191. char dummy;
  2192. if (argc < 5) {
  2193. ti->error = "Not enough arguments";
  2194. return -EINVAL;
  2195. }
  2196. key_size = get_key_size(&argv[1]);
  2197. if (key_size < 0) {
  2198. ti->error = "Cannot parse key size";
  2199. return -EINVAL;
  2200. }
  2201. cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
  2202. if (!cc) {
  2203. ti->error = "Cannot allocate encryption context";
  2204. return -ENOMEM;
  2205. }
  2206. cc->key_size = key_size;
  2207. cc->sector_size = (1 << SECTOR_SHIFT);
  2208. cc->sector_shift = 0;
  2209. ti->private = cc;
  2210. spin_lock(&dm_crypt_clients_lock);
  2211. dm_crypt_clients_n++;
  2212. crypt_calculate_pages_per_client();
  2213. spin_unlock(&dm_crypt_clients_lock);
  2214. ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
  2215. if (ret < 0)
  2216. goto bad;
  2217. /* Optional parameters need to be read before cipher constructor */
  2218. if (argc > 5) {
  2219. ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
  2220. if (ret)
  2221. goto bad;
  2222. }
  2223. ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
  2224. if (ret < 0)
  2225. goto bad;
  2226. if (crypt_integrity_aead(cc)) {
  2227. cc->dmreq_start = sizeof(struct aead_request);
  2228. cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
  2229. align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
  2230. } else {
  2231. cc->dmreq_start = sizeof(struct skcipher_request);
  2232. cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
  2233. align_mask = crypto_skcipher_alignmask(any_tfm(cc));
  2234. }
  2235. cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
  2236. if (align_mask < CRYPTO_MINALIGN) {
  2237. /* Allocate the padding exactly */
  2238. iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
  2239. & align_mask;
  2240. } else {
  2241. /*
  2242. * If the cipher requires greater alignment than kmalloc
  2243. * alignment, we don't know the exact position of the
  2244. * initialization vector. We must assume worst case.
  2245. */
  2246. iv_size_padding = align_mask;
  2247. }
  2248. /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
  2249. additional_req_size = sizeof(struct dm_crypt_request) +
  2250. iv_size_padding + cc->iv_size +
  2251. cc->iv_size +
  2252. sizeof(uint64_t) +
  2253. sizeof(unsigned int);
  2254. ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
  2255. if (ret) {
  2256. ti->error = "Cannot allocate crypt request mempool";
  2257. goto bad;
  2258. }
  2259. cc->per_bio_data_size = ti->per_io_data_size =
  2260. ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
  2261. ARCH_KMALLOC_MINALIGN);
  2262. ret = mempool_init(&cc->page_pool, BIO_MAX_PAGES, crypt_page_alloc, crypt_page_free, cc);
  2263. if (ret) {
  2264. ti->error = "Cannot allocate page mempool";
  2265. goto bad;
  2266. }
  2267. ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
  2268. if (ret) {
  2269. ti->error = "Cannot allocate crypt bioset";
  2270. goto bad;
  2271. }
  2272. mutex_init(&cc->bio_alloc_lock);
  2273. ret = -EINVAL;
  2274. if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
  2275. (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
  2276. ti->error = "Invalid iv_offset sector";
  2277. goto bad;
  2278. }
  2279. cc->iv_offset = tmpll;
  2280. ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
  2281. if (ret) {
  2282. ti->error = "Device lookup failed";
  2283. goto bad;
  2284. }
  2285. ret = -EINVAL;
  2286. if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1) {
  2287. ti->error = "Invalid device sector";
  2288. goto bad;
  2289. }
  2290. cc->start = tmpll;
  2291. if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
  2292. ret = crypt_integrity_ctr(cc, ti);
  2293. if (ret)
  2294. goto bad;
  2295. cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
  2296. if (!cc->tag_pool_max_sectors)
  2297. cc->tag_pool_max_sectors = 1;
  2298. ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
  2299. cc->tag_pool_max_sectors * cc->on_disk_tag_size);
  2300. if (ret) {
  2301. ti->error = "Cannot allocate integrity tags mempool";
  2302. goto bad;
  2303. }
  2304. cc->tag_pool_max_sectors <<= cc->sector_shift;
  2305. }
  2306. ret = -ENOMEM;
  2307. cc->io_queue = alloc_workqueue("kcryptd_io", WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 1);
  2308. if (!cc->io_queue) {
  2309. ti->error = "Couldn't create kcryptd io queue";
  2310. goto bad;
  2311. }
  2312. if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
  2313. cc->crypt_queue = alloc_workqueue("kcryptd", WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 1);
  2314. else
  2315. cc->crypt_queue = alloc_workqueue("kcryptd",
  2316. WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
  2317. num_online_cpus());
  2318. if (!cc->crypt_queue) {
  2319. ti->error = "Couldn't create kcryptd queue";
  2320. goto bad;
  2321. }
  2322. spin_lock_init(&cc->write_thread_lock);
  2323. cc->write_tree = RB_ROOT;
  2324. cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write");
  2325. if (IS_ERR(cc->write_thread)) {
  2326. ret = PTR_ERR(cc->write_thread);
  2327. cc->write_thread = NULL;
  2328. ti->error = "Couldn't spawn write thread";
  2329. goto bad;
  2330. }
  2331. wake_up_process(cc->write_thread);
  2332. ti->num_flush_bios = 1;
  2333. return 0;
  2334. bad:
  2335. crypt_dtr(ti);
  2336. return ret;
  2337. }
  2338. static int crypt_map(struct dm_target *ti, struct bio *bio)
  2339. {
  2340. struct dm_crypt_io *io;
  2341. struct crypt_config *cc = ti->private;
  2342. /*
  2343. * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
  2344. * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
  2345. * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
  2346. */
  2347. if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
  2348. bio_op(bio) == REQ_OP_DISCARD)) {
  2349. bio_set_dev(bio, cc->dev->bdev);
  2350. if (bio_sectors(bio))
  2351. bio->bi_iter.bi_sector = cc->start +
  2352. dm_target_offset(ti, bio->bi_iter.bi_sector);
  2353. return DM_MAPIO_REMAPPED;
  2354. }
  2355. /*
  2356. * Check if bio is too large, split as needed.
  2357. */
  2358. if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_PAGES << PAGE_SHIFT)) &&
  2359. (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
  2360. dm_accept_partial_bio(bio, ((BIO_MAX_PAGES << PAGE_SHIFT) >> SECTOR_SHIFT));
  2361. /*
  2362. * Ensure that bio is a multiple of internal sector encryption size
  2363. * and is aligned to this size as defined in IO hints.
  2364. */
  2365. if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
  2366. return DM_MAPIO_KILL;
  2367. if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
  2368. return DM_MAPIO_KILL;
  2369. io = dm_per_bio_data(bio, cc->per_bio_data_size);
  2370. crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
  2371. if (cc->on_disk_tag_size) {
  2372. unsigned tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
  2373. if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
  2374. unlikely(!(io->integrity_metadata = kmalloc(tag_len,
  2375. GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
  2376. if (bio_sectors(bio) > cc->tag_pool_max_sectors)
  2377. dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
  2378. io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
  2379. io->integrity_metadata_from_pool = true;
  2380. }
  2381. }
  2382. if (crypt_integrity_aead(cc))
  2383. io->ctx.r.req_aead = (struct aead_request *)(io + 1);
  2384. else
  2385. io->ctx.r.req = (struct skcipher_request *)(io + 1);
  2386. if (bio_data_dir(io->base_bio) == READ) {
  2387. if (kcryptd_io_read(io, GFP_NOWAIT))
  2388. kcryptd_queue_read(io);
  2389. } else
  2390. kcryptd_queue_crypt(io);
  2391. return DM_MAPIO_SUBMITTED;
  2392. }
  2393. static void crypt_status(struct dm_target *ti, status_type_t type,
  2394. unsigned status_flags, char *result, unsigned maxlen)
  2395. {
  2396. struct crypt_config *cc = ti->private;
  2397. unsigned i, sz = 0;
  2398. int num_feature_args = 0;
  2399. switch (type) {
  2400. case STATUSTYPE_INFO:
  2401. result[0] = '\0';
  2402. break;
  2403. case STATUSTYPE_TABLE:
  2404. DMEMIT("%s ", cc->cipher_string);
  2405. if (cc->key_size > 0) {
  2406. if (cc->key_string)
  2407. DMEMIT(":%u:%s", cc->key_size, cc->key_string);
  2408. else
  2409. for (i = 0; i < cc->key_size; i++)
  2410. DMEMIT("%02x", cc->key[i]);
  2411. } else
  2412. DMEMIT("-");
  2413. DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
  2414. cc->dev->name, (unsigned long long)cc->start);
  2415. num_feature_args += !!ti->num_discard_bios;
  2416. num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
  2417. num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
  2418. num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
  2419. num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
  2420. if (cc->on_disk_tag_size)
  2421. num_feature_args++;
  2422. if (num_feature_args) {
  2423. DMEMIT(" %d", num_feature_args);
  2424. if (ti->num_discard_bios)
  2425. DMEMIT(" allow_discards");
  2426. if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
  2427. DMEMIT(" same_cpu_crypt");
  2428. if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
  2429. DMEMIT(" submit_from_crypt_cpus");
  2430. if (cc->on_disk_tag_size)
  2431. DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
  2432. if (cc->sector_size != (1 << SECTOR_SHIFT))
  2433. DMEMIT(" sector_size:%d", cc->sector_size);
  2434. if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
  2435. DMEMIT(" iv_large_sectors");
  2436. }
  2437. break;
  2438. }
  2439. }
  2440. static void crypt_postsuspend(struct dm_target *ti)
  2441. {
  2442. struct crypt_config *cc = ti->private;
  2443. set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  2444. }
  2445. static int crypt_preresume(struct dm_target *ti)
  2446. {
  2447. struct crypt_config *cc = ti->private;
  2448. if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
  2449. DMERR("aborting resume - crypt key is not set.");
  2450. return -EAGAIN;
  2451. }
  2452. return 0;
  2453. }
  2454. static void crypt_resume(struct dm_target *ti)
  2455. {
  2456. struct crypt_config *cc = ti->private;
  2457. clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  2458. }
  2459. /* Message interface
  2460. * key set <key>
  2461. * key wipe
  2462. */
  2463. static int crypt_message(struct dm_target *ti, unsigned argc, char **argv,
  2464. char *result, unsigned maxlen)
  2465. {
  2466. struct crypt_config *cc = ti->private;
  2467. int key_size, ret = -EINVAL;
  2468. if (argc < 2)
  2469. goto error;
  2470. if (!strcasecmp(argv[0], "key")) {
  2471. if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
  2472. DMWARN("not suspended during key manipulation.");
  2473. return -EINVAL;
  2474. }
  2475. if (argc == 3 && !strcasecmp(argv[1], "set")) {
  2476. /* The key size may not be changed. */
  2477. key_size = get_key_size(&argv[2]);
  2478. if (key_size < 0 || cc->key_size != key_size) {
  2479. memset(argv[2], '0', strlen(argv[2]));
  2480. return -EINVAL;
  2481. }
  2482. ret = crypt_set_key(cc, argv[2]);
  2483. if (ret)
  2484. return ret;
  2485. if (cc->iv_gen_ops && cc->iv_gen_ops->init)
  2486. ret = cc->iv_gen_ops->init(cc);
  2487. /* wipe the kernel key payload copy */
  2488. if (cc->key_string)
  2489. memset(cc->key, 0, cc->key_size * sizeof(u8));
  2490. return ret;
  2491. }
  2492. if (argc == 2 && !strcasecmp(argv[1], "wipe")) {
  2493. if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
  2494. ret = cc->iv_gen_ops->wipe(cc);
  2495. if (ret)
  2496. return ret;
  2497. }
  2498. return crypt_wipe_key(cc);
  2499. }
  2500. }
  2501. error:
  2502. DMWARN("unrecognised message received.");
  2503. return -EINVAL;
  2504. }
  2505. static int crypt_iterate_devices(struct dm_target *ti,
  2506. iterate_devices_callout_fn fn, void *data)
  2507. {
  2508. struct crypt_config *cc = ti->private;
  2509. return fn(ti, cc->dev, cc->start, ti->len, data);
  2510. }
  2511. static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
  2512. {
  2513. struct crypt_config *cc = ti->private;
  2514. /*
  2515. * Unfortunate constraint that is required to avoid the potential
  2516. * for exceeding underlying device's max_segments limits -- due to
  2517. * crypt_alloc_buffer() possibly allocating pages for the encryption
  2518. * bio that are not as physically contiguous as the original bio.
  2519. */
  2520. limits->max_segment_size = PAGE_SIZE;
  2521. limits->logical_block_size =
  2522. max_t(unsigned short, limits->logical_block_size, cc->sector_size);
  2523. limits->physical_block_size =
  2524. max_t(unsigned, limits->physical_block_size, cc->sector_size);
  2525. limits->io_min = max_t(unsigned, limits->io_min, cc->sector_size);
  2526. }
  2527. static struct target_type crypt_target = {
  2528. .name = "crypt",
  2529. .version = {1, 18, 1},
  2530. .module = THIS_MODULE,
  2531. .ctr = crypt_ctr,
  2532. .dtr = crypt_dtr,
  2533. .map = crypt_map,
  2534. .status = crypt_status,
  2535. .postsuspend = crypt_postsuspend,
  2536. .preresume = crypt_preresume,
  2537. .resume = crypt_resume,
  2538. .message = crypt_message,
  2539. .iterate_devices = crypt_iterate_devices,
  2540. .io_hints = crypt_io_hints,
  2541. };
  2542. static int __init dm_crypt_init(void)
  2543. {
  2544. int r;
  2545. r = dm_register_target(&crypt_target);
  2546. if (r < 0)
  2547. DMERR("register failed %d", r);
  2548. return r;
  2549. }
  2550. static void __exit dm_crypt_exit(void)
  2551. {
  2552. dm_unregister_target(&crypt_target);
  2553. }
  2554. module_init(dm_crypt_init);
  2555. module_exit(dm_crypt_exit);
  2556. MODULE_AUTHOR("Jana Saout <jana@saout.de>");
  2557. MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
  2558. MODULE_LICENSE("GPL");