dm-crypt.c 83 KB

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