dm-crypt.c 99 KB

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