dm-crypt.c 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright (C) 2003 Jana Saout <jana@saout.de>
  4. * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
  5. * Copyright (C) 2006-2020 Red Hat, Inc. All rights reserved.
  6. * Copyright (C) 2013-2020 Milan Broz <gmazyland@gmail.com>
  7. *
  8. * This file is released under the GPL.
  9. */
  10. #include <linux/completion.h>
  11. #include <linux/err.h>
  12. #include <linux/module.h>
  13. #include <linux/hex.h>
  14. #include <linux/init.h>
  15. #include <linux/kernel.h>
  16. #include <linux/key.h>
  17. #include <linux/bio.h>
  18. #include <linux/blkdev.h>
  19. #include <linux/blk-integrity.h>
  20. #include <linux/crc32.h>
  21. #include <linux/mempool.h>
  22. #include <linux/slab.h>
  23. #include <linux/crypto.h>
  24. #include <linux/fips.h>
  25. #include <linux/workqueue.h>
  26. #include <linux/kthread.h>
  27. #include <linux/backing-dev.h>
  28. #include <linux/atomic.h>
  29. #include <linux/scatterlist.h>
  30. #include <linux/rbtree.h>
  31. #include <linux/ctype.h>
  32. #include <asm/page.h>
  33. #include <linux/unaligned.h>
  34. #include <crypto/hash.h>
  35. #include <crypto/md5.h>
  36. #include <crypto/skcipher.h>
  37. #include <crypto/aead.h>
  38. #include <crypto/authenc.h>
  39. #include <crypto/utils.h>
  40. #include <linux/rtnetlink.h> /* for struct rtattr and RTA macros only */
  41. #include <linux/key-type.h>
  42. #include <keys/user-type.h>
  43. #include <keys/encrypted-type.h>
  44. #include <keys/trusted-type.h>
  45. #include <linux/device-mapper.h>
  46. #include "dm-audit.h"
  47. #define DM_MSG_PREFIX "crypt"
  48. static DEFINE_IDA(workqueue_ida);
  49. /*
  50. * context holding the current state of a multi-part conversion
  51. */
  52. struct convert_context {
  53. struct completion restart;
  54. struct bio *bio_in;
  55. struct bvec_iter iter_in;
  56. struct bio *bio_out;
  57. struct bvec_iter iter_out;
  58. atomic_t cc_pending;
  59. unsigned int tag_offset;
  60. u64 cc_sector;
  61. union {
  62. struct skcipher_request *req;
  63. struct aead_request *req_aead;
  64. } r;
  65. bool aead_recheck;
  66. bool aead_failed;
  67. };
  68. /*
  69. * per bio private data
  70. */
  71. struct dm_crypt_io {
  72. struct crypt_config *cc;
  73. struct bio *base_bio;
  74. u8 *integrity_metadata;
  75. bool integrity_metadata_from_pool:1;
  76. struct work_struct work;
  77. struct convert_context ctx;
  78. atomic_t io_pending;
  79. blk_status_t error;
  80. sector_t sector;
  81. struct bvec_iter saved_bi_iter;
  82. struct rb_node rb_node;
  83. } CRYPTO_MINALIGN_ATTR;
  84. struct dm_crypt_request {
  85. struct convert_context *ctx;
  86. struct scatterlist sg_in[4];
  87. struct scatterlist sg_out[4];
  88. u64 iv_sector;
  89. };
  90. struct crypt_config;
  91. struct crypt_iv_operations {
  92. int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
  93. const char *opts);
  94. void (*dtr)(struct crypt_config *cc);
  95. int (*init)(struct crypt_config *cc);
  96. int (*wipe)(struct crypt_config *cc);
  97. int (*generator)(struct crypt_config *cc, u8 *iv,
  98. struct dm_crypt_request *dmreq);
  99. int (*post)(struct crypt_config *cc, u8 *iv,
  100. struct dm_crypt_request *dmreq);
  101. };
  102. struct iv_benbi_private {
  103. int shift;
  104. };
  105. #define LMK_SEED_SIZE 64 /* hash + 0 */
  106. struct iv_lmk_private {
  107. u8 *seed;
  108. };
  109. #define TCW_WHITENING_SIZE 16
  110. struct iv_tcw_private {
  111. u8 *iv_seed;
  112. u8 *whitening;
  113. };
  114. #define ELEPHANT_MAX_KEY_SIZE 32
  115. struct iv_elephant_private {
  116. struct crypto_skcipher *tfm;
  117. };
  118. /*
  119. * Crypt: maps a linear range of a block device
  120. * and encrypts / decrypts at the same time.
  121. */
  122. enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
  123. DM_CRYPT_SAME_CPU, DM_CRYPT_HIGH_PRIORITY,
  124. DM_CRYPT_NO_OFFLOAD, DM_CRYPT_NO_READ_WORKQUEUE,
  125. DM_CRYPT_NO_WRITE_WORKQUEUE, DM_CRYPT_WRITE_INLINE };
  126. enum cipher_flags {
  127. CRYPT_MODE_INTEGRITY_AEAD, /* Use authenticated mode for cipher */
  128. CRYPT_IV_LARGE_SECTORS, /* Calculate IV from sector_size, not 512B sectors */
  129. CRYPT_ENCRYPT_PREPROCESS, /* Must preprocess data for encryption (elephant) */
  130. CRYPT_KEY_MAC_SIZE_SET, /* The integrity_key_size option was used */
  131. };
  132. /*
  133. * The fields in here must be read only after initialization.
  134. */
  135. struct crypt_config {
  136. struct dm_dev *dev;
  137. sector_t start;
  138. struct percpu_counter n_allocated_pages;
  139. struct workqueue_struct *io_queue;
  140. struct workqueue_struct *crypt_queue;
  141. spinlock_t write_thread_lock;
  142. struct task_struct *write_thread;
  143. struct rb_root write_tree;
  144. char *cipher_string;
  145. char *cipher_auth;
  146. char *key_string;
  147. const struct crypt_iv_operations *iv_gen_ops;
  148. union {
  149. struct iv_benbi_private benbi;
  150. struct iv_lmk_private lmk;
  151. struct iv_tcw_private tcw;
  152. struct iv_elephant_private elephant;
  153. } iv_gen_private;
  154. u64 iv_offset;
  155. unsigned int iv_size;
  156. unsigned short sector_size;
  157. unsigned char sector_shift;
  158. union {
  159. struct crypto_skcipher **tfms;
  160. struct crypto_aead **tfms_aead;
  161. } cipher_tfm;
  162. unsigned int tfms_count;
  163. int workqueue_id;
  164. unsigned long cipher_flags;
  165. /*
  166. * Layout of each crypto request:
  167. *
  168. * struct skcipher_request
  169. * context
  170. * padding
  171. * struct dm_crypt_request
  172. * padding
  173. * IV
  174. *
  175. * The padding is added so that dm_crypt_request and the IV are
  176. * correctly aligned.
  177. */
  178. unsigned int dmreq_start;
  179. unsigned int per_bio_data_size;
  180. unsigned long flags;
  181. unsigned int key_size;
  182. unsigned int key_parts; /* independent parts in key buffer */
  183. unsigned int key_extra_size; /* additional keys length */
  184. unsigned int key_mac_size; /* MAC key size for authenc(...) */
  185. unsigned int integrity_tag_size;
  186. unsigned int integrity_iv_size;
  187. unsigned int used_tag_size;
  188. unsigned int tuple_size;
  189. /*
  190. * pool for per bio private data, crypto requests,
  191. * encryption requeusts/buffer pages and integrity tags
  192. */
  193. unsigned int tag_pool_max_sectors;
  194. mempool_t tag_pool;
  195. mempool_t req_pool;
  196. mempool_t page_pool;
  197. struct bio_set bs;
  198. struct mutex bio_alloc_lock;
  199. u8 *authenc_key; /* space for keys in authenc() format (if used) */
  200. u8 key[] __counted_by(key_size);
  201. };
  202. #define MIN_IOS 64
  203. #define MAX_TAG_SIZE 480
  204. #define POOL_ENTRY_SIZE 512
  205. static DEFINE_SPINLOCK(dm_crypt_clients_lock);
  206. static unsigned int dm_crypt_clients_n;
  207. static volatile unsigned long dm_crypt_pages_per_client;
  208. #define DM_CRYPT_MEMORY_PERCENT 2
  209. #define DM_CRYPT_MIN_PAGES_PER_CLIENT (BIO_MAX_VECS * 16)
  210. #define DM_CRYPT_DEFAULT_MAX_READ_SIZE 131072
  211. #define DM_CRYPT_DEFAULT_MAX_WRITE_SIZE 131072
  212. static unsigned int max_read_size = 0;
  213. module_param(max_read_size, uint, 0644);
  214. MODULE_PARM_DESC(max_read_size, "Maximum size of a read request");
  215. static unsigned int max_write_size = 0;
  216. module_param(max_write_size, uint, 0644);
  217. MODULE_PARM_DESC(max_write_size, "Maximum size of a write request");
  218. static unsigned get_max_request_sectors(struct dm_target *ti, struct bio *bio, bool no_split)
  219. {
  220. struct crypt_config *cc = ti->private;
  221. unsigned val, sector_align;
  222. bool wrt = op_is_write(bio_op(bio));
  223. if (no_split) {
  224. val = -1;
  225. } else if (wrt) {
  226. val = min_not_zero(READ_ONCE(max_write_size),
  227. DM_CRYPT_DEFAULT_MAX_WRITE_SIZE);
  228. } else {
  229. val = min_not_zero(READ_ONCE(max_read_size),
  230. DM_CRYPT_DEFAULT_MAX_READ_SIZE);
  231. }
  232. if (wrt || cc->used_tag_size)
  233. val = min(val, BIO_MAX_VECS << PAGE_SHIFT);
  234. sector_align = max(bdev_logical_block_size(cc->dev->bdev),
  235. (unsigned)cc->sector_size);
  236. val = round_down(val, sector_align);
  237. if (unlikely(!val))
  238. val = sector_align;
  239. return val >> SECTOR_SHIFT;
  240. }
  241. static void crypt_endio(struct bio *clone);
  242. static void kcryptd_queue_crypt(struct dm_crypt_io *io);
  243. static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
  244. struct scatterlist *sg);
  245. static bool crypt_integrity_aead(struct crypt_config *cc);
  246. /*
  247. * Use this to access cipher attributes that are independent of the key.
  248. */
  249. static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
  250. {
  251. return cc->cipher_tfm.tfms[0];
  252. }
  253. static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
  254. {
  255. return cc->cipher_tfm.tfms_aead[0];
  256. }
  257. /*
  258. * Different IV generation algorithms:
  259. *
  260. * plain: the initial vector is the 32-bit little-endian version of the sector
  261. * number, padded with zeros if necessary.
  262. *
  263. * plain64: the initial vector is the 64-bit little-endian version of the sector
  264. * number, padded with zeros if necessary.
  265. *
  266. * plain64be: the initial vector is the 64-bit big-endian version of the sector
  267. * number, padded with zeros if necessary.
  268. *
  269. * essiv: "encrypted sector|salt initial vector", the sector number is
  270. * encrypted with the bulk cipher using a salt as key. The salt
  271. * should be derived from the bulk cipher's key via hashing.
  272. *
  273. * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
  274. * (needed for LRW-32-AES and possible other narrow block modes)
  275. *
  276. * null: the initial vector is always zero. Provides compatibility with
  277. * obsolete loop_fish2 devices. Do not use for new devices.
  278. *
  279. * lmk: Compatible implementation of the block chaining mode used
  280. * by the Loop-AES block device encryption system
  281. * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
  282. * It operates on full 512 byte sectors and uses CBC
  283. * with an IV derived from the sector number, the data and
  284. * optionally extra IV seed.
  285. * This means that after decryption the first block
  286. * of sector must be tweaked according to decrypted data.
  287. * Loop-AES can use three encryption schemes:
  288. * version 1: is plain aes-cbc mode
  289. * version 2: uses 64 multikey scheme with lmk IV generator
  290. * version 3: the same as version 2 with additional IV seed
  291. * (it uses 65 keys, last key is used as IV seed)
  292. *
  293. * tcw: Compatible implementation of the block chaining mode used
  294. * by the TrueCrypt device encryption system (prior to version 4.1).
  295. * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
  296. * It operates on full 512 byte sectors and uses CBC
  297. * with an IV derived from initial key and the sector number.
  298. * In addition, whitening value is applied on every sector, whitening
  299. * is calculated from initial key, sector number and mixed using CRC32.
  300. * Note that this encryption scheme is vulnerable to watermarking attacks
  301. * and should be used for old compatible containers access only.
  302. *
  303. * eboiv: Encrypted byte-offset IV (used in Bitlocker in CBC mode)
  304. * The IV is encrypted little-endian byte-offset (with the same key
  305. * and cipher as the volume).
  306. *
  307. * elephant: The extended version of eboiv with additional Elephant diffuser
  308. * used with Bitlocker CBC mode.
  309. * This mode was used in older Windows systems
  310. * https://download.microsoft.com/download/0/2/3/0238acaf-d3bf-4a6d-b3d6-0a0be4bbb36e/bitlockercipher200608.pdf
  311. */
  312. static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
  313. struct dm_crypt_request *dmreq)
  314. {
  315. memset(iv, 0, cc->iv_size);
  316. *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
  317. return 0;
  318. }
  319. static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
  320. struct dm_crypt_request *dmreq)
  321. {
  322. memset(iv, 0, cc->iv_size);
  323. *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
  324. return 0;
  325. }
  326. static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
  327. struct dm_crypt_request *dmreq)
  328. {
  329. memset(iv, 0, cc->iv_size);
  330. /* iv_size is at least of size u64; usually it is 16 bytes */
  331. *(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
  332. return 0;
  333. }
  334. static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
  335. struct dm_crypt_request *dmreq)
  336. {
  337. /*
  338. * ESSIV encryption of the IV is now handled by the crypto API,
  339. * so just pass the plain sector number here.
  340. */
  341. memset(iv, 0, cc->iv_size);
  342. *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
  343. return 0;
  344. }
  345. static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
  346. const char *opts)
  347. {
  348. unsigned int bs;
  349. int log;
  350. if (crypt_integrity_aead(cc))
  351. bs = crypto_aead_blocksize(any_tfm_aead(cc));
  352. else
  353. bs = crypto_skcipher_blocksize(any_tfm(cc));
  354. log = ilog2(bs);
  355. /*
  356. * We need to calculate how far we must shift the sector count
  357. * to get the cipher block count, we use this shift in _gen.
  358. */
  359. if (1 << log != bs) {
  360. ti->error = "cypher blocksize is not a power of 2";
  361. return -EINVAL;
  362. }
  363. if (log > 9) {
  364. ti->error = "cypher blocksize is > 512";
  365. return -EINVAL;
  366. }
  367. cc->iv_gen_private.benbi.shift = 9 - log;
  368. return 0;
  369. }
  370. static void crypt_iv_benbi_dtr(struct crypt_config *cc)
  371. {
  372. }
  373. static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
  374. struct dm_crypt_request *dmreq)
  375. {
  376. __be64 val;
  377. memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
  378. val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
  379. put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
  380. return 0;
  381. }
  382. static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
  383. struct dm_crypt_request *dmreq)
  384. {
  385. memset(iv, 0, cc->iv_size);
  386. return 0;
  387. }
  388. static void crypt_iv_lmk_dtr(struct crypt_config *cc)
  389. {
  390. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  391. kfree_sensitive(lmk->seed);
  392. lmk->seed = NULL;
  393. }
  394. static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
  395. const char *opts)
  396. {
  397. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  398. if (cc->sector_size != (1 << SECTOR_SHIFT)) {
  399. ti->error = "Unsupported sector size for LMK";
  400. return -EINVAL;
  401. }
  402. if (fips_enabled) {
  403. ti->error = "LMK support is disabled due to FIPS";
  404. /* ... because it uses MD5. */
  405. return -EINVAL;
  406. }
  407. /* No seed in LMK version 2 */
  408. if (cc->key_parts == cc->tfms_count) {
  409. lmk->seed = NULL;
  410. return 0;
  411. }
  412. lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
  413. if (!lmk->seed) {
  414. ti->error = "Error kmallocing seed storage in LMK";
  415. return -ENOMEM;
  416. }
  417. return 0;
  418. }
  419. static int crypt_iv_lmk_init(struct crypt_config *cc)
  420. {
  421. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  422. int subkey_size = cc->key_size / cc->key_parts;
  423. /* LMK seed is on the position of LMK_KEYS + 1 key */
  424. if (lmk->seed)
  425. memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
  426. MD5_DIGEST_SIZE);
  427. return 0;
  428. }
  429. static int crypt_iv_lmk_wipe(struct crypt_config *cc)
  430. {
  431. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  432. if (lmk->seed)
  433. memset(lmk->seed, 0, LMK_SEED_SIZE);
  434. return 0;
  435. }
  436. static void crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
  437. struct dm_crypt_request *dmreq, u8 *data)
  438. {
  439. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  440. struct md5_ctx ctx;
  441. __le32 buf[4];
  442. md5_init(&ctx);
  443. if (lmk->seed)
  444. md5_update(&ctx, lmk->seed, LMK_SEED_SIZE);
  445. /* Sector is always 512B, block size 16, add data of blocks 1-31 */
  446. md5_update(&ctx, data + 16, 16 * 31);
  447. /* Sector is cropped to 56 bits here */
  448. buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
  449. buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
  450. buf[2] = cpu_to_le32(4024);
  451. buf[3] = 0;
  452. md5_update(&ctx, (u8 *)buf, sizeof(buf));
  453. /* No MD5 padding here */
  454. cpu_to_le32_array(ctx.state.h, ARRAY_SIZE(ctx.state.h));
  455. memcpy(iv, ctx.state.h, cc->iv_size);
  456. }
  457. static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
  458. struct dm_crypt_request *dmreq)
  459. {
  460. struct scatterlist *sg;
  461. u8 *src;
  462. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
  463. sg = crypt_get_sg_data(cc, dmreq->sg_in);
  464. src = kmap_local_page(sg_page(sg));
  465. crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
  466. kunmap_local(src);
  467. } else
  468. memset(iv, 0, cc->iv_size);
  469. return 0;
  470. }
  471. static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
  472. struct dm_crypt_request *dmreq)
  473. {
  474. struct scatterlist *sg;
  475. u8 *dst;
  476. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
  477. return 0;
  478. sg = crypt_get_sg_data(cc, dmreq->sg_out);
  479. dst = kmap_local_page(sg_page(sg));
  480. crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
  481. /* Tweak the first block of plaintext sector */
  482. crypto_xor(dst + sg->offset, iv, cc->iv_size);
  483. kunmap_local(dst);
  484. return 0;
  485. }
  486. static void crypt_iv_tcw_dtr(struct crypt_config *cc)
  487. {
  488. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  489. kfree_sensitive(tcw->iv_seed);
  490. tcw->iv_seed = NULL;
  491. kfree_sensitive(tcw->whitening);
  492. tcw->whitening = NULL;
  493. }
  494. static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
  495. const char *opts)
  496. {
  497. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  498. if (cc->sector_size != (1 << SECTOR_SHIFT)) {
  499. ti->error = "Unsupported sector size for TCW";
  500. return -EINVAL;
  501. }
  502. if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
  503. ti->error = "Wrong key size for TCW";
  504. return -EINVAL;
  505. }
  506. tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
  507. tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
  508. if (!tcw->iv_seed || !tcw->whitening) {
  509. crypt_iv_tcw_dtr(cc);
  510. ti->error = "Error allocating seed storage in TCW";
  511. return -ENOMEM;
  512. }
  513. return 0;
  514. }
  515. static int crypt_iv_tcw_init(struct crypt_config *cc)
  516. {
  517. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  518. int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
  519. memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
  520. memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
  521. TCW_WHITENING_SIZE);
  522. return 0;
  523. }
  524. static int crypt_iv_tcw_wipe(struct crypt_config *cc)
  525. {
  526. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  527. memset(tcw->iv_seed, 0, cc->iv_size);
  528. memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
  529. return 0;
  530. }
  531. static void crypt_iv_tcw_whitening(struct crypt_config *cc,
  532. struct dm_crypt_request *dmreq, u8 *data)
  533. {
  534. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  535. __le64 sector = cpu_to_le64(dmreq->iv_sector);
  536. u8 buf[TCW_WHITENING_SIZE];
  537. int i;
  538. /* xor whitening with sector number */
  539. crypto_xor_cpy(buf, tcw->whitening, (u8 *)&sector, 8);
  540. crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)&sector, 8);
  541. /* calculate crc32 for every 32bit part and xor it */
  542. for (i = 0; i < 4; i++)
  543. put_unaligned_le32(crc32(0, &buf[i * 4], 4), &buf[i * 4]);
  544. crypto_xor(&buf[0], &buf[12], 4);
  545. crypto_xor(&buf[4], &buf[8], 4);
  546. /* apply whitening (8 bytes) to whole sector */
  547. for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
  548. crypto_xor(data + i * 8, buf, 8);
  549. memzero_explicit(buf, sizeof(buf));
  550. }
  551. static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
  552. struct dm_crypt_request *dmreq)
  553. {
  554. struct scatterlist *sg;
  555. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  556. __le64 sector = cpu_to_le64(dmreq->iv_sector);
  557. u8 *src;
  558. /* Remove whitening from ciphertext */
  559. if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
  560. sg = crypt_get_sg_data(cc, dmreq->sg_in);
  561. src = kmap_local_page(sg_page(sg));
  562. crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
  563. kunmap_local(src);
  564. }
  565. /* Calculate IV */
  566. crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)&sector, 8);
  567. if (cc->iv_size > 8)
  568. crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)&sector,
  569. cc->iv_size - 8);
  570. return 0;
  571. }
  572. static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
  573. struct dm_crypt_request *dmreq)
  574. {
  575. struct scatterlist *sg;
  576. u8 *dst;
  577. if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
  578. return 0;
  579. /* Apply whitening on ciphertext */
  580. sg = crypt_get_sg_data(cc, dmreq->sg_out);
  581. dst = kmap_local_page(sg_page(sg));
  582. crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
  583. kunmap_local(dst);
  584. return 0;
  585. }
  586. static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
  587. struct dm_crypt_request *dmreq)
  588. {
  589. /* Used only for writes, there must be an additional space to store IV */
  590. get_random_bytes(iv, cc->iv_size);
  591. return 0;
  592. }
  593. static int crypt_iv_eboiv_ctr(struct crypt_config *cc, struct dm_target *ti,
  594. const char *opts)
  595. {
  596. if (crypt_integrity_aead(cc)) {
  597. ti->error = "AEAD transforms not supported for EBOIV";
  598. return -EINVAL;
  599. }
  600. if (crypto_skcipher_blocksize(any_tfm(cc)) != cc->iv_size) {
  601. ti->error = "Block size of EBOIV cipher does not match IV size of block cipher";
  602. return -EINVAL;
  603. }
  604. return 0;
  605. }
  606. static int crypt_iv_eboiv_gen(struct crypt_config *cc, u8 *iv,
  607. struct dm_crypt_request *dmreq)
  608. {
  609. struct crypto_skcipher *tfm = any_tfm(cc);
  610. struct skcipher_request *req;
  611. struct scatterlist src, dst;
  612. DECLARE_CRYPTO_WAIT(wait);
  613. unsigned int reqsize;
  614. int err;
  615. u8 *buf;
  616. reqsize = sizeof(*req) + crypto_skcipher_reqsize(tfm);
  617. reqsize = ALIGN(reqsize, __alignof__(__le64));
  618. req = kmalloc(reqsize + cc->iv_size, GFP_NOIO);
  619. if (!req)
  620. return -ENOMEM;
  621. skcipher_request_set_tfm(req, tfm);
  622. buf = (u8 *)req + reqsize;
  623. memset(buf, 0, cc->iv_size);
  624. *(__le64 *)buf = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
  625. sg_init_one(&src, page_address(ZERO_PAGE(0)), cc->iv_size);
  626. sg_init_one(&dst, iv, cc->iv_size);
  627. skcipher_request_set_crypt(req, &src, &dst, cc->iv_size, buf);
  628. skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
  629. err = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
  630. kfree_sensitive(req);
  631. return err;
  632. }
  633. static void crypt_iv_elephant_dtr(struct crypt_config *cc)
  634. {
  635. struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
  636. crypto_free_skcipher(elephant->tfm);
  637. elephant->tfm = NULL;
  638. }
  639. static int crypt_iv_elephant_ctr(struct crypt_config *cc, struct dm_target *ti,
  640. const char *opts)
  641. {
  642. struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
  643. int r;
  644. elephant->tfm = crypto_alloc_skcipher("ecb(aes)", 0,
  645. CRYPTO_ALG_ALLOCATES_MEMORY);
  646. if (IS_ERR(elephant->tfm)) {
  647. r = PTR_ERR(elephant->tfm);
  648. elephant->tfm = NULL;
  649. return r;
  650. }
  651. r = crypt_iv_eboiv_ctr(cc, ti, NULL);
  652. if (r)
  653. crypt_iv_elephant_dtr(cc);
  654. return r;
  655. }
  656. static void diffuser_disk_to_cpu(u32 *d, size_t n)
  657. {
  658. #ifndef __LITTLE_ENDIAN
  659. int i;
  660. for (i = 0; i < n; i++)
  661. d[i] = le32_to_cpu((__le32)d[i]);
  662. #endif
  663. }
  664. static void diffuser_cpu_to_disk(__le32 *d, size_t n)
  665. {
  666. #ifndef __LITTLE_ENDIAN
  667. int i;
  668. for (i = 0; i < n; i++)
  669. d[i] = cpu_to_le32((u32)d[i]);
  670. #endif
  671. }
  672. static void diffuser_a_decrypt(u32 *d, size_t n)
  673. {
  674. int i, i1, i2, i3;
  675. for (i = 0; i < 5; i++) {
  676. i1 = 0;
  677. i2 = n - 2;
  678. i3 = n - 5;
  679. while (i1 < (n - 1)) {
  680. d[i1] += d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
  681. i1++; i2++; i3++;
  682. if (i3 >= n)
  683. i3 -= n;
  684. d[i1] += d[i2] ^ d[i3];
  685. i1++; i2++; i3++;
  686. if (i2 >= n)
  687. i2 -= n;
  688. d[i1] += d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
  689. i1++; i2++; i3++;
  690. d[i1] += d[i2] ^ d[i3];
  691. i1++; i2++; i3++;
  692. }
  693. }
  694. }
  695. static void diffuser_a_encrypt(u32 *d, size_t n)
  696. {
  697. int i, i1, i2, i3;
  698. for (i = 0; i < 5; i++) {
  699. i1 = n - 1;
  700. i2 = n - 2 - 1;
  701. i3 = n - 5 - 1;
  702. while (i1 > 0) {
  703. d[i1] -= d[i2] ^ d[i3];
  704. i1--; i2--; i3--;
  705. d[i1] -= d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
  706. i1--; i2--; i3--;
  707. if (i2 < 0)
  708. i2 += n;
  709. d[i1] -= d[i2] ^ d[i3];
  710. i1--; i2--; i3--;
  711. if (i3 < 0)
  712. i3 += n;
  713. d[i1] -= d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
  714. i1--; i2--; i3--;
  715. }
  716. }
  717. }
  718. static void diffuser_b_decrypt(u32 *d, size_t n)
  719. {
  720. int i, i1, i2, i3;
  721. for (i = 0; i < 3; i++) {
  722. i1 = 0;
  723. i2 = 2;
  724. i3 = 5;
  725. while (i1 < (n - 1)) {
  726. d[i1] += d[i2] ^ d[i3];
  727. i1++; i2++; i3++;
  728. d[i1] += d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
  729. i1++; i2++; i3++;
  730. if (i2 >= n)
  731. i2 -= n;
  732. d[i1] += d[i2] ^ d[i3];
  733. i1++; i2++; i3++;
  734. if (i3 >= n)
  735. i3 -= n;
  736. d[i1] += d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
  737. i1++; i2++; i3++;
  738. }
  739. }
  740. }
  741. static void diffuser_b_encrypt(u32 *d, size_t n)
  742. {
  743. int i, i1, i2, i3;
  744. for (i = 0; i < 3; i++) {
  745. i1 = n - 1;
  746. i2 = 2 - 1;
  747. i3 = 5 - 1;
  748. while (i1 > 0) {
  749. d[i1] -= d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
  750. i1--; i2--; i3--;
  751. if (i3 < 0)
  752. i3 += n;
  753. d[i1] -= d[i2] ^ d[i3];
  754. i1--; i2--; i3--;
  755. if (i2 < 0)
  756. i2 += n;
  757. d[i1] -= d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
  758. i1--; i2--; i3--;
  759. d[i1] -= d[i2] ^ d[i3];
  760. i1--; i2--; i3--;
  761. }
  762. }
  763. }
  764. static int crypt_iv_elephant(struct crypt_config *cc, struct dm_crypt_request *dmreq)
  765. {
  766. struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
  767. u8 *es, *ks, *data, *data2, *data_offset;
  768. struct skcipher_request *req;
  769. struct scatterlist *sg, *sg2, src, dst;
  770. DECLARE_CRYPTO_WAIT(wait);
  771. int i, r;
  772. req = skcipher_request_alloc(elephant->tfm, GFP_NOIO);
  773. es = kzalloc(16, GFP_NOIO); /* Key for AES */
  774. ks = kzalloc(32, GFP_NOIO); /* Elephant sector key */
  775. if (!req || !es || !ks) {
  776. r = -ENOMEM;
  777. goto out;
  778. }
  779. *(__le64 *)es = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
  780. /* E(Ks, e(s)) */
  781. sg_init_one(&src, es, 16);
  782. sg_init_one(&dst, ks, 16);
  783. skcipher_request_set_crypt(req, &src, &dst, 16, NULL);
  784. skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
  785. r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
  786. if (r)
  787. goto out;
  788. /* E(Ks, e'(s)) */
  789. es[15] = 0x80;
  790. sg_init_one(&dst, &ks[16], 16);
  791. r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
  792. if (r)
  793. goto out;
  794. sg = crypt_get_sg_data(cc, dmreq->sg_out);
  795. data = kmap_local_page(sg_page(sg));
  796. data_offset = data + sg->offset;
  797. /* Cannot modify original bio, copy to sg_out and apply Elephant to it */
  798. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
  799. sg2 = crypt_get_sg_data(cc, dmreq->sg_in);
  800. data2 = kmap_local_page(sg_page(sg2));
  801. memcpy(data_offset, data2 + sg2->offset, cc->sector_size);
  802. kunmap_local(data2);
  803. }
  804. if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
  805. diffuser_disk_to_cpu((u32 *)data_offset, cc->sector_size / sizeof(u32));
  806. diffuser_b_decrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
  807. diffuser_a_decrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
  808. diffuser_cpu_to_disk((__le32 *)data_offset, cc->sector_size / sizeof(u32));
  809. }
  810. for (i = 0; i < (cc->sector_size / 32); i++)
  811. crypto_xor(data_offset + i * 32, ks, 32);
  812. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
  813. diffuser_disk_to_cpu((u32 *)data_offset, cc->sector_size / sizeof(u32));
  814. diffuser_a_encrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
  815. diffuser_b_encrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
  816. diffuser_cpu_to_disk((__le32 *)data_offset, cc->sector_size / sizeof(u32));
  817. }
  818. kunmap_local(data);
  819. out:
  820. kfree_sensitive(ks);
  821. kfree_sensitive(es);
  822. skcipher_request_free(req);
  823. return r;
  824. }
  825. static int crypt_iv_elephant_gen(struct crypt_config *cc, u8 *iv,
  826. struct dm_crypt_request *dmreq)
  827. {
  828. int r;
  829. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
  830. r = crypt_iv_elephant(cc, dmreq);
  831. if (r)
  832. return r;
  833. }
  834. return crypt_iv_eboiv_gen(cc, iv, dmreq);
  835. }
  836. static int crypt_iv_elephant_post(struct crypt_config *cc, u8 *iv,
  837. struct dm_crypt_request *dmreq)
  838. {
  839. if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
  840. return crypt_iv_elephant(cc, dmreq);
  841. return 0;
  842. }
  843. static int crypt_iv_elephant_init(struct crypt_config *cc)
  844. {
  845. struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
  846. int key_offset = cc->key_size - cc->key_extra_size;
  847. return crypto_skcipher_setkey(elephant->tfm, &cc->key[key_offset], cc->key_extra_size);
  848. }
  849. static int crypt_iv_elephant_wipe(struct crypt_config *cc)
  850. {
  851. struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
  852. u8 key[ELEPHANT_MAX_KEY_SIZE];
  853. memset(key, 0, cc->key_extra_size);
  854. return crypto_skcipher_setkey(elephant->tfm, key, cc->key_extra_size);
  855. }
  856. static const struct crypt_iv_operations crypt_iv_plain_ops = {
  857. .generator = crypt_iv_plain_gen
  858. };
  859. static const struct crypt_iv_operations crypt_iv_plain64_ops = {
  860. .generator = crypt_iv_plain64_gen
  861. };
  862. static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
  863. .generator = crypt_iv_plain64be_gen
  864. };
  865. static const struct crypt_iv_operations crypt_iv_essiv_ops = {
  866. .generator = crypt_iv_essiv_gen
  867. };
  868. static const struct crypt_iv_operations crypt_iv_benbi_ops = {
  869. .ctr = crypt_iv_benbi_ctr,
  870. .dtr = crypt_iv_benbi_dtr,
  871. .generator = crypt_iv_benbi_gen
  872. };
  873. static const struct crypt_iv_operations crypt_iv_null_ops = {
  874. .generator = crypt_iv_null_gen
  875. };
  876. static const struct crypt_iv_operations crypt_iv_lmk_ops = {
  877. .ctr = crypt_iv_lmk_ctr,
  878. .dtr = crypt_iv_lmk_dtr,
  879. .init = crypt_iv_lmk_init,
  880. .wipe = crypt_iv_lmk_wipe,
  881. .generator = crypt_iv_lmk_gen,
  882. .post = crypt_iv_lmk_post
  883. };
  884. static const struct crypt_iv_operations crypt_iv_tcw_ops = {
  885. .ctr = crypt_iv_tcw_ctr,
  886. .dtr = crypt_iv_tcw_dtr,
  887. .init = crypt_iv_tcw_init,
  888. .wipe = crypt_iv_tcw_wipe,
  889. .generator = crypt_iv_tcw_gen,
  890. .post = crypt_iv_tcw_post
  891. };
  892. static const struct crypt_iv_operations crypt_iv_random_ops = {
  893. .generator = crypt_iv_random_gen
  894. };
  895. static const struct crypt_iv_operations crypt_iv_eboiv_ops = {
  896. .ctr = crypt_iv_eboiv_ctr,
  897. .generator = crypt_iv_eboiv_gen
  898. };
  899. static const struct crypt_iv_operations crypt_iv_elephant_ops = {
  900. .ctr = crypt_iv_elephant_ctr,
  901. .dtr = crypt_iv_elephant_dtr,
  902. .init = crypt_iv_elephant_init,
  903. .wipe = crypt_iv_elephant_wipe,
  904. .generator = crypt_iv_elephant_gen,
  905. .post = crypt_iv_elephant_post
  906. };
  907. /*
  908. * Integrity extensions
  909. */
  910. static bool crypt_integrity_aead(struct crypt_config *cc)
  911. {
  912. return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
  913. }
  914. static bool crypt_integrity_hmac(struct crypt_config *cc)
  915. {
  916. return crypt_integrity_aead(cc) && cc->key_mac_size;
  917. }
  918. /* Get sg containing data */
  919. static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
  920. struct scatterlist *sg)
  921. {
  922. if (unlikely(crypt_integrity_aead(cc)))
  923. return &sg[2];
  924. return sg;
  925. }
  926. static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
  927. {
  928. struct bio_integrity_payload *bip;
  929. unsigned int tag_len;
  930. int ret;
  931. if (!bio_sectors(bio) || !io->cc->tuple_size)
  932. return 0;
  933. bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
  934. if (IS_ERR(bip))
  935. return PTR_ERR(bip);
  936. tag_len = io->cc->tuple_size * (bio_sectors(bio) >> io->cc->sector_shift);
  937. bip->bip_iter.bi_sector = bio->bi_iter.bi_sector;
  938. ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
  939. tag_len, offset_in_page(io->integrity_metadata));
  940. if (unlikely(ret != tag_len))
  941. return -ENOMEM;
  942. return 0;
  943. }
  944. static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
  945. {
  946. #ifdef CONFIG_BLK_DEV_INTEGRITY
  947. struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
  948. struct mapped_device *md = dm_table_get_md(ti->table);
  949. /* We require an underlying device with non-PI metadata */
  950. if (!bi || bi->csum_type != BLK_INTEGRITY_CSUM_NONE) {
  951. ti->error = "Integrity profile not supported.";
  952. return -EINVAL;
  953. }
  954. if (bi->metadata_size < cc->used_tag_size) {
  955. ti->error = "Integrity profile tag size mismatch.";
  956. return -EINVAL;
  957. }
  958. cc->tuple_size = bi->metadata_size;
  959. if (1 << bi->interval_exp != cc->sector_size) {
  960. ti->error = "Integrity profile sector size mismatch.";
  961. return -EINVAL;
  962. }
  963. if (crypt_integrity_aead(cc)) {
  964. cc->integrity_tag_size = cc->used_tag_size - cc->integrity_iv_size;
  965. DMDEBUG("%s: Integrity AEAD, tag size %u, IV size %u.", dm_device_name(md),
  966. cc->integrity_tag_size, cc->integrity_iv_size);
  967. if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
  968. ti->error = "Integrity AEAD auth tag size is not supported.";
  969. return -EINVAL;
  970. }
  971. } else if (cc->integrity_iv_size)
  972. DMDEBUG("%s: Additional per-sector space %u bytes for IV.", dm_device_name(md),
  973. cc->integrity_iv_size);
  974. if ((cc->integrity_tag_size + cc->integrity_iv_size) > cc->tuple_size) {
  975. ti->error = "Not enough space for integrity tag in the profile.";
  976. return -EINVAL;
  977. }
  978. return 0;
  979. #else
  980. ti->error = "Integrity profile not supported.";
  981. return -EINVAL;
  982. #endif
  983. }
  984. static void crypt_convert_init(struct crypt_config *cc,
  985. struct convert_context *ctx,
  986. struct bio *bio_out, struct bio *bio_in,
  987. sector_t sector)
  988. {
  989. ctx->bio_in = bio_in;
  990. ctx->bio_out = bio_out;
  991. if (bio_in)
  992. ctx->iter_in = bio_in->bi_iter;
  993. if (bio_out)
  994. ctx->iter_out = bio_out->bi_iter;
  995. ctx->cc_sector = sector + cc->iv_offset;
  996. ctx->tag_offset = 0;
  997. init_completion(&ctx->restart);
  998. }
  999. static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
  1000. void *req)
  1001. {
  1002. return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
  1003. }
  1004. static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
  1005. {
  1006. return (void *)((char *)dmreq - cc->dmreq_start);
  1007. }
  1008. static u8 *iv_of_dmreq(struct crypt_config *cc,
  1009. struct dm_crypt_request *dmreq)
  1010. {
  1011. if (crypt_integrity_aead(cc))
  1012. return (u8 *)ALIGN((unsigned long)(dmreq + 1),
  1013. crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
  1014. else
  1015. return (u8 *)ALIGN((unsigned long)(dmreq + 1),
  1016. crypto_skcipher_alignmask(any_tfm(cc)) + 1);
  1017. }
  1018. static u8 *org_iv_of_dmreq(struct crypt_config *cc,
  1019. struct dm_crypt_request *dmreq)
  1020. {
  1021. return iv_of_dmreq(cc, dmreq) + cc->iv_size;
  1022. }
  1023. static __le64 *org_sector_of_dmreq(struct crypt_config *cc,
  1024. struct dm_crypt_request *dmreq)
  1025. {
  1026. u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
  1027. return (__le64 *) ptr;
  1028. }
  1029. static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
  1030. struct dm_crypt_request *dmreq)
  1031. {
  1032. u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
  1033. cc->iv_size + sizeof(uint64_t);
  1034. return (unsigned int *)ptr;
  1035. }
  1036. static void *tag_from_dmreq(struct crypt_config *cc,
  1037. struct dm_crypt_request *dmreq)
  1038. {
  1039. struct convert_context *ctx = dmreq->ctx;
  1040. struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
  1041. return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
  1042. cc->tuple_size];
  1043. }
  1044. static void *iv_tag_from_dmreq(struct crypt_config *cc,
  1045. struct dm_crypt_request *dmreq)
  1046. {
  1047. return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
  1048. }
  1049. static int crypt_convert_block_aead(struct crypt_config *cc,
  1050. struct convert_context *ctx,
  1051. struct aead_request *req,
  1052. unsigned int tag_offset)
  1053. {
  1054. struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
  1055. struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
  1056. struct dm_crypt_request *dmreq;
  1057. u8 *iv, *org_iv, *tag_iv, *tag;
  1058. __le64 *sector;
  1059. int r = 0;
  1060. BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
  1061. /* Reject unexpected unaligned bio. */
  1062. if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
  1063. return -EIO;
  1064. dmreq = dmreq_of_req(cc, req);
  1065. dmreq->iv_sector = ctx->cc_sector;
  1066. if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
  1067. dmreq->iv_sector >>= cc->sector_shift;
  1068. dmreq->ctx = ctx;
  1069. *org_tag_of_dmreq(cc, dmreq) = tag_offset;
  1070. sector = org_sector_of_dmreq(cc, dmreq);
  1071. *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
  1072. iv = iv_of_dmreq(cc, dmreq);
  1073. org_iv = org_iv_of_dmreq(cc, dmreq);
  1074. tag = tag_from_dmreq(cc, dmreq);
  1075. tag_iv = iv_tag_from_dmreq(cc, dmreq);
  1076. /* AEAD request:
  1077. * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
  1078. * | (authenticated) | (auth+encryption) | |
  1079. * | sector_LE | IV | sector in/out | tag in/out |
  1080. */
  1081. sg_init_table(dmreq->sg_in, 4);
  1082. sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
  1083. sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
  1084. sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
  1085. sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
  1086. sg_init_table(dmreq->sg_out, 4);
  1087. sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
  1088. sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
  1089. sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
  1090. sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
  1091. if (cc->iv_gen_ops) {
  1092. /* For READs use IV stored in integrity metadata */
  1093. if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
  1094. memcpy(org_iv, tag_iv, cc->iv_size);
  1095. } else {
  1096. r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
  1097. if (r < 0)
  1098. return r;
  1099. /* Store generated IV in integrity metadata */
  1100. if (cc->integrity_iv_size)
  1101. memcpy(tag_iv, org_iv, cc->iv_size);
  1102. }
  1103. /* Working copy of IV, to be modified in crypto API */
  1104. memcpy(iv, org_iv, cc->iv_size);
  1105. }
  1106. aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
  1107. if (bio_data_dir(ctx->bio_in) == WRITE) {
  1108. aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
  1109. cc->sector_size, iv);
  1110. r = crypto_aead_encrypt(req);
  1111. if (cc->integrity_tag_size + cc->integrity_iv_size != cc->tuple_size)
  1112. memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
  1113. cc->tuple_size - (cc->integrity_tag_size + cc->integrity_iv_size));
  1114. } else {
  1115. aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
  1116. cc->sector_size + cc->integrity_tag_size, iv);
  1117. r = crypto_aead_decrypt(req);
  1118. }
  1119. if (r == -EBADMSG) {
  1120. sector_t s = le64_to_cpu(*sector);
  1121. ctx->aead_failed = true;
  1122. if (ctx->aead_recheck) {
  1123. DMERR_LIMIT("%pg: INTEGRITY AEAD ERROR, sector %llu",
  1124. ctx->bio_in->bi_bdev, s);
  1125. dm_audit_log_bio(DM_MSG_PREFIX, "integrity-aead",
  1126. ctx->bio_in, s, 0);
  1127. }
  1128. }
  1129. if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
  1130. r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
  1131. bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
  1132. bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
  1133. return r;
  1134. }
  1135. static int crypt_convert_block_skcipher(struct crypt_config *cc,
  1136. struct convert_context *ctx,
  1137. struct skcipher_request *req,
  1138. unsigned int tag_offset)
  1139. {
  1140. struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
  1141. struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
  1142. struct scatterlist *sg_in, *sg_out;
  1143. struct dm_crypt_request *dmreq;
  1144. u8 *iv, *org_iv, *tag_iv;
  1145. __le64 *sector;
  1146. int r = 0;
  1147. /* Reject unexpected unaligned bio. */
  1148. if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
  1149. return -EIO;
  1150. dmreq = dmreq_of_req(cc, req);
  1151. dmreq->iv_sector = ctx->cc_sector;
  1152. if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
  1153. dmreq->iv_sector >>= cc->sector_shift;
  1154. dmreq->ctx = ctx;
  1155. *org_tag_of_dmreq(cc, dmreq) = tag_offset;
  1156. iv = iv_of_dmreq(cc, dmreq);
  1157. org_iv = org_iv_of_dmreq(cc, dmreq);
  1158. tag_iv = iv_tag_from_dmreq(cc, dmreq);
  1159. sector = org_sector_of_dmreq(cc, dmreq);
  1160. *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
  1161. /* For skcipher we use only the first sg item */
  1162. sg_in = &dmreq->sg_in[0];
  1163. sg_out = &dmreq->sg_out[0];
  1164. sg_init_table(sg_in, 1);
  1165. sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
  1166. sg_init_table(sg_out, 1);
  1167. sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
  1168. if (cc->iv_gen_ops) {
  1169. /* For READs use IV stored in integrity metadata */
  1170. if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
  1171. memcpy(org_iv, tag_iv, cc->integrity_iv_size);
  1172. } else {
  1173. r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
  1174. if (r < 0)
  1175. return r;
  1176. /* Data can be already preprocessed in generator */
  1177. if (test_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags))
  1178. sg_in = sg_out;
  1179. /* Store generated IV in integrity metadata */
  1180. if (cc->integrity_iv_size)
  1181. memcpy(tag_iv, org_iv, cc->integrity_iv_size);
  1182. }
  1183. /* Working copy of IV, to be modified in crypto API */
  1184. memcpy(iv, org_iv, cc->iv_size);
  1185. }
  1186. skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
  1187. if (bio_data_dir(ctx->bio_in) == WRITE)
  1188. r = crypto_skcipher_encrypt(req);
  1189. else
  1190. r = crypto_skcipher_decrypt(req);
  1191. if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
  1192. r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
  1193. bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
  1194. bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
  1195. return r;
  1196. }
  1197. static void kcryptd_async_done(void *async_req, int error);
  1198. static int crypt_alloc_req_skcipher(struct crypt_config *cc,
  1199. struct convert_context *ctx)
  1200. {
  1201. unsigned int key_index = ctx->cc_sector & (cc->tfms_count - 1);
  1202. if (!ctx->r.req) {
  1203. ctx->r.req = mempool_alloc(&cc->req_pool, in_interrupt() ? GFP_ATOMIC : GFP_NOIO);
  1204. if (!ctx->r.req)
  1205. return -ENOMEM;
  1206. }
  1207. skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
  1208. /*
  1209. * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
  1210. * requests if driver request queue is full.
  1211. */
  1212. skcipher_request_set_callback(ctx->r.req,
  1213. CRYPTO_TFM_REQ_MAY_BACKLOG,
  1214. kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
  1215. return 0;
  1216. }
  1217. static int crypt_alloc_req_aead(struct crypt_config *cc,
  1218. struct convert_context *ctx)
  1219. {
  1220. if (!ctx->r.req_aead) {
  1221. ctx->r.req_aead = mempool_alloc(&cc->req_pool, in_interrupt() ? GFP_ATOMIC : GFP_NOIO);
  1222. if (!ctx->r.req_aead)
  1223. return -ENOMEM;
  1224. }
  1225. aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
  1226. /*
  1227. * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
  1228. * requests if driver request queue is full.
  1229. */
  1230. aead_request_set_callback(ctx->r.req_aead,
  1231. CRYPTO_TFM_REQ_MAY_BACKLOG,
  1232. kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
  1233. return 0;
  1234. }
  1235. static int crypt_alloc_req(struct crypt_config *cc,
  1236. struct convert_context *ctx)
  1237. {
  1238. if (crypt_integrity_aead(cc))
  1239. return crypt_alloc_req_aead(cc, ctx);
  1240. else
  1241. return crypt_alloc_req_skcipher(cc, ctx);
  1242. }
  1243. static void crypt_free_req_skcipher(struct crypt_config *cc,
  1244. struct skcipher_request *req, struct bio *base_bio)
  1245. {
  1246. struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
  1247. if ((struct skcipher_request *)(io + 1) != req)
  1248. mempool_free(req, &cc->req_pool);
  1249. }
  1250. static void crypt_free_req_aead(struct crypt_config *cc,
  1251. struct aead_request *req, struct bio *base_bio)
  1252. {
  1253. struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
  1254. if ((struct aead_request *)(io + 1) != req)
  1255. mempool_free(req, &cc->req_pool);
  1256. }
  1257. static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
  1258. {
  1259. if (crypt_integrity_aead(cc))
  1260. crypt_free_req_aead(cc, req, base_bio);
  1261. else
  1262. crypt_free_req_skcipher(cc, req, base_bio);
  1263. }
  1264. /*
  1265. * Encrypt / decrypt data from one bio to another one (can be the same one)
  1266. */
  1267. static blk_status_t crypt_convert(struct crypt_config *cc,
  1268. struct convert_context *ctx, bool atomic, bool reset_pending)
  1269. {
  1270. unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
  1271. int r;
  1272. /*
  1273. * if reset_pending is set we are dealing with the bio for the first time,
  1274. * else we're continuing to work on the previous bio, so don't mess with
  1275. * the cc_pending counter
  1276. */
  1277. if (reset_pending)
  1278. atomic_set(&ctx->cc_pending, 1);
  1279. while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
  1280. r = crypt_alloc_req(cc, ctx);
  1281. if (r) {
  1282. complete(&ctx->restart);
  1283. return BLK_STS_DEV_RESOURCE;
  1284. }
  1285. atomic_inc(&ctx->cc_pending);
  1286. if (crypt_integrity_aead(cc))
  1287. r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, ctx->tag_offset);
  1288. else
  1289. r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, ctx->tag_offset);
  1290. switch (r) {
  1291. /*
  1292. * The request was queued by a crypto driver
  1293. * but the driver request queue is full, let's wait.
  1294. */
  1295. case -EBUSY:
  1296. if (in_interrupt()) {
  1297. if (try_wait_for_completion(&ctx->restart)) {
  1298. /*
  1299. * we don't have to block to wait for completion,
  1300. * so proceed
  1301. */
  1302. } else {
  1303. /*
  1304. * we can't wait for completion without blocking
  1305. * exit and continue processing in a workqueue
  1306. */
  1307. ctx->r.req = NULL;
  1308. ctx->tag_offset++;
  1309. ctx->cc_sector += sector_step;
  1310. return BLK_STS_DEV_RESOURCE;
  1311. }
  1312. } else {
  1313. wait_for_completion(&ctx->restart);
  1314. }
  1315. reinit_completion(&ctx->restart);
  1316. fallthrough;
  1317. /*
  1318. * The request is queued and processed asynchronously,
  1319. * completion function kcryptd_async_done() will be called.
  1320. */
  1321. case -EINPROGRESS:
  1322. ctx->r.req = NULL;
  1323. ctx->tag_offset++;
  1324. ctx->cc_sector += sector_step;
  1325. continue;
  1326. /*
  1327. * The request was already processed (synchronously).
  1328. */
  1329. case 0:
  1330. atomic_dec(&ctx->cc_pending);
  1331. ctx->cc_sector += sector_step;
  1332. ctx->tag_offset++;
  1333. if (!atomic)
  1334. cond_resched();
  1335. continue;
  1336. /*
  1337. * There was a data integrity error.
  1338. */
  1339. case -EBADMSG:
  1340. atomic_dec(&ctx->cc_pending);
  1341. return BLK_STS_PROTECTION;
  1342. /*
  1343. * There was an error while processing the request.
  1344. */
  1345. default:
  1346. atomic_dec(&ctx->cc_pending);
  1347. return BLK_STS_IOERR;
  1348. }
  1349. }
  1350. return 0;
  1351. }
  1352. static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
  1353. /*
  1354. * Generate a new unfragmented bio with the given size
  1355. * This should never violate the device limitations (but if it did then block
  1356. * core should split the bio as needed).
  1357. *
  1358. * This function may be called concurrently. If we allocate from the mempool
  1359. * concurrently, there is a possibility of deadlock. For example, if we have
  1360. * mempool of 256 pages, two processes, each wanting 256, pages allocate from
  1361. * the mempool concurrently, it may deadlock in a situation where both processes
  1362. * have allocated 128 pages and the mempool is exhausted.
  1363. *
  1364. * In order to avoid this scenario we allocate the pages under a mutex.
  1365. *
  1366. * In order to not degrade performance with excessive locking, we try
  1367. * non-blocking allocations without a mutex first but on failure we fallback
  1368. * to blocking allocations with a mutex.
  1369. *
  1370. * In order to reduce allocation overhead, we try to allocate compound pages in
  1371. * the first pass. If they are not available, we fall back to the mempool.
  1372. */
  1373. static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned int size)
  1374. {
  1375. struct crypt_config *cc = io->cc;
  1376. struct bio *clone;
  1377. unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
  1378. gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
  1379. unsigned int remaining_size;
  1380. unsigned int order = MAX_PAGE_ORDER;
  1381. retry:
  1382. if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
  1383. mutex_lock(&cc->bio_alloc_lock);
  1384. clone = bio_alloc_bioset(cc->dev->bdev, nr_iovecs, io->base_bio->bi_opf,
  1385. GFP_NOIO, &cc->bs);
  1386. clone->bi_private = io;
  1387. clone->bi_end_io = crypt_endio;
  1388. clone->bi_ioprio = io->base_bio->bi_ioprio;
  1389. clone->bi_iter.bi_sector = cc->start + io->sector;
  1390. remaining_size = size;
  1391. while (remaining_size) {
  1392. struct page *pages;
  1393. unsigned size_to_add;
  1394. unsigned remaining_order = __fls((remaining_size + PAGE_SIZE - 1) >> PAGE_SHIFT);
  1395. order = min(order, remaining_order);
  1396. while (order > 0) {
  1397. if (unlikely(percpu_counter_read_positive(&cc->n_allocated_pages) +
  1398. (1 << order) > dm_crypt_pages_per_client))
  1399. goto decrease_order;
  1400. pages = alloc_pages(gfp_mask
  1401. | __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN | __GFP_COMP,
  1402. order);
  1403. if (likely(pages != NULL)) {
  1404. percpu_counter_add(&cc->n_allocated_pages, 1 << order);
  1405. goto have_pages;
  1406. }
  1407. decrease_order:
  1408. order--;
  1409. }
  1410. pages = mempool_alloc(&cc->page_pool, gfp_mask);
  1411. if (!pages) {
  1412. crypt_free_buffer_pages(cc, clone);
  1413. bio_put(clone);
  1414. gfp_mask |= __GFP_DIRECT_RECLAIM;
  1415. order = 0;
  1416. goto retry;
  1417. }
  1418. have_pages:
  1419. size_to_add = min((unsigned)PAGE_SIZE << order, remaining_size);
  1420. __bio_add_page(clone, pages, size_to_add, 0);
  1421. remaining_size -= size_to_add;
  1422. }
  1423. /* Allocate space for integrity tags */
  1424. if (dm_crypt_integrity_io_alloc(io, clone)) {
  1425. crypt_free_buffer_pages(cc, clone);
  1426. bio_put(clone);
  1427. clone = NULL;
  1428. }
  1429. if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
  1430. mutex_unlock(&cc->bio_alloc_lock);
  1431. return clone;
  1432. }
  1433. static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
  1434. {
  1435. struct folio_iter fi;
  1436. if (clone->bi_vcnt > 0) { /* bio_for_each_folio_all crashes with an empty bio */
  1437. bio_for_each_folio_all(fi, clone) {
  1438. if (folio_test_large(fi.folio)) {
  1439. percpu_counter_sub(&cc->n_allocated_pages,
  1440. folio_nr_pages(fi.folio));
  1441. folio_put(fi.folio);
  1442. } else {
  1443. mempool_free(&fi.folio->page, &cc->page_pool);
  1444. }
  1445. }
  1446. }
  1447. }
  1448. static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
  1449. struct bio *bio, sector_t sector)
  1450. {
  1451. io->cc = cc;
  1452. io->base_bio = bio;
  1453. io->sector = sector;
  1454. io->error = 0;
  1455. io->ctx.aead_recheck = false;
  1456. io->ctx.aead_failed = false;
  1457. io->ctx.r.req = NULL;
  1458. io->integrity_metadata = NULL;
  1459. io->integrity_metadata_from_pool = false;
  1460. atomic_set(&io->io_pending, 0);
  1461. }
  1462. static void crypt_inc_pending(struct dm_crypt_io *io)
  1463. {
  1464. atomic_inc(&io->io_pending);
  1465. }
  1466. static void kcryptd_queue_read(struct dm_crypt_io *io);
  1467. /*
  1468. * One of the bios was finished. Check for completion of
  1469. * the whole request and correctly clean up the buffer.
  1470. */
  1471. static void crypt_dec_pending(struct dm_crypt_io *io)
  1472. {
  1473. struct crypt_config *cc = io->cc;
  1474. struct bio *base_bio = io->base_bio;
  1475. blk_status_t error = io->error;
  1476. if (!atomic_dec_and_test(&io->io_pending))
  1477. return;
  1478. if (likely(!io->ctx.aead_recheck) && unlikely(io->ctx.aead_failed) &&
  1479. cc->used_tag_size && bio_data_dir(base_bio) == READ) {
  1480. io->ctx.aead_recheck = true;
  1481. io->ctx.aead_failed = false;
  1482. io->error = 0;
  1483. kcryptd_queue_read(io);
  1484. return;
  1485. }
  1486. if (io->ctx.r.req)
  1487. crypt_free_req(cc, io->ctx.r.req, base_bio);
  1488. if (unlikely(io->integrity_metadata_from_pool))
  1489. mempool_free(io->integrity_metadata, &io->cc->tag_pool);
  1490. else
  1491. kfree(io->integrity_metadata);
  1492. base_bio->bi_status = error;
  1493. bio_endio(base_bio);
  1494. }
  1495. /*
  1496. * kcryptd/kcryptd_io:
  1497. *
  1498. * Needed because it would be very unwise to do decryption in an
  1499. * interrupt context.
  1500. *
  1501. * kcryptd performs the actual encryption or decryption.
  1502. *
  1503. * kcryptd_io performs the IO submission.
  1504. *
  1505. * They must be separated as otherwise the final stages could be
  1506. * starved by new requests which can block in the first stages due
  1507. * to memory allocation.
  1508. *
  1509. * The work is done per CPU global for all dm-crypt instances.
  1510. * They should not depend on each other and do not block.
  1511. */
  1512. static void crypt_endio(struct bio *clone)
  1513. {
  1514. struct dm_crypt_io *io = clone->bi_private;
  1515. struct crypt_config *cc = io->cc;
  1516. unsigned int rw = bio_data_dir(clone);
  1517. blk_status_t error = clone->bi_status;
  1518. if (io->ctx.aead_recheck && !error) {
  1519. kcryptd_queue_crypt(io);
  1520. return;
  1521. }
  1522. /*
  1523. * free the processed pages
  1524. */
  1525. if (rw == WRITE || io->ctx.aead_recheck)
  1526. crypt_free_buffer_pages(cc, clone);
  1527. bio_put(clone);
  1528. if (rw == READ && !error) {
  1529. kcryptd_queue_crypt(io);
  1530. return;
  1531. }
  1532. if (unlikely(error))
  1533. io->error = error;
  1534. crypt_dec_pending(io);
  1535. }
  1536. #define CRYPT_MAP_READ_GFP GFP_NOWAIT
  1537. static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
  1538. {
  1539. struct crypt_config *cc = io->cc;
  1540. struct bio *clone;
  1541. if (io->ctx.aead_recheck) {
  1542. if (!(gfp & __GFP_DIRECT_RECLAIM))
  1543. return 1;
  1544. crypt_inc_pending(io);
  1545. clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
  1546. if (unlikely(!clone)) {
  1547. crypt_dec_pending(io);
  1548. return 1;
  1549. }
  1550. crypt_convert_init(cc, &io->ctx, clone, clone, io->sector);
  1551. io->saved_bi_iter = clone->bi_iter;
  1552. dm_submit_bio_remap(io->base_bio, clone);
  1553. return 0;
  1554. }
  1555. /*
  1556. * We need the original biovec array in order to decrypt the whole bio
  1557. * data *afterwards* -- thanks to immutable biovecs we don't need to
  1558. * worry about the block layer modifying the biovec array; so leverage
  1559. * bio_alloc_clone().
  1560. */
  1561. clone = bio_alloc_clone(cc->dev->bdev, io->base_bio, gfp, &cc->bs);
  1562. if (!clone)
  1563. return 1;
  1564. clone->bi_iter.bi_sector = cc->start + io->sector;
  1565. clone->bi_private = io;
  1566. clone->bi_end_io = crypt_endio;
  1567. crypt_inc_pending(io);
  1568. if (dm_crypt_integrity_io_alloc(io, clone)) {
  1569. crypt_dec_pending(io);
  1570. bio_put(clone);
  1571. return 1;
  1572. }
  1573. dm_submit_bio_remap(io->base_bio, clone);
  1574. return 0;
  1575. }
  1576. static void kcryptd_io_read_work(struct work_struct *work)
  1577. {
  1578. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  1579. crypt_inc_pending(io);
  1580. if (kcryptd_io_read(io, GFP_NOIO))
  1581. io->error = BLK_STS_RESOURCE;
  1582. crypt_dec_pending(io);
  1583. }
  1584. static void kcryptd_queue_read(struct dm_crypt_io *io)
  1585. {
  1586. struct crypt_config *cc = io->cc;
  1587. INIT_WORK(&io->work, kcryptd_io_read_work);
  1588. queue_work(cc->io_queue, &io->work);
  1589. }
  1590. static void kcryptd_io_write(struct dm_crypt_io *io)
  1591. {
  1592. struct bio *clone = io->ctx.bio_out;
  1593. dm_submit_bio_remap(io->base_bio, clone);
  1594. }
  1595. #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
  1596. static int dmcrypt_write(void *data)
  1597. {
  1598. struct crypt_config *cc = data;
  1599. struct dm_crypt_io *io;
  1600. while (1) {
  1601. struct rb_root write_tree;
  1602. struct blk_plug plug;
  1603. spin_lock_irq(&cc->write_thread_lock);
  1604. continue_locked:
  1605. if (!RB_EMPTY_ROOT(&cc->write_tree))
  1606. goto pop_from_list;
  1607. set_current_state(TASK_INTERRUPTIBLE);
  1608. spin_unlock_irq(&cc->write_thread_lock);
  1609. if (unlikely(kthread_should_stop())) {
  1610. set_current_state(TASK_RUNNING);
  1611. break;
  1612. }
  1613. schedule();
  1614. spin_lock_irq(&cc->write_thread_lock);
  1615. goto continue_locked;
  1616. pop_from_list:
  1617. write_tree = cc->write_tree;
  1618. cc->write_tree = RB_ROOT;
  1619. spin_unlock_irq(&cc->write_thread_lock);
  1620. BUG_ON(rb_parent(write_tree.rb_node));
  1621. /*
  1622. * Note: we cannot walk the tree here with rb_next because
  1623. * the structures may be freed when kcryptd_io_write is called.
  1624. */
  1625. blk_start_plug(&plug);
  1626. do {
  1627. io = crypt_io_from_node(rb_first(&write_tree));
  1628. rb_erase(&io->rb_node, &write_tree);
  1629. kcryptd_io_write(io);
  1630. cond_resched();
  1631. } while (!RB_EMPTY_ROOT(&write_tree));
  1632. blk_finish_plug(&plug);
  1633. }
  1634. return 0;
  1635. }
  1636. static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
  1637. {
  1638. struct bio *clone = io->ctx.bio_out;
  1639. struct crypt_config *cc = io->cc;
  1640. unsigned long flags;
  1641. sector_t sector;
  1642. struct rb_node **rbp, *parent;
  1643. if (unlikely(io->error)) {
  1644. crypt_free_buffer_pages(cc, clone);
  1645. bio_put(clone);
  1646. crypt_dec_pending(io);
  1647. return;
  1648. }
  1649. /* crypt_convert should have filled the clone bio */
  1650. BUG_ON(io->ctx.iter_out.bi_size);
  1651. if ((likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) ||
  1652. test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags)) {
  1653. dm_submit_bio_remap(io->base_bio, clone);
  1654. return;
  1655. }
  1656. spin_lock_irqsave(&cc->write_thread_lock, flags);
  1657. if (RB_EMPTY_ROOT(&cc->write_tree))
  1658. wake_up_process(cc->write_thread);
  1659. rbp = &cc->write_tree.rb_node;
  1660. parent = NULL;
  1661. sector = io->sector;
  1662. while (*rbp) {
  1663. parent = *rbp;
  1664. if (sector < crypt_io_from_node(parent)->sector)
  1665. rbp = &(*rbp)->rb_left;
  1666. else
  1667. rbp = &(*rbp)->rb_right;
  1668. }
  1669. rb_link_node(&io->rb_node, parent, rbp);
  1670. rb_insert_color(&io->rb_node, &cc->write_tree);
  1671. spin_unlock_irqrestore(&cc->write_thread_lock, flags);
  1672. }
  1673. static bool kcryptd_crypt_write_inline(struct crypt_config *cc,
  1674. struct convert_context *ctx)
  1675. {
  1676. if (!test_bit(DM_CRYPT_WRITE_INLINE, &cc->flags))
  1677. return false;
  1678. /*
  1679. * Note: zone append writes (REQ_OP_ZONE_APPEND) do not have ordering
  1680. * constraints so they do not need to be issued inline by
  1681. * kcryptd_crypt_write_convert().
  1682. */
  1683. switch (bio_op(ctx->bio_in)) {
  1684. case REQ_OP_WRITE:
  1685. case REQ_OP_WRITE_ZEROES:
  1686. return true;
  1687. default:
  1688. return false;
  1689. }
  1690. }
  1691. static void kcryptd_crypt_write_continue(struct work_struct *work)
  1692. {
  1693. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  1694. struct crypt_config *cc = io->cc;
  1695. struct convert_context *ctx = &io->ctx;
  1696. int crypt_finished;
  1697. blk_status_t r;
  1698. wait_for_completion(&ctx->restart);
  1699. reinit_completion(&ctx->restart);
  1700. r = crypt_convert(cc, &io->ctx, false, false);
  1701. if (r)
  1702. io->error = r;
  1703. crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
  1704. if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
  1705. /* Wait for completion signaled by kcryptd_async_done() */
  1706. wait_for_completion(&ctx->restart);
  1707. crypt_finished = 1;
  1708. }
  1709. /* Encryption was already finished, submit io now */
  1710. if (crypt_finished)
  1711. kcryptd_crypt_write_io_submit(io, 0);
  1712. crypt_dec_pending(io);
  1713. }
  1714. static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
  1715. {
  1716. struct crypt_config *cc = io->cc;
  1717. struct convert_context *ctx = &io->ctx;
  1718. struct bio *clone;
  1719. int crypt_finished;
  1720. blk_status_t r;
  1721. /*
  1722. * Prevent io from disappearing until this function completes.
  1723. */
  1724. crypt_inc_pending(io);
  1725. crypt_convert_init(cc, ctx, NULL, io->base_bio, io->sector);
  1726. clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
  1727. if (unlikely(!clone)) {
  1728. io->error = BLK_STS_IOERR;
  1729. goto dec;
  1730. }
  1731. io->ctx.bio_out = clone;
  1732. io->ctx.iter_out = clone->bi_iter;
  1733. if (crypt_integrity_aead(cc)) {
  1734. bio_copy_data(clone, io->base_bio);
  1735. io->ctx.bio_in = clone;
  1736. io->ctx.iter_in = clone->bi_iter;
  1737. }
  1738. crypt_inc_pending(io);
  1739. r = crypt_convert(cc, ctx,
  1740. test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags), true);
  1741. /*
  1742. * Crypto API backlogged the request, because its queue was full
  1743. * and we're in softirq context, so continue from a workqueue
  1744. * (TODO: is it actually possible to be in softirq in the write path?)
  1745. */
  1746. if (r == BLK_STS_DEV_RESOURCE) {
  1747. INIT_WORK(&io->work, kcryptd_crypt_write_continue);
  1748. queue_work(cc->crypt_queue, &io->work);
  1749. return;
  1750. }
  1751. if (r)
  1752. io->error = r;
  1753. crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
  1754. if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
  1755. /* Wait for completion signaled by kcryptd_async_done() */
  1756. wait_for_completion(&ctx->restart);
  1757. crypt_finished = 1;
  1758. }
  1759. /* Encryption was already finished, submit io now */
  1760. if (crypt_finished)
  1761. kcryptd_crypt_write_io_submit(io, 0);
  1762. dec:
  1763. crypt_dec_pending(io);
  1764. }
  1765. static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
  1766. {
  1767. if (io->ctx.aead_recheck) {
  1768. if (!io->error) {
  1769. io->ctx.bio_in->bi_iter = io->saved_bi_iter;
  1770. bio_copy_data(io->base_bio, io->ctx.bio_in);
  1771. }
  1772. crypt_free_buffer_pages(io->cc, io->ctx.bio_in);
  1773. bio_put(io->ctx.bio_in);
  1774. }
  1775. crypt_dec_pending(io);
  1776. }
  1777. static void kcryptd_crypt_read_continue(struct work_struct *work)
  1778. {
  1779. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  1780. struct crypt_config *cc = io->cc;
  1781. blk_status_t r;
  1782. wait_for_completion(&io->ctx.restart);
  1783. reinit_completion(&io->ctx.restart);
  1784. r = crypt_convert(cc, &io->ctx, false, false);
  1785. if (r)
  1786. io->error = r;
  1787. if (atomic_dec_and_test(&io->ctx.cc_pending))
  1788. kcryptd_crypt_read_done(io);
  1789. crypt_dec_pending(io);
  1790. }
  1791. static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
  1792. {
  1793. struct crypt_config *cc = io->cc;
  1794. blk_status_t r;
  1795. crypt_inc_pending(io);
  1796. if (io->ctx.aead_recheck) {
  1797. r = crypt_convert(cc, &io->ctx,
  1798. test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags), true);
  1799. } else {
  1800. crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
  1801. io->sector);
  1802. r = crypt_convert(cc, &io->ctx,
  1803. test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags), true);
  1804. }
  1805. /*
  1806. * Crypto API backlogged the request, because its queue was full
  1807. * and we're in softirq context, so continue from a workqueue
  1808. */
  1809. if (r == BLK_STS_DEV_RESOURCE) {
  1810. INIT_WORK(&io->work, kcryptd_crypt_read_continue);
  1811. queue_work(cc->crypt_queue, &io->work);
  1812. return;
  1813. }
  1814. if (r)
  1815. io->error = r;
  1816. if (atomic_dec_and_test(&io->ctx.cc_pending))
  1817. kcryptd_crypt_read_done(io);
  1818. crypt_dec_pending(io);
  1819. }
  1820. static void kcryptd_async_done(void *data, int error)
  1821. {
  1822. struct dm_crypt_request *dmreq = data;
  1823. struct convert_context *ctx = dmreq->ctx;
  1824. struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
  1825. struct crypt_config *cc = io->cc;
  1826. /*
  1827. * A request from crypto driver backlog is going to be processed now,
  1828. * finish the completion and continue in crypt_convert().
  1829. * (Callback will be called for the second time for this request.)
  1830. */
  1831. if (error == -EINPROGRESS) {
  1832. complete(&ctx->restart);
  1833. return;
  1834. }
  1835. if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
  1836. error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
  1837. if (error == -EBADMSG) {
  1838. sector_t s = le64_to_cpu(*org_sector_of_dmreq(cc, dmreq));
  1839. ctx->aead_failed = true;
  1840. if (ctx->aead_recheck) {
  1841. DMERR_LIMIT("%pg: INTEGRITY AEAD ERROR, sector %llu",
  1842. ctx->bio_in->bi_bdev, s);
  1843. dm_audit_log_bio(DM_MSG_PREFIX, "integrity-aead",
  1844. ctx->bio_in, s, 0);
  1845. }
  1846. io->error = BLK_STS_PROTECTION;
  1847. } else if (error < 0)
  1848. io->error = BLK_STS_IOERR;
  1849. crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
  1850. if (!atomic_dec_and_test(&ctx->cc_pending))
  1851. return;
  1852. /*
  1853. * The request is fully completed: for inline writes, let
  1854. * kcryptd_crypt_write_convert() do the IO submission.
  1855. */
  1856. if (bio_data_dir(io->base_bio) == READ) {
  1857. kcryptd_crypt_read_done(io);
  1858. return;
  1859. }
  1860. if (kcryptd_crypt_write_inline(cc, ctx)) {
  1861. complete(&ctx->restart);
  1862. return;
  1863. }
  1864. kcryptd_crypt_write_io_submit(io, 1);
  1865. }
  1866. static void kcryptd_crypt(struct work_struct *work)
  1867. {
  1868. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  1869. if (bio_data_dir(io->base_bio) == READ)
  1870. kcryptd_crypt_read_convert(io);
  1871. else
  1872. kcryptd_crypt_write_convert(io);
  1873. }
  1874. static void kcryptd_queue_crypt(struct dm_crypt_io *io)
  1875. {
  1876. struct crypt_config *cc = io->cc;
  1877. if ((bio_data_dir(io->base_bio) == READ && test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags)) ||
  1878. (bio_data_dir(io->base_bio) == WRITE && test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))) {
  1879. /*
  1880. * in_hardirq(): Crypto API's skcipher_walk_first() refuses to work in hard IRQ context.
  1881. * irqs_disabled(): the kernel may run some IO completion from the idle thread, but
  1882. * it is being executed with irqs disabled.
  1883. */
  1884. if (in_hardirq() || irqs_disabled()) {
  1885. INIT_WORK(&io->work, kcryptd_crypt);
  1886. queue_work(system_bh_wq, &io->work);
  1887. return;
  1888. } else {
  1889. kcryptd_crypt(&io->work);
  1890. return;
  1891. }
  1892. }
  1893. INIT_WORK(&io->work, kcryptd_crypt);
  1894. queue_work(cc->crypt_queue, &io->work);
  1895. }
  1896. static void crypt_free_tfms_aead(struct crypt_config *cc)
  1897. {
  1898. if (!cc->cipher_tfm.tfms_aead)
  1899. return;
  1900. if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
  1901. crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
  1902. cc->cipher_tfm.tfms_aead[0] = NULL;
  1903. }
  1904. kfree(cc->cipher_tfm.tfms_aead);
  1905. cc->cipher_tfm.tfms_aead = NULL;
  1906. }
  1907. static void crypt_free_tfms_skcipher(struct crypt_config *cc)
  1908. {
  1909. unsigned int i;
  1910. if (!cc->cipher_tfm.tfms)
  1911. return;
  1912. for (i = 0; i < cc->tfms_count; i++)
  1913. if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
  1914. crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
  1915. cc->cipher_tfm.tfms[i] = NULL;
  1916. }
  1917. kfree(cc->cipher_tfm.tfms);
  1918. cc->cipher_tfm.tfms = NULL;
  1919. }
  1920. static void crypt_free_tfms(struct crypt_config *cc)
  1921. {
  1922. if (crypt_integrity_aead(cc))
  1923. crypt_free_tfms_aead(cc);
  1924. else
  1925. crypt_free_tfms_skcipher(cc);
  1926. }
  1927. static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
  1928. {
  1929. unsigned int i;
  1930. int err;
  1931. cc->cipher_tfm.tfms = kzalloc_objs(struct crypto_skcipher *,
  1932. cc->tfms_count);
  1933. if (!cc->cipher_tfm.tfms)
  1934. return -ENOMEM;
  1935. for (i = 0; i < cc->tfms_count; i++) {
  1936. cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0,
  1937. CRYPTO_ALG_ALLOCATES_MEMORY);
  1938. if (IS_ERR(cc->cipher_tfm.tfms[i])) {
  1939. err = PTR_ERR(cc->cipher_tfm.tfms[i]);
  1940. crypt_free_tfms(cc);
  1941. return err;
  1942. }
  1943. }
  1944. /*
  1945. * dm-crypt performance can vary greatly depending on which crypto
  1946. * algorithm implementation is used. Help people debug performance
  1947. * problems by logging the ->cra_driver_name.
  1948. */
  1949. DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
  1950. crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
  1951. return 0;
  1952. }
  1953. static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
  1954. {
  1955. int err;
  1956. cc->cipher_tfm.tfms = kmalloc_obj(struct crypto_skcipher *);
  1957. if (!cc->cipher_tfm.tfms)
  1958. return -ENOMEM;
  1959. cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0,
  1960. CRYPTO_ALG_ALLOCATES_MEMORY);
  1961. if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
  1962. err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
  1963. crypt_free_tfms(cc);
  1964. return err;
  1965. }
  1966. DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
  1967. crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
  1968. return 0;
  1969. }
  1970. static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
  1971. {
  1972. if (crypt_integrity_aead(cc))
  1973. return crypt_alloc_tfms_aead(cc, ciphermode);
  1974. else
  1975. return crypt_alloc_tfms_skcipher(cc, ciphermode);
  1976. }
  1977. static unsigned int crypt_subkey_size(struct crypt_config *cc)
  1978. {
  1979. return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
  1980. }
  1981. static unsigned int crypt_authenckey_size(struct crypt_config *cc)
  1982. {
  1983. return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
  1984. }
  1985. /*
  1986. * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
  1987. * the key must be for some reason in special format.
  1988. * This funcion converts cc->key to this special format.
  1989. */
  1990. static void crypt_copy_authenckey(char *p, const void *key,
  1991. unsigned int enckeylen, unsigned int authkeylen)
  1992. {
  1993. struct crypto_authenc_key_param *param;
  1994. struct rtattr *rta;
  1995. rta = (struct rtattr *)p;
  1996. param = RTA_DATA(rta);
  1997. param->enckeylen = cpu_to_be32(enckeylen);
  1998. rta->rta_len = RTA_LENGTH(sizeof(*param));
  1999. rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
  2000. p += RTA_SPACE(sizeof(*param));
  2001. memcpy(p, key + enckeylen, authkeylen);
  2002. p += authkeylen;
  2003. memcpy(p, key, enckeylen);
  2004. }
  2005. static int crypt_setkey(struct crypt_config *cc)
  2006. {
  2007. unsigned int subkey_size;
  2008. int err = 0, i, r;
  2009. /* Ignore extra keys (which are used for IV etc) */
  2010. subkey_size = crypt_subkey_size(cc);
  2011. if (crypt_integrity_hmac(cc)) {
  2012. if (subkey_size < cc->key_mac_size)
  2013. return -EINVAL;
  2014. crypt_copy_authenckey(cc->authenc_key, cc->key,
  2015. subkey_size - cc->key_mac_size,
  2016. cc->key_mac_size);
  2017. }
  2018. for (i = 0; i < cc->tfms_count; i++) {
  2019. if (crypt_integrity_hmac(cc))
  2020. r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
  2021. cc->authenc_key, crypt_authenckey_size(cc));
  2022. else if (crypt_integrity_aead(cc))
  2023. r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
  2024. cc->key + (i * subkey_size),
  2025. subkey_size);
  2026. else
  2027. r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
  2028. cc->key + (i * subkey_size),
  2029. subkey_size);
  2030. if (r)
  2031. err = r;
  2032. }
  2033. if (crypt_integrity_hmac(cc))
  2034. memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
  2035. return err;
  2036. }
  2037. #ifdef CONFIG_KEYS
  2038. static bool contains_whitespace(const char *str)
  2039. {
  2040. while (*str)
  2041. if (isspace(*str++))
  2042. return true;
  2043. return false;
  2044. }
  2045. static int set_key_user(struct crypt_config *cc, struct key *key)
  2046. {
  2047. const struct user_key_payload *ukp;
  2048. ukp = user_key_payload_locked(key);
  2049. if (!ukp)
  2050. return -EKEYREVOKED;
  2051. if (cc->key_size != ukp->datalen)
  2052. return -EINVAL;
  2053. memcpy(cc->key, ukp->data, cc->key_size);
  2054. return 0;
  2055. }
  2056. static int set_key_encrypted(struct crypt_config *cc, struct key *key)
  2057. {
  2058. const struct encrypted_key_payload *ekp;
  2059. ekp = key->payload.data[0];
  2060. if (!ekp)
  2061. return -EKEYREVOKED;
  2062. if (cc->key_size != ekp->decrypted_datalen)
  2063. return -EINVAL;
  2064. memcpy(cc->key, ekp->decrypted_data, cc->key_size);
  2065. return 0;
  2066. }
  2067. static int set_key_trusted(struct crypt_config *cc, struct key *key)
  2068. {
  2069. const struct trusted_key_payload *tkp;
  2070. tkp = key->payload.data[0];
  2071. if (!tkp)
  2072. return -EKEYREVOKED;
  2073. if (cc->key_size != tkp->key_len)
  2074. return -EINVAL;
  2075. memcpy(cc->key, tkp->key, cc->key_size);
  2076. return 0;
  2077. }
  2078. static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
  2079. {
  2080. char *new_key_string, *key_desc;
  2081. int ret;
  2082. struct key_type *type;
  2083. struct key *key;
  2084. int (*set_key)(struct crypt_config *cc, struct key *key);
  2085. /*
  2086. * Reject key_string with whitespace. dm core currently lacks code for
  2087. * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
  2088. */
  2089. if (contains_whitespace(key_string)) {
  2090. DMERR("whitespace chars not allowed in key string");
  2091. return -EINVAL;
  2092. }
  2093. /* look for next ':' separating key_type from key_description */
  2094. key_desc = strchr(key_string, ':');
  2095. if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
  2096. return -EINVAL;
  2097. if (!strncmp(key_string, "logon:", key_desc - key_string + 1)) {
  2098. type = &key_type_logon;
  2099. set_key = set_key_user;
  2100. } else if (!strncmp(key_string, "user:", key_desc - key_string + 1)) {
  2101. type = &key_type_user;
  2102. set_key = set_key_user;
  2103. } else if (IS_ENABLED(CONFIG_ENCRYPTED_KEYS) &&
  2104. !strncmp(key_string, "encrypted:", key_desc - key_string + 1)) {
  2105. type = &key_type_encrypted;
  2106. set_key = set_key_encrypted;
  2107. } else if (IS_ENABLED(CONFIG_TRUSTED_KEYS) &&
  2108. !strncmp(key_string, "trusted:", key_desc - key_string + 1)) {
  2109. type = &key_type_trusted;
  2110. set_key = set_key_trusted;
  2111. } else {
  2112. return -EINVAL;
  2113. }
  2114. new_key_string = kstrdup(key_string, GFP_KERNEL);
  2115. if (!new_key_string)
  2116. return -ENOMEM;
  2117. key = request_key(type, key_desc + 1, NULL);
  2118. if (IS_ERR(key)) {
  2119. ret = PTR_ERR(key);
  2120. goto free_new_key_string;
  2121. }
  2122. down_read(&key->sem);
  2123. ret = set_key(cc, key);
  2124. up_read(&key->sem);
  2125. key_put(key);
  2126. if (ret < 0)
  2127. goto free_new_key_string;
  2128. /* clear the flag since following operations may invalidate previously valid key */
  2129. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  2130. ret = crypt_setkey(cc);
  2131. if (ret)
  2132. goto free_new_key_string;
  2133. set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  2134. kfree_sensitive(cc->key_string);
  2135. cc->key_string = new_key_string;
  2136. return 0;
  2137. free_new_key_string:
  2138. kfree_sensitive(new_key_string);
  2139. return ret;
  2140. }
  2141. static int get_key_size(char **key_string)
  2142. {
  2143. char *colon, dummy;
  2144. int ret;
  2145. if (*key_string[0] != ':')
  2146. return strlen(*key_string) >> 1;
  2147. /* look for next ':' in key string */
  2148. colon = strpbrk(*key_string + 1, ":");
  2149. if (!colon)
  2150. return -EINVAL;
  2151. if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
  2152. return -EINVAL;
  2153. *key_string = colon;
  2154. /* remaining key string should be :<logon|user>:<key_desc> */
  2155. return ret;
  2156. }
  2157. #else
  2158. static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
  2159. {
  2160. return -EINVAL;
  2161. }
  2162. static int get_key_size(char **key_string)
  2163. {
  2164. return (*key_string[0] == ':') ? -EINVAL : (int)(strlen(*key_string) >> 1);
  2165. }
  2166. #endif /* CONFIG_KEYS */
  2167. static int crypt_set_key(struct crypt_config *cc, char *key)
  2168. {
  2169. int r = -EINVAL;
  2170. int key_string_len = strlen(key);
  2171. /* Hyphen (which gives a key_size of zero) means there is no key. */
  2172. if (!cc->key_size && strcmp(key, "-"))
  2173. goto out;
  2174. /* ':' means the key is in kernel keyring, short-circuit normal key processing */
  2175. if (key[0] == ':') {
  2176. r = crypt_set_keyring_key(cc, key + 1);
  2177. goto out;
  2178. }
  2179. /* clear the flag since following operations may invalidate previously valid key */
  2180. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  2181. /* wipe references to any kernel keyring key */
  2182. kfree_sensitive(cc->key_string);
  2183. cc->key_string = NULL;
  2184. /* Decode key from its hex representation. */
  2185. if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
  2186. goto out;
  2187. r = crypt_setkey(cc);
  2188. if (!r)
  2189. set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  2190. out:
  2191. /* Hex key string not needed after here, so wipe it. */
  2192. memset(key, '0', key_string_len);
  2193. return r;
  2194. }
  2195. static int crypt_wipe_key(struct crypt_config *cc)
  2196. {
  2197. int r;
  2198. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  2199. get_random_bytes(&cc->key, cc->key_size);
  2200. /* Wipe IV private keys */
  2201. if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
  2202. r = cc->iv_gen_ops->wipe(cc);
  2203. if (r)
  2204. return r;
  2205. }
  2206. kfree_sensitive(cc->key_string);
  2207. cc->key_string = NULL;
  2208. r = crypt_setkey(cc);
  2209. memset(&cc->key, 0, cc->key_size * sizeof(u8));
  2210. return r;
  2211. }
  2212. static void crypt_calculate_pages_per_client(void)
  2213. {
  2214. unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
  2215. if (!dm_crypt_clients_n)
  2216. return;
  2217. pages /= dm_crypt_clients_n;
  2218. if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
  2219. pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
  2220. dm_crypt_pages_per_client = pages;
  2221. }
  2222. static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
  2223. {
  2224. struct crypt_config *cc = pool_data;
  2225. struct page *page;
  2226. /*
  2227. * Note, percpu_counter_read_positive() may over (and under) estimate
  2228. * the current usage by at most (batch - 1) * num_online_cpus() pages,
  2229. * but avoids potential spinlock contention of an exact result.
  2230. */
  2231. if (unlikely(percpu_counter_read_positive(&cc->n_allocated_pages) >= dm_crypt_pages_per_client) &&
  2232. likely(gfp_mask & __GFP_NORETRY))
  2233. return NULL;
  2234. page = alloc_page(gfp_mask);
  2235. if (likely(page != NULL))
  2236. percpu_counter_add(&cc->n_allocated_pages, 1);
  2237. return page;
  2238. }
  2239. static void crypt_page_free(void *page, void *pool_data)
  2240. {
  2241. struct crypt_config *cc = pool_data;
  2242. __free_page(page);
  2243. percpu_counter_sub(&cc->n_allocated_pages, 1);
  2244. }
  2245. static void crypt_dtr(struct dm_target *ti)
  2246. {
  2247. struct crypt_config *cc = ti->private;
  2248. ti->private = NULL;
  2249. if (!cc)
  2250. return;
  2251. if (cc->write_thread)
  2252. kthread_stop(cc->write_thread);
  2253. if (cc->io_queue)
  2254. destroy_workqueue(cc->io_queue);
  2255. if (cc->crypt_queue)
  2256. destroy_workqueue(cc->crypt_queue);
  2257. if (cc->workqueue_id)
  2258. ida_free(&workqueue_ida, cc->workqueue_id);
  2259. crypt_free_tfms(cc);
  2260. bioset_exit(&cc->bs);
  2261. mempool_exit(&cc->page_pool);
  2262. mempool_exit(&cc->req_pool);
  2263. mempool_exit(&cc->tag_pool);
  2264. WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
  2265. percpu_counter_destroy(&cc->n_allocated_pages);
  2266. if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
  2267. cc->iv_gen_ops->dtr(cc);
  2268. if (cc->dev)
  2269. dm_put_device(ti, cc->dev);
  2270. kfree_sensitive(cc->cipher_string);
  2271. kfree_sensitive(cc->key_string);
  2272. kfree_sensitive(cc->cipher_auth);
  2273. kfree_sensitive(cc->authenc_key);
  2274. mutex_destroy(&cc->bio_alloc_lock);
  2275. /* Must zero key material before freeing */
  2276. kfree_sensitive(cc);
  2277. spin_lock(&dm_crypt_clients_lock);
  2278. WARN_ON(!dm_crypt_clients_n);
  2279. dm_crypt_clients_n--;
  2280. crypt_calculate_pages_per_client();
  2281. spin_unlock(&dm_crypt_clients_lock);
  2282. dm_audit_log_dtr(DM_MSG_PREFIX, ti, 1);
  2283. }
  2284. static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
  2285. {
  2286. struct crypt_config *cc = ti->private;
  2287. if (crypt_integrity_aead(cc))
  2288. cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
  2289. else
  2290. cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
  2291. if (cc->iv_size)
  2292. /* at least a 64 bit sector number should fit in our buffer */
  2293. cc->iv_size = max(cc->iv_size,
  2294. (unsigned int)(sizeof(u64) / sizeof(u8)));
  2295. else if (ivmode) {
  2296. DMWARN("Selected cipher does not support IVs");
  2297. ivmode = NULL;
  2298. }
  2299. /* Choose ivmode, see comments at iv code. */
  2300. if (ivmode == NULL)
  2301. cc->iv_gen_ops = NULL;
  2302. else if (strcmp(ivmode, "plain") == 0)
  2303. cc->iv_gen_ops = &crypt_iv_plain_ops;
  2304. else if (strcmp(ivmode, "plain64") == 0)
  2305. cc->iv_gen_ops = &crypt_iv_plain64_ops;
  2306. else if (strcmp(ivmode, "plain64be") == 0)
  2307. cc->iv_gen_ops = &crypt_iv_plain64be_ops;
  2308. else if (strcmp(ivmode, "essiv") == 0)
  2309. cc->iv_gen_ops = &crypt_iv_essiv_ops;
  2310. else if (strcmp(ivmode, "benbi") == 0)
  2311. cc->iv_gen_ops = &crypt_iv_benbi_ops;
  2312. else if (strcmp(ivmode, "null") == 0)
  2313. cc->iv_gen_ops = &crypt_iv_null_ops;
  2314. else if (strcmp(ivmode, "eboiv") == 0)
  2315. cc->iv_gen_ops = &crypt_iv_eboiv_ops;
  2316. else if (strcmp(ivmode, "elephant") == 0) {
  2317. cc->iv_gen_ops = &crypt_iv_elephant_ops;
  2318. cc->key_parts = 2;
  2319. cc->key_extra_size = cc->key_size / 2;
  2320. if (cc->key_extra_size > ELEPHANT_MAX_KEY_SIZE)
  2321. return -EINVAL;
  2322. set_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags);
  2323. } else if (strcmp(ivmode, "lmk") == 0) {
  2324. cc->iv_gen_ops = &crypt_iv_lmk_ops;
  2325. /*
  2326. * Version 2 and 3 is recognised according
  2327. * to length of provided multi-key string.
  2328. * If present (version 3), last key is used as IV seed.
  2329. * All keys (including IV seed) are always the same size.
  2330. */
  2331. if (cc->key_size % cc->key_parts) {
  2332. cc->key_parts++;
  2333. cc->key_extra_size = cc->key_size / cc->key_parts;
  2334. }
  2335. } else if (strcmp(ivmode, "tcw") == 0) {
  2336. cc->iv_gen_ops = &crypt_iv_tcw_ops;
  2337. cc->key_parts += 2; /* IV + whitening */
  2338. cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
  2339. } else if (strcmp(ivmode, "random") == 0) {
  2340. cc->iv_gen_ops = &crypt_iv_random_ops;
  2341. /* Need storage space in integrity fields. */
  2342. cc->integrity_iv_size = cc->iv_size;
  2343. } else {
  2344. ti->error = "Invalid IV mode";
  2345. return -EINVAL;
  2346. }
  2347. return 0;
  2348. }
  2349. /*
  2350. * Workaround to parse HMAC algorithm from AEAD crypto API spec.
  2351. * The HMAC is needed to calculate tag size (HMAC digest size).
  2352. * This should be probably done by crypto-api calls (once available...)
  2353. */
  2354. static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
  2355. {
  2356. char *start, *end, *mac_alg = NULL;
  2357. struct crypto_ahash *mac;
  2358. if (!strstarts(cipher_api, "authenc("))
  2359. return 0;
  2360. start = strchr(cipher_api, '(');
  2361. end = strchr(cipher_api, ',');
  2362. if (!start || !end || ++start > end)
  2363. return -EINVAL;
  2364. mac_alg = kmemdup_nul(start, end - start, GFP_KERNEL);
  2365. if (!mac_alg)
  2366. return -ENOMEM;
  2367. mac = crypto_alloc_ahash(mac_alg, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
  2368. kfree(mac_alg);
  2369. if (IS_ERR(mac))
  2370. return PTR_ERR(mac);
  2371. if (!test_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags))
  2372. cc->key_mac_size = crypto_ahash_digestsize(mac);
  2373. crypto_free_ahash(mac);
  2374. cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
  2375. if (!cc->authenc_key)
  2376. return -ENOMEM;
  2377. return 0;
  2378. }
  2379. static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
  2380. char **ivmode, char **ivopts)
  2381. {
  2382. struct crypt_config *cc = ti->private;
  2383. char *tmp, *cipher_api, buf[CRYPTO_MAX_ALG_NAME];
  2384. int ret = -EINVAL;
  2385. cc->tfms_count = 1;
  2386. /*
  2387. * New format (capi: prefix)
  2388. * capi:cipher_api_spec-iv:ivopts
  2389. */
  2390. tmp = &cipher_in[strlen("capi:")];
  2391. /* Separate IV options if present, it can contain another '-' in hash name */
  2392. *ivopts = strrchr(tmp, ':');
  2393. if (*ivopts) {
  2394. **ivopts = '\0';
  2395. (*ivopts)++;
  2396. }
  2397. /* Parse IV mode */
  2398. *ivmode = strrchr(tmp, '-');
  2399. if (*ivmode) {
  2400. **ivmode = '\0';
  2401. (*ivmode)++;
  2402. }
  2403. /* The rest is crypto API spec */
  2404. cipher_api = tmp;
  2405. /* Alloc AEAD, can be used only in new format. */
  2406. if (crypt_integrity_aead(cc)) {
  2407. ret = crypt_ctr_auth_cipher(cc, cipher_api);
  2408. if (ret < 0) {
  2409. ti->error = "Invalid AEAD cipher spec";
  2410. return ret;
  2411. }
  2412. }
  2413. if (*ivmode && !strcmp(*ivmode, "lmk"))
  2414. cc->tfms_count = 64;
  2415. if (*ivmode && !strcmp(*ivmode, "essiv")) {
  2416. if (!*ivopts) {
  2417. ti->error = "Digest algorithm missing for ESSIV mode";
  2418. return -EINVAL;
  2419. }
  2420. ret = snprintf(buf, CRYPTO_MAX_ALG_NAME, "essiv(%s,%s)",
  2421. cipher_api, *ivopts);
  2422. if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
  2423. ti->error = "Cannot allocate cipher string";
  2424. return -ENOMEM;
  2425. }
  2426. cipher_api = buf;
  2427. }
  2428. cc->key_parts = cc->tfms_count;
  2429. /* Allocate cipher */
  2430. ret = crypt_alloc_tfms(cc, cipher_api);
  2431. if (ret < 0) {
  2432. ti->error = "Error allocating crypto tfm";
  2433. return ret;
  2434. }
  2435. if (crypt_integrity_aead(cc))
  2436. cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
  2437. else
  2438. cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
  2439. return 0;
  2440. }
  2441. static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
  2442. char **ivmode, char **ivopts)
  2443. {
  2444. struct crypt_config *cc = ti->private;
  2445. char *tmp, *cipher, *chainmode, *keycount;
  2446. char *cipher_api = NULL;
  2447. int ret = -EINVAL;
  2448. char dummy;
  2449. if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
  2450. ti->error = "Bad cipher specification";
  2451. return -EINVAL;
  2452. }
  2453. /*
  2454. * Legacy dm-crypt cipher specification
  2455. * cipher[:keycount]-mode-iv:ivopts
  2456. */
  2457. tmp = cipher_in;
  2458. keycount = strsep(&tmp, "-");
  2459. cipher = strsep(&keycount, ":");
  2460. if (!keycount)
  2461. cc->tfms_count = 1;
  2462. else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
  2463. !is_power_of_2(cc->tfms_count)) {
  2464. ti->error = "Bad cipher key count specification";
  2465. return -EINVAL;
  2466. }
  2467. cc->key_parts = cc->tfms_count;
  2468. chainmode = strsep(&tmp, "-");
  2469. *ivmode = strsep(&tmp, ":");
  2470. *ivopts = tmp;
  2471. /*
  2472. * For compatibility with the original dm-crypt mapping format, if
  2473. * only the cipher name is supplied, use cbc-plain.
  2474. */
  2475. if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
  2476. chainmode = "cbc";
  2477. *ivmode = "plain";
  2478. }
  2479. if (strcmp(chainmode, "ecb") && !*ivmode) {
  2480. ti->error = "IV mechanism required";
  2481. return -EINVAL;
  2482. }
  2483. cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
  2484. if (!cipher_api)
  2485. goto bad_mem;
  2486. if (*ivmode && !strcmp(*ivmode, "essiv")) {
  2487. if (!*ivopts) {
  2488. ti->error = "Digest algorithm missing for ESSIV mode";
  2489. kfree(cipher_api);
  2490. return -EINVAL;
  2491. }
  2492. ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
  2493. "essiv(%s(%s),%s)", chainmode, cipher, *ivopts);
  2494. } else {
  2495. ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
  2496. "%s(%s)", chainmode, cipher);
  2497. }
  2498. if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
  2499. kfree(cipher_api);
  2500. goto bad_mem;
  2501. }
  2502. /* Allocate cipher */
  2503. ret = crypt_alloc_tfms(cc, cipher_api);
  2504. if (ret < 0) {
  2505. ti->error = "Error allocating crypto tfm";
  2506. kfree(cipher_api);
  2507. return ret;
  2508. }
  2509. kfree(cipher_api);
  2510. return 0;
  2511. bad_mem:
  2512. ti->error = "Cannot allocate cipher strings";
  2513. return -ENOMEM;
  2514. }
  2515. static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
  2516. {
  2517. struct crypt_config *cc = ti->private;
  2518. char *ivmode = NULL, *ivopts = NULL;
  2519. int ret;
  2520. cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
  2521. if (!cc->cipher_string) {
  2522. ti->error = "Cannot allocate cipher strings";
  2523. return -ENOMEM;
  2524. }
  2525. if (strstarts(cipher_in, "capi:"))
  2526. ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
  2527. else
  2528. ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
  2529. if (ret)
  2530. return ret;
  2531. /* Initialize IV */
  2532. ret = crypt_ctr_ivmode(ti, ivmode);
  2533. if (ret < 0)
  2534. return ret;
  2535. /* Initialize and set key */
  2536. ret = crypt_set_key(cc, key);
  2537. if (ret < 0) {
  2538. ti->error = "Error decoding and setting key";
  2539. return ret;
  2540. }
  2541. /* Allocate IV */
  2542. if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
  2543. ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
  2544. if (ret < 0) {
  2545. ti->error = "Error creating IV";
  2546. return ret;
  2547. }
  2548. }
  2549. /* Initialize IV (set keys for ESSIV etc) */
  2550. if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
  2551. ret = cc->iv_gen_ops->init(cc);
  2552. if (ret < 0) {
  2553. ti->error = "Error initialising IV";
  2554. return ret;
  2555. }
  2556. }
  2557. /* wipe the kernel key payload copy */
  2558. if (cc->key_string)
  2559. memset(cc->key, 0, cc->key_size * sizeof(u8));
  2560. return ret;
  2561. }
  2562. static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
  2563. {
  2564. struct crypt_config *cc = ti->private;
  2565. struct dm_arg_set as;
  2566. static const struct dm_arg _args[] = {
  2567. {0, 9, "Invalid number of feature args"},
  2568. };
  2569. unsigned int opt_params, val;
  2570. const char *opt_string, *sval;
  2571. char dummy;
  2572. int ret;
  2573. /* Optional parameters */
  2574. as.argc = argc;
  2575. as.argv = argv;
  2576. ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
  2577. if (ret)
  2578. return ret;
  2579. while (opt_params--) {
  2580. opt_string = dm_shift_arg(&as);
  2581. if (!opt_string) {
  2582. ti->error = "Not enough feature arguments";
  2583. return -EINVAL;
  2584. }
  2585. if (!strcasecmp(opt_string, "allow_discards"))
  2586. ti->num_discard_bios = 1;
  2587. else if (!strcasecmp(opt_string, "same_cpu_crypt"))
  2588. set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
  2589. else if (!strcasecmp(opt_string, "high_priority"))
  2590. set_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags);
  2591. else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
  2592. set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
  2593. else if (!strcasecmp(opt_string, "no_read_workqueue"))
  2594. set_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
  2595. else if (!strcasecmp(opt_string, "no_write_workqueue"))
  2596. set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
  2597. else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
  2598. if (val == 0 || val > MAX_TAG_SIZE) {
  2599. ti->error = "Invalid integrity arguments";
  2600. return -EINVAL;
  2601. }
  2602. cc->used_tag_size = val;
  2603. sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
  2604. if (!strcasecmp(sval, "aead")) {
  2605. set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
  2606. } else if (strcasecmp(sval, "none")) {
  2607. ti->error = "Unknown integrity profile";
  2608. return -EINVAL;
  2609. }
  2610. cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
  2611. if (!cc->cipher_auth)
  2612. return -ENOMEM;
  2613. } else if (sscanf(opt_string, "integrity_key_size:%u%c", &val, &dummy) == 1) {
  2614. if (!val) {
  2615. ti->error = "Invalid integrity_key_size argument";
  2616. return -EINVAL;
  2617. }
  2618. cc->key_mac_size = val;
  2619. set_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags);
  2620. } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
  2621. if (cc->sector_size < (1 << SECTOR_SHIFT) ||
  2622. cc->sector_size > 4096 ||
  2623. (cc->sector_size & (cc->sector_size - 1))) {
  2624. ti->error = "Invalid feature value for sector_size";
  2625. return -EINVAL;
  2626. }
  2627. if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
  2628. ti->error = "Device size is not multiple of sector_size feature";
  2629. return -EINVAL;
  2630. }
  2631. cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
  2632. } else if (!strcasecmp(opt_string, "iv_large_sectors"))
  2633. set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
  2634. else {
  2635. ti->error = "Invalid feature arguments";
  2636. return -EINVAL;
  2637. }
  2638. }
  2639. return 0;
  2640. }
  2641. #ifdef CONFIG_BLK_DEV_ZONED
  2642. static int crypt_report_zones(struct dm_target *ti,
  2643. struct dm_report_zones_args *args, unsigned int nr_zones)
  2644. {
  2645. struct crypt_config *cc = ti->private;
  2646. return dm_report_zones(cc->dev->bdev, cc->start,
  2647. cc->start + dm_target_offset(ti, args->next_sector),
  2648. args, nr_zones);
  2649. }
  2650. #else
  2651. #define crypt_report_zones NULL
  2652. #endif
  2653. /*
  2654. * Construct an encryption mapping:
  2655. * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
  2656. */
  2657. static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
  2658. {
  2659. struct crypt_config *cc;
  2660. const char *devname = dm_table_device_name(ti->table);
  2661. int key_size, wq_id;
  2662. unsigned int align_mask;
  2663. unsigned int common_wq_flags;
  2664. unsigned long long tmpll;
  2665. int ret;
  2666. size_t iv_size_padding, additional_req_size;
  2667. char dummy;
  2668. if (argc < 5) {
  2669. ti->error = "Not enough arguments";
  2670. return -EINVAL;
  2671. }
  2672. key_size = get_key_size(&argv[1]);
  2673. if (key_size < 0) {
  2674. ti->error = "Cannot parse key size";
  2675. return -EINVAL;
  2676. }
  2677. cc = kzalloc_flex(*cc, key, key_size);
  2678. if (!cc) {
  2679. ti->error = "Cannot allocate encryption context";
  2680. return -ENOMEM;
  2681. }
  2682. cc->key_size = key_size;
  2683. cc->sector_size = (1 << SECTOR_SHIFT);
  2684. cc->sector_shift = 0;
  2685. ti->private = cc;
  2686. spin_lock(&dm_crypt_clients_lock);
  2687. dm_crypt_clients_n++;
  2688. crypt_calculate_pages_per_client();
  2689. spin_unlock(&dm_crypt_clients_lock);
  2690. ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
  2691. if (ret < 0)
  2692. goto bad;
  2693. /* Optional parameters need to be read before cipher constructor */
  2694. if (argc > 5) {
  2695. ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
  2696. if (ret)
  2697. goto bad;
  2698. }
  2699. ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
  2700. if (ret < 0)
  2701. goto bad;
  2702. if (crypt_integrity_aead(cc)) {
  2703. cc->dmreq_start = sizeof(struct aead_request);
  2704. cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
  2705. align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
  2706. } else {
  2707. cc->dmreq_start = sizeof(struct skcipher_request);
  2708. cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
  2709. align_mask = crypto_skcipher_alignmask(any_tfm(cc));
  2710. }
  2711. cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
  2712. if (align_mask < CRYPTO_MINALIGN) {
  2713. /* Allocate the padding exactly */
  2714. iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
  2715. & align_mask;
  2716. } else {
  2717. /*
  2718. * If the cipher requires greater alignment than kmalloc
  2719. * alignment, we don't know the exact position of the
  2720. * initialization vector. We must assume worst case.
  2721. */
  2722. iv_size_padding = align_mask;
  2723. }
  2724. /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
  2725. additional_req_size = sizeof(struct dm_crypt_request) +
  2726. iv_size_padding + cc->iv_size +
  2727. cc->iv_size +
  2728. sizeof(uint64_t) +
  2729. sizeof(unsigned int);
  2730. ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
  2731. if (ret) {
  2732. ti->error = "Cannot allocate crypt request mempool";
  2733. goto bad;
  2734. }
  2735. cc->per_bio_data_size = ti->per_io_data_size =
  2736. ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
  2737. ARCH_DMA_MINALIGN);
  2738. ret = mempool_init(&cc->page_pool, BIO_MAX_VECS, crypt_page_alloc, crypt_page_free, cc);
  2739. if (ret) {
  2740. ti->error = "Cannot allocate page mempool";
  2741. goto bad;
  2742. }
  2743. ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
  2744. if (ret) {
  2745. ti->error = "Cannot allocate crypt bioset";
  2746. goto bad;
  2747. }
  2748. mutex_init(&cc->bio_alloc_lock);
  2749. ret = -EINVAL;
  2750. if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
  2751. (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
  2752. ti->error = "Invalid iv_offset sector";
  2753. goto bad;
  2754. }
  2755. cc->iv_offset = tmpll;
  2756. ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
  2757. if (ret) {
  2758. ti->error = "Device lookup failed";
  2759. goto bad;
  2760. }
  2761. ret = -EINVAL;
  2762. if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
  2763. ti->error = "Invalid device sector";
  2764. goto bad;
  2765. }
  2766. cc->start = tmpll;
  2767. if (bdev_is_zoned(cc->dev->bdev)) {
  2768. /*
  2769. * For zoned block devices, we need to preserve the issuer write
  2770. * ordering. To do so, disable write workqueues and force inline
  2771. * encryption completion.
  2772. */
  2773. set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
  2774. set_bit(DM_CRYPT_WRITE_INLINE, &cc->flags);
  2775. /*
  2776. * All zone append writes to a zone of a zoned block device will
  2777. * have the same BIO sector, the start of the zone. When the
  2778. * cypher IV mode uses sector values, all data targeting a
  2779. * zone will be encrypted using the first sector numbers of the
  2780. * zone. This will not result in write errors but will
  2781. * cause most reads to fail as reads will use the sector values
  2782. * for the actual data locations, resulting in IV mismatch.
  2783. * To avoid this problem, ask DM core to emulate zone append
  2784. * operations with regular writes.
  2785. */
  2786. DMDEBUG("Zone append operations will be emulated");
  2787. ti->emulate_zone_append = true;
  2788. }
  2789. if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
  2790. ret = crypt_integrity_ctr(cc, ti);
  2791. if (ret)
  2792. goto bad;
  2793. cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->tuple_size;
  2794. if (!cc->tag_pool_max_sectors)
  2795. cc->tag_pool_max_sectors = 1;
  2796. ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
  2797. cc->tag_pool_max_sectors * cc->tuple_size);
  2798. if (ret) {
  2799. ti->error = "Cannot allocate integrity tags mempool";
  2800. goto bad;
  2801. }
  2802. cc->tag_pool_max_sectors <<= cc->sector_shift;
  2803. }
  2804. wq_id = ida_alloc_min(&workqueue_ida, 1, GFP_KERNEL);
  2805. if (wq_id < 0) {
  2806. ti->error = "Couldn't get workqueue id";
  2807. ret = wq_id;
  2808. goto bad;
  2809. }
  2810. cc->workqueue_id = wq_id;
  2811. ret = -ENOMEM;
  2812. common_wq_flags = WQ_MEM_RECLAIM | WQ_SYSFS;
  2813. if (test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags))
  2814. common_wq_flags |= WQ_HIGHPRI;
  2815. cc->io_queue = alloc_workqueue("kcryptd_io-%s-%d",
  2816. common_wq_flags | WQ_PERCPU, 1,
  2817. devname, wq_id);
  2818. if (!cc->io_queue) {
  2819. ti->error = "Couldn't create kcryptd io queue";
  2820. goto bad;
  2821. }
  2822. if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags)) {
  2823. cc->crypt_queue = alloc_workqueue("kcryptd-%s-%d",
  2824. common_wq_flags | WQ_CPU_INTENSIVE | WQ_PERCPU,
  2825. 1, devname, wq_id);
  2826. } else {
  2827. /*
  2828. * While crypt_queue is certainly CPU intensive, the use of
  2829. * WQ_CPU_INTENSIVE is meaningless with WQ_UNBOUND.
  2830. */
  2831. cc->crypt_queue = alloc_workqueue("kcryptd-%s-%d",
  2832. common_wq_flags | WQ_UNBOUND,
  2833. num_online_cpus(), devname, wq_id);
  2834. }
  2835. if (!cc->crypt_queue) {
  2836. ti->error = "Couldn't create kcryptd queue";
  2837. goto bad;
  2838. }
  2839. spin_lock_init(&cc->write_thread_lock);
  2840. cc->write_tree = RB_ROOT;
  2841. cc->write_thread = kthread_run(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
  2842. if (IS_ERR(cc->write_thread)) {
  2843. ret = PTR_ERR(cc->write_thread);
  2844. cc->write_thread = NULL;
  2845. ti->error = "Couldn't spawn write thread";
  2846. goto bad;
  2847. }
  2848. if (test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags))
  2849. set_user_nice(cc->write_thread, MIN_NICE);
  2850. ti->num_flush_bios = 1;
  2851. ti->limit_swap_bios = true;
  2852. ti->accounts_remapped_io = true;
  2853. dm_audit_log_ctr(DM_MSG_PREFIX, ti, 1);
  2854. return 0;
  2855. bad:
  2856. dm_audit_log_ctr(DM_MSG_PREFIX, ti, 0);
  2857. crypt_dtr(ti);
  2858. return ret;
  2859. }
  2860. static int crypt_map(struct dm_target *ti, struct bio *bio)
  2861. {
  2862. struct dm_crypt_io *io;
  2863. struct crypt_config *cc = ti->private;
  2864. unsigned max_sectors;
  2865. bool no_split;
  2866. /*
  2867. * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
  2868. * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
  2869. * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
  2870. */
  2871. if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
  2872. bio_op(bio) == REQ_OP_DISCARD)) {
  2873. bio_set_dev(bio, cc->dev->bdev);
  2874. if (bio_sectors(bio))
  2875. bio->bi_iter.bi_sector = cc->start +
  2876. dm_target_offset(ti, bio->bi_iter.bi_sector);
  2877. return DM_MAPIO_REMAPPED;
  2878. }
  2879. /*
  2880. * Check if bio is too large, split as needed.
  2881. *
  2882. * For zoned devices, splitting write operations creates the
  2883. * risk of deadlocking queue freeze operations with zone write
  2884. * plugging BIO work when the reminder of a split BIO is
  2885. * issued. So always allow the entire BIO to proceed.
  2886. */
  2887. no_split = (ti->emulate_zone_append && op_is_write(bio_op(bio))) ||
  2888. (bio->bi_opf & REQ_ATOMIC);
  2889. max_sectors = get_max_request_sectors(ti, bio, no_split);
  2890. if (unlikely(bio_sectors(bio) > max_sectors)) {
  2891. if (unlikely(no_split))
  2892. return DM_MAPIO_KILL;
  2893. dm_accept_partial_bio(bio, max_sectors);
  2894. }
  2895. /*
  2896. * Ensure that bio is a multiple of internal sector encryption size
  2897. * and is aligned to this size as defined in IO hints.
  2898. */
  2899. if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
  2900. return DM_MAPIO_KILL;
  2901. if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
  2902. return DM_MAPIO_KILL;
  2903. io = dm_per_bio_data(bio, cc->per_bio_data_size);
  2904. crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
  2905. if (cc->tuple_size) {
  2906. unsigned int tag_len = cc->tuple_size * (bio_sectors(bio) >> cc->sector_shift);
  2907. if (unlikely(tag_len > KMALLOC_MAX_SIZE))
  2908. io->integrity_metadata = NULL;
  2909. else
  2910. io->integrity_metadata = kmalloc(tag_len, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
  2911. if (unlikely(!io->integrity_metadata)) {
  2912. if (bio_sectors(bio) > cc->tag_pool_max_sectors)
  2913. dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
  2914. io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
  2915. io->integrity_metadata_from_pool = true;
  2916. }
  2917. }
  2918. if (crypt_integrity_aead(cc))
  2919. io->ctx.r.req_aead = (struct aead_request *)(io + 1);
  2920. else
  2921. io->ctx.r.req = (struct skcipher_request *)(io + 1);
  2922. if (bio_data_dir(io->base_bio) == READ) {
  2923. if (kcryptd_io_read(io, CRYPT_MAP_READ_GFP))
  2924. kcryptd_queue_read(io);
  2925. } else
  2926. kcryptd_queue_crypt(io);
  2927. return DM_MAPIO_SUBMITTED;
  2928. }
  2929. static char hex2asc(unsigned char c)
  2930. {
  2931. return c + '0' + ((unsigned int)(9 - c) >> 4 & 0x27);
  2932. }
  2933. static void crypt_status(struct dm_target *ti, status_type_t type,
  2934. unsigned int status_flags, char *result, unsigned int maxlen)
  2935. {
  2936. struct crypt_config *cc = ti->private;
  2937. unsigned int i, sz = 0;
  2938. int num_feature_args = 0;
  2939. switch (type) {
  2940. case STATUSTYPE_INFO:
  2941. result[0] = '\0';
  2942. break;
  2943. case STATUSTYPE_TABLE:
  2944. DMEMIT("%s ", cc->cipher_string);
  2945. if (cc->key_size > 0) {
  2946. if (cc->key_string)
  2947. DMEMIT(":%u:%s", cc->key_size, cc->key_string);
  2948. else {
  2949. for (i = 0; i < cc->key_size; i++) {
  2950. DMEMIT("%c%c", hex2asc(cc->key[i] >> 4),
  2951. hex2asc(cc->key[i] & 0xf));
  2952. }
  2953. }
  2954. } else
  2955. DMEMIT("-");
  2956. DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
  2957. cc->dev->name, (unsigned long long)cc->start);
  2958. num_feature_args += !!ti->num_discard_bios;
  2959. num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
  2960. num_feature_args += test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags);
  2961. num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
  2962. num_feature_args += test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
  2963. num_feature_args += test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
  2964. num_feature_args += !!cc->used_tag_size;
  2965. num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
  2966. num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
  2967. num_feature_args += test_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags);
  2968. if (num_feature_args) {
  2969. DMEMIT(" %d", num_feature_args);
  2970. if (ti->num_discard_bios)
  2971. DMEMIT(" allow_discards");
  2972. if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
  2973. DMEMIT(" same_cpu_crypt");
  2974. if (test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags))
  2975. DMEMIT(" high_priority");
  2976. if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
  2977. DMEMIT(" submit_from_crypt_cpus");
  2978. if (test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags))
  2979. DMEMIT(" no_read_workqueue");
  2980. if (test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))
  2981. DMEMIT(" no_write_workqueue");
  2982. if (cc->used_tag_size)
  2983. DMEMIT(" integrity:%u:%s", cc->used_tag_size, cc->cipher_auth);
  2984. if (cc->sector_size != (1 << SECTOR_SHIFT))
  2985. DMEMIT(" sector_size:%d", cc->sector_size);
  2986. if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
  2987. DMEMIT(" iv_large_sectors");
  2988. if (test_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags))
  2989. DMEMIT(" integrity_key_size:%u", cc->key_mac_size);
  2990. }
  2991. break;
  2992. case STATUSTYPE_IMA:
  2993. DMEMIT_TARGET_NAME_VERSION(ti->type);
  2994. DMEMIT(",allow_discards=%c", ti->num_discard_bios ? 'y' : 'n');
  2995. DMEMIT(",same_cpu_crypt=%c", test_bit(DM_CRYPT_SAME_CPU, &cc->flags) ? 'y' : 'n');
  2996. DMEMIT(",high_priority=%c", test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags) ? 'y' : 'n');
  2997. DMEMIT(",submit_from_crypt_cpus=%c", test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags) ?
  2998. 'y' : 'n');
  2999. DMEMIT(",no_read_workqueue=%c", test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags) ?
  3000. 'y' : 'n');
  3001. DMEMIT(",no_write_workqueue=%c", test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags) ?
  3002. 'y' : 'n');
  3003. DMEMIT(",iv_large_sectors=%c", test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags) ?
  3004. 'y' : 'n');
  3005. if (cc->used_tag_size)
  3006. DMEMIT(",integrity_tag_size=%u,cipher_auth=%s",
  3007. cc->used_tag_size, cc->cipher_auth);
  3008. if (cc->sector_size != (1 << SECTOR_SHIFT))
  3009. DMEMIT(",sector_size=%d", cc->sector_size);
  3010. if (cc->cipher_string)
  3011. DMEMIT(",cipher_string=%s", cc->cipher_string);
  3012. DMEMIT(",key_size=%u", cc->key_size);
  3013. DMEMIT(",key_parts=%u", cc->key_parts);
  3014. DMEMIT(",key_extra_size=%u", cc->key_extra_size);
  3015. DMEMIT(",key_mac_size=%u", cc->key_mac_size);
  3016. DMEMIT(";");
  3017. break;
  3018. }
  3019. }
  3020. static void crypt_postsuspend(struct dm_target *ti)
  3021. {
  3022. struct crypt_config *cc = ti->private;
  3023. set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  3024. }
  3025. static int crypt_preresume(struct dm_target *ti)
  3026. {
  3027. struct crypt_config *cc = ti->private;
  3028. if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
  3029. DMERR("aborting resume - crypt key is not set.");
  3030. return -EAGAIN;
  3031. }
  3032. return 0;
  3033. }
  3034. static void crypt_resume(struct dm_target *ti)
  3035. {
  3036. struct crypt_config *cc = ti->private;
  3037. clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  3038. }
  3039. /* Message interface
  3040. * key set <key>
  3041. * key wipe
  3042. */
  3043. static int crypt_message(struct dm_target *ti, unsigned int argc, char **argv,
  3044. char *result, unsigned int maxlen)
  3045. {
  3046. struct crypt_config *cc = ti->private;
  3047. int key_size, ret = -EINVAL;
  3048. if (argc < 2)
  3049. goto error;
  3050. if (!strcasecmp(argv[0], "key")) {
  3051. if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
  3052. DMWARN("not suspended during key manipulation.");
  3053. return -EINVAL;
  3054. }
  3055. if (argc == 3 && !strcasecmp(argv[1], "set")) {
  3056. /* The key size may not be changed. */
  3057. key_size = get_key_size(&argv[2]);
  3058. if (key_size < 0 || cc->key_size != key_size) {
  3059. memset(argv[2], '0', strlen(argv[2]));
  3060. return -EINVAL;
  3061. }
  3062. ret = crypt_set_key(cc, argv[2]);
  3063. if (ret)
  3064. return ret;
  3065. if (cc->iv_gen_ops && cc->iv_gen_ops->init)
  3066. ret = cc->iv_gen_ops->init(cc);
  3067. /* wipe the kernel key payload copy */
  3068. if (cc->key_string)
  3069. memset(cc->key, 0, cc->key_size * sizeof(u8));
  3070. return ret;
  3071. }
  3072. if (argc == 2 && !strcasecmp(argv[1], "wipe"))
  3073. return crypt_wipe_key(cc);
  3074. }
  3075. error:
  3076. DMWARN("unrecognised message received.");
  3077. return -EINVAL;
  3078. }
  3079. static int crypt_iterate_devices(struct dm_target *ti,
  3080. iterate_devices_callout_fn fn, void *data)
  3081. {
  3082. struct crypt_config *cc = ti->private;
  3083. return fn(ti, cc->dev, cc->start, ti->len, data);
  3084. }
  3085. static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
  3086. {
  3087. struct crypt_config *cc = ti->private;
  3088. limits->logical_block_size =
  3089. max_t(unsigned int, limits->logical_block_size, cc->sector_size);
  3090. limits->physical_block_size =
  3091. max_t(unsigned int, limits->physical_block_size, cc->sector_size);
  3092. limits->io_min = max_t(unsigned int, limits->io_min, cc->sector_size);
  3093. limits->dma_alignment = limits->logical_block_size - 1;
  3094. /*
  3095. * For zoned dm-crypt targets, there will be no internal splitting of
  3096. * write BIOs to avoid exceeding BIO_MAX_VECS vectors per BIO. But
  3097. * without respecting this limit, crypt_alloc_buffer() will trigger a
  3098. * BUG(). Avoid this by forcing DM core to split write BIOs to this
  3099. * limit.
  3100. */
  3101. if (ti->emulate_zone_append)
  3102. limits->max_hw_sectors = min(limits->max_hw_sectors,
  3103. BIO_MAX_VECS << PAGE_SECTORS_SHIFT);
  3104. limits->atomic_write_hw_unit_max = min(limits->atomic_write_hw_unit_max,
  3105. BIO_MAX_VECS << PAGE_SHIFT);
  3106. limits->atomic_write_hw_max = min(limits->atomic_write_hw_max,
  3107. BIO_MAX_VECS << PAGE_SHIFT);
  3108. }
  3109. static struct target_type crypt_target = {
  3110. .name = "crypt",
  3111. .version = {1, 29, 0},
  3112. .module = THIS_MODULE,
  3113. .ctr = crypt_ctr,
  3114. .dtr = crypt_dtr,
  3115. .features = DM_TARGET_ZONED_HM | DM_TARGET_ATOMIC_WRITES,
  3116. .report_zones = crypt_report_zones,
  3117. .map = crypt_map,
  3118. .status = crypt_status,
  3119. .postsuspend = crypt_postsuspend,
  3120. .preresume = crypt_preresume,
  3121. .resume = crypt_resume,
  3122. .message = crypt_message,
  3123. .iterate_devices = crypt_iterate_devices,
  3124. .io_hints = crypt_io_hints,
  3125. };
  3126. module_dm(crypt);
  3127. MODULE_AUTHOR("Jana Saout <jana@saout.de>");
  3128. MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
  3129. MODULE_LICENSE("GPL");