super.c 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * bcache setup/teardown code, and some metadata io - read a superblock and
  4. * figure out what to do with it.
  5. *
  6. * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
  7. * Copyright 2012 Google, Inc.
  8. */
  9. #include "bcache.h"
  10. #include "btree.h"
  11. #include "debug.h"
  12. #include "extents.h"
  13. #include "request.h"
  14. #include "writeback.h"
  15. #include "features.h"
  16. #include <linux/blkdev.h>
  17. #include <linux/pagemap.h>
  18. #include <linux/debugfs.h>
  19. #include <linux/idr.h>
  20. #include <linux/kthread.h>
  21. #include <linux/workqueue.h>
  22. #include <linux/module.h>
  23. #include <linux/random.h>
  24. #include <linux/reboot.h>
  25. #include <linux/sysfs.h>
  26. unsigned int bch_cutoff_writeback;
  27. unsigned int bch_cutoff_writeback_sync;
  28. static const char bcache_magic[] = {
  29. 0xc6, 0x85, 0x73, 0xf6, 0x4e, 0x1a, 0x45, 0xca,
  30. 0x82, 0x65, 0xf5, 0x7f, 0x48, 0xba, 0x6d, 0x81
  31. };
  32. static const char invalid_uuid[] = {
  33. 0xa0, 0x3e, 0xf8, 0xed, 0x3e, 0xe1, 0xb8, 0x78,
  34. 0xc8, 0x50, 0xfc, 0x5e, 0xcb, 0x16, 0xcd, 0x99
  35. };
  36. static struct kobject *bcache_kobj;
  37. struct mutex bch_register_lock;
  38. bool bcache_is_reboot;
  39. LIST_HEAD(bch_cache_sets);
  40. static LIST_HEAD(uncached_devices);
  41. static int bcache_major;
  42. static DEFINE_IDA(bcache_device_idx);
  43. static wait_queue_head_t unregister_wait;
  44. struct workqueue_struct *bcache_wq;
  45. struct workqueue_struct *bch_flush_wq;
  46. struct workqueue_struct *bch_journal_wq;
  47. #define BTREE_MAX_PAGES (256 * 1024 / PAGE_SIZE)
  48. /* limitation of partitions number on single bcache device */
  49. #define BCACHE_MINORS 128
  50. /* limitation of bcache devices number on single system */
  51. #define BCACHE_DEVICE_IDX_MAX ((1U << MINORBITS)/BCACHE_MINORS)
  52. /* Superblock */
  53. static unsigned int get_bucket_size(struct cache_sb *sb, struct cache_sb_disk *s)
  54. {
  55. unsigned int bucket_size = le16_to_cpu(s->bucket_size);
  56. if (sb->version >= BCACHE_SB_VERSION_CDEV_WITH_FEATURES) {
  57. if (bch_has_feature_large_bucket(sb)) {
  58. unsigned int max, order;
  59. max = sizeof(unsigned int) * BITS_PER_BYTE - 1;
  60. order = le16_to_cpu(s->bucket_size);
  61. /*
  62. * bcache tool will make sure the overflow won't
  63. * happen, an error message here is enough.
  64. */
  65. if (order > max)
  66. pr_err("Bucket size (1 << %u) overflows\n",
  67. order);
  68. bucket_size = 1 << order;
  69. } else if (bch_has_feature_obso_large_bucket(sb)) {
  70. bucket_size +=
  71. le16_to_cpu(s->obso_bucket_size_hi) << 16;
  72. }
  73. }
  74. return bucket_size;
  75. }
  76. static const char *read_super_common(struct cache_sb *sb, struct block_device *bdev,
  77. struct cache_sb_disk *s)
  78. {
  79. const char *err;
  80. unsigned int i;
  81. sb->first_bucket= le16_to_cpu(s->first_bucket);
  82. sb->nbuckets = le64_to_cpu(s->nbuckets);
  83. sb->bucket_size = get_bucket_size(sb, s);
  84. sb->nr_in_set = le16_to_cpu(s->nr_in_set);
  85. sb->nr_this_dev = le16_to_cpu(s->nr_this_dev);
  86. err = "Too many journal buckets";
  87. if (sb->keys > SB_JOURNAL_BUCKETS)
  88. goto err;
  89. err = "Too many buckets";
  90. if (sb->nbuckets > LONG_MAX)
  91. goto err;
  92. err = "Not enough buckets";
  93. if (sb->nbuckets < 1 << 7)
  94. goto err;
  95. err = "Bad block size (not power of 2)";
  96. if (!is_power_of_2(sb->block_size))
  97. goto err;
  98. err = "Bad block size (larger than page size)";
  99. if (sb->block_size > PAGE_SECTORS)
  100. goto err;
  101. err = "Bad bucket size (not power of 2)";
  102. if (!is_power_of_2(sb->bucket_size))
  103. goto err;
  104. err = "Bad bucket size (smaller than page size)";
  105. if (sb->bucket_size < PAGE_SECTORS)
  106. goto err;
  107. err = "Invalid superblock: device too small";
  108. if (get_capacity(bdev->bd_disk) <
  109. sb->bucket_size * sb->nbuckets)
  110. goto err;
  111. err = "Bad UUID";
  112. if (bch_is_zero(sb->set_uuid, 16))
  113. goto err;
  114. err = "Bad cache device number in set";
  115. if (!sb->nr_in_set ||
  116. sb->nr_in_set <= sb->nr_this_dev ||
  117. sb->nr_in_set > MAX_CACHES_PER_SET)
  118. goto err;
  119. err = "Journal buckets not sequential";
  120. for (i = 0; i < sb->keys; i++)
  121. if (sb->d[i] != sb->first_bucket + i)
  122. goto err;
  123. err = "Too many journal buckets";
  124. if (sb->first_bucket + sb->keys > sb->nbuckets)
  125. goto err;
  126. err = "Invalid superblock: first bucket comes before end of super";
  127. if (sb->first_bucket * sb->bucket_size < 16)
  128. goto err;
  129. err = NULL;
  130. err:
  131. return err;
  132. }
  133. static const char *read_super(struct cache_sb *sb, struct block_device *bdev,
  134. struct cache_sb_disk **res)
  135. {
  136. const char *err;
  137. struct cache_sb_disk *s;
  138. struct folio *folio;
  139. unsigned int i;
  140. folio = mapping_read_folio_gfp(bdev->bd_mapping,
  141. SB_OFFSET >> PAGE_SHIFT, GFP_KERNEL);
  142. if (IS_ERR(folio))
  143. return "IO error";
  144. s = folio_address(folio) + offset_in_folio(folio, SB_OFFSET);
  145. sb->offset = le64_to_cpu(s->offset);
  146. sb->version = le64_to_cpu(s->version);
  147. memcpy(sb->magic, s->magic, 16);
  148. memcpy(sb->uuid, s->uuid, 16);
  149. memcpy(sb->set_uuid, s->set_uuid, 16);
  150. memcpy(sb->label, s->label, SB_LABEL_SIZE);
  151. sb->flags = le64_to_cpu(s->flags);
  152. sb->seq = le64_to_cpu(s->seq);
  153. sb->last_mount = le32_to_cpu(s->last_mount);
  154. sb->keys = le16_to_cpu(s->keys);
  155. for (i = 0; i < SB_JOURNAL_BUCKETS; i++)
  156. sb->d[i] = le64_to_cpu(s->d[i]);
  157. pr_debug("read sb version %llu, flags %llu, seq %llu, journal size %u\n",
  158. sb->version, sb->flags, sb->seq, sb->keys);
  159. err = "Not a bcache superblock (bad offset)";
  160. if (sb->offset != SB_SECTOR)
  161. goto err;
  162. err = "Not a bcache superblock (bad magic)";
  163. if (memcmp(sb->magic, bcache_magic, 16))
  164. goto err;
  165. err = "Bad checksum";
  166. if (s->csum != csum_set(s))
  167. goto err;
  168. err = "Bad UUID";
  169. if (bch_is_zero(sb->uuid, 16))
  170. goto err;
  171. sb->block_size = le16_to_cpu(s->block_size);
  172. err = "Superblock block size smaller than device block size";
  173. if (sb->block_size << 9 < bdev_logical_block_size(bdev))
  174. goto err;
  175. switch (sb->version) {
  176. case BCACHE_SB_VERSION_BDEV:
  177. sb->data_offset = BDEV_DATA_START_DEFAULT;
  178. break;
  179. case BCACHE_SB_VERSION_BDEV_WITH_OFFSET:
  180. case BCACHE_SB_VERSION_BDEV_WITH_FEATURES:
  181. sb->data_offset = le64_to_cpu(s->data_offset);
  182. err = "Bad data offset";
  183. if (sb->data_offset < BDEV_DATA_START_DEFAULT)
  184. goto err;
  185. break;
  186. case BCACHE_SB_VERSION_CDEV:
  187. case BCACHE_SB_VERSION_CDEV_WITH_UUID:
  188. err = read_super_common(sb, bdev, s);
  189. if (err)
  190. goto err;
  191. break;
  192. case BCACHE_SB_VERSION_CDEV_WITH_FEATURES:
  193. /*
  194. * Feature bits are needed in read_super_common(),
  195. * convert them firstly.
  196. */
  197. sb->feature_compat = le64_to_cpu(s->feature_compat);
  198. sb->feature_incompat = le64_to_cpu(s->feature_incompat);
  199. sb->feature_ro_compat = le64_to_cpu(s->feature_ro_compat);
  200. /* Check incompatible features */
  201. err = "Unsupported compatible feature found";
  202. if (bch_has_unknown_compat_features(sb))
  203. goto err;
  204. err = "Unsupported read-only compatible feature found";
  205. if (bch_has_unknown_ro_compat_features(sb))
  206. goto err;
  207. err = "Unsupported incompatible feature found";
  208. if (bch_has_unknown_incompat_features(sb))
  209. goto err;
  210. err = read_super_common(sb, bdev, s);
  211. if (err)
  212. goto err;
  213. break;
  214. default:
  215. err = "Unsupported superblock version";
  216. goto err;
  217. }
  218. sb->last_mount = (u32)ktime_get_real_seconds();
  219. *res = s;
  220. return NULL;
  221. err:
  222. folio_put(folio);
  223. return err;
  224. }
  225. static void write_bdev_super_endio(struct bio *bio)
  226. {
  227. struct cached_dev *dc = bio->bi_private;
  228. if (bio->bi_status)
  229. bch_count_backing_io_errors(dc, bio);
  230. closure_put(&dc->sb_write);
  231. }
  232. static void __write_super(struct cache_sb *sb, struct cache_sb_disk *out,
  233. struct bio *bio)
  234. {
  235. unsigned int i;
  236. bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_META;
  237. bio->bi_iter.bi_sector = SB_SECTOR;
  238. bio_add_virt_nofail(bio, out, SB_SIZE);
  239. out->offset = cpu_to_le64(sb->offset);
  240. memcpy(out->uuid, sb->uuid, 16);
  241. memcpy(out->set_uuid, sb->set_uuid, 16);
  242. memcpy(out->label, sb->label, SB_LABEL_SIZE);
  243. out->flags = cpu_to_le64(sb->flags);
  244. out->seq = cpu_to_le64(sb->seq);
  245. out->last_mount = cpu_to_le32(sb->last_mount);
  246. out->first_bucket = cpu_to_le16(sb->first_bucket);
  247. out->keys = cpu_to_le16(sb->keys);
  248. for (i = 0; i < sb->keys; i++)
  249. out->d[i] = cpu_to_le64(sb->d[i]);
  250. if (sb->version >= BCACHE_SB_VERSION_CDEV_WITH_FEATURES) {
  251. out->feature_compat = cpu_to_le64(sb->feature_compat);
  252. out->feature_incompat = cpu_to_le64(sb->feature_incompat);
  253. out->feature_ro_compat = cpu_to_le64(sb->feature_ro_compat);
  254. }
  255. out->version = cpu_to_le64(sb->version);
  256. out->csum = csum_set(out);
  257. pr_debug("ver %llu, flags %llu, seq %llu\n",
  258. sb->version, sb->flags, sb->seq);
  259. submit_bio(bio);
  260. }
  261. static CLOSURE_CALLBACK(bch_write_bdev_super_unlock)
  262. {
  263. closure_type(dc, struct cached_dev, sb_write);
  264. up(&dc->sb_write_mutex);
  265. }
  266. void bch_write_bdev_super(struct cached_dev *dc, struct closure *parent)
  267. {
  268. struct closure *cl = &dc->sb_write;
  269. struct bio *bio = &dc->sb_bio;
  270. down(&dc->sb_write_mutex);
  271. closure_init(cl, parent);
  272. bio_init(bio, dc->bdev, dc->sb_bv, 1, 0);
  273. bio->bi_end_io = write_bdev_super_endio;
  274. bio->bi_private = dc;
  275. closure_get(cl);
  276. /* I/O request sent to backing device */
  277. __write_super(&dc->sb, dc->sb_disk, bio);
  278. closure_return_with_destructor(cl, bch_write_bdev_super_unlock);
  279. }
  280. static void write_super_endio(struct bio *bio)
  281. {
  282. struct cache *ca = bio->bi_private;
  283. /* is_read = 0 */
  284. bch_count_io_errors(ca, bio->bi_status, 0,
  285. "writing superblock");
  286. closure_put(&ca->set->sb_write);
  287. }
  288. static CLOSURE_CALLBACK(bcache_write_super_unlock)
  289. {
  290. closure_type(c, struct cache_set, sb_write);
  291. up(&c->sb_write_mutex);
  292. }
  293. void bcache_write_super(struct cache_set *c)
  294. {
  295. struct closure *cl = &c->sb_write;
  296. struct cache *ca = c->cache;
  297. struct bio *bio = &ca->sb_bio;
  298. unsigned int version = BCACHE_SB_VERSION_CDEV_WITH_UUID;
  299. down(&c->sb_write_mutex);
  300. closure_init(cl, &c->cl);
  301. ca->sb.seq++;
  302. if (ca->sb.version < version)
  303. ca->sb.version = version;
  304. bio_init(bio, ca->bdev, ca->sb_bv, 1, 0);
  305. bio->bi_end_io = write_super_endio;
  306. bio->bi_private = ca;
  307. closure_get(cl);
  308. __write_super(&ca->sb, ca->sb_disk, bio);
  309. closure_return_with_destructor(cl, bcache_write_super_unlock);
  310. }
  311. /* UUID io */
  312. static void uuid_endio(struct bio *bio)
  313. {
  314. struct closure *cl = bio->bi_private;
  315. struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
  316. cache_set_err_on(bio->bi_status, c, "accessing uuids");
  317. bch_bbio_free(bio, c);
  318. closure_put(cl);
  319. }
  320. static CLOSURE_CALLBACK(uuid_io_unlock)
  321. {
  322. closure_type(c, struct cache_set, uuid_write);
  323. up(&c->uuid_write_mutex);
  324. }
  325. static void uuid_io(struct cache_set *c, blk_opf_t opf, struct bkey *k,
  326. struct closure *parent)
  327. {
  328. struct closure *cl = &c->uuid_write;
  329. struct uuid_entry *u;
  330. unsigned int i;
  331. char buf[80];
  332. BUG_ON(!parent);
  333. down(&c->uuid_write_mutex);
  334. closure_init(cl, parent);
  335. for (i = 0; i < KEY_PTRS(k); i++) {
  336. struct bio *bio = bch_bbio_alloc(c);
  337. bio->bi_opf = opf | REQ_SYNC | REQ_META;
  338. bio->bi_iter.bi_size = KEY_SIZE(k) << 9;
  339. bio->bi_end_io = uuid_endio;
  340. bio->bi_private = cl;
  341. bch_bio_map(bio, c->uuids);
  342. bch_submit_bbio(bio, c, k, i);
  343. if ((opf & REQ_OP_MASK) != REQ_OP_WRITE)
  344. break;
  345. }
  346. bch_extent_to_text(buf, sizeof(buf), k);
  347. pr_debug("%s UUIDs at %s\n", (opf & REQ_OP_MASK) == REQ_OP_WRITE ?
  348. "wrote" : "read", buf);
  349. for (u = c->uuids; u < c->uuids + c->nr_uuids; u++)
  350. if (!bch_is_zero(u->uuid, 16))
  351. pr_debug("Slot %zi: %pU: %s: 1st: %u last: %u inv: %u\n",
  352. u - c->uuids, u->uuid, u->label,
  353. u->first_reg, u->last_reg, u->invalidated);
  354. closure_return_with_destructor(cl, uuid_io_unlock);
  355. }
  356. static char *uuid_read(struct cache_set *c, struct jset *j, struct closure *cl)
  357. {
  358. struct bkey *k = &j->uuid_bucket;
  359. if (__bch_btree_ptr_invalid(c, k))
  360. return "bad uuid pointer";
  361. bkey_copy(&c->uuid_bucket, k);
  362. uuid_io(c, REQ_OP_READ, k, cl);
  363. if (j->version < BCACHE_JSET_VERSION_UUIDv1) {
  364. struct uuid_entry_v0 *u0 = (void *) c->uuids;
  365. struct uuid_entry *u1 = (void *) c->uuids;
  366. int i;
  367. closure_sync(cl);
  368. /*
  369. * Since the new uuid entry is bigger than the old, we have to
  370. * convert starting at the highest memory address and work down
  371. * in order to do it in place
  372. */
  373. for (i = c->nr_uuids - 1;
  374. i >= 0;
  375. --i) {
  376. memcpy(u1[i].uuid, u0[i].uuid, 16);
  377. memcpy(u1[i].label, u0[i].label, 32);
  378. u1[i].first_reg = u0[i].first_reg;
  379. u1[i].last_reg = u0[i].last_reg;
  380. u1[i].invalidated = u0[i].invalidated;
  381. u1[i].flags = 0;
  382. u1[i].sectors = 0;
  383. }
  384. }
  385. return NULL;
  386. }
  387. static int __uuid_write(struct cache_set *c)
  388. {
  389. BKEY_PADDED(key) k;
  390. struct closure cl;
  391. struct cache *ca = c->cache;
  392. unsigned int size;
  393. closure_init_stack(&cl);
  394. lockdep_assert_held(&bch_register_lock);
  395. if (bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, true))
  396. return 1;
  397. size = meta_bucket_pages(&ca->sb) * PAGE_SECTORS;
  398. SET_KEY_SIZE(&k.key, size);
  399. uuid_io(c, REQ_OP_WRITE, &k.key, &cl);
  400. closure_sync(&cl);
  401. /* Only one bucket used for uuid write */
  402. atomic_long_add(ca->sb.bucket_size, &ca->meta_sectors_written);
  403. bkey_copy(&c->uuid_bucket, &k.key);
  404. bkey_put(c, &k.key);
  405. return 0;
  406. }
  407. int bch_uuid_write(struct cache_set *c)
  408. {
  409. int ret = __uuid_write(c);
  410. if (!ret)
  411. bch_journal_meta(c, NULL);
  412. return ret;
  413. }
  414. static struct uuid_entry *uuid_find(struct cache_set *c, const char *uuid)
  415. {
  416. struct uuid_entry *u;
  417. for (u = c->uuids;
  418. u < c->uuids + c->nr_uuids; u++)
  419. if (!memcmp(u->uuid, uuid, 16))
  420. return u;
  421. return NULL;
  422. }
  423. static struct uuid_entry *uuid_find_empty(struct cache_set *c)
  424. {
  425. static const char zero_uuid[16] __nonstring =
  426. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  427. return uuid_find(c, zero_uuid);
  428. }
  429. /*
  430. * Bucket priorities/gens:
  431. *
  432. * For each bucket, we store on disk its
  433. * 8 bit gen
  434. * 16 bit priority
  435. *
  436. * See alloc.c for an explanation of the gen. The priority is used to implement
  437. * lru (and in the future other) cache replacement policies; for most purposes
  438. * it's just an opaque integer.
  439. *
  440. * The gens and the priorities don't have a whole lot to do with each other, and
  441. * it's actually the gens that must be written out at specific times - it's no
  442. * big deal if the priorities don't get written, if we lose them we just reuse
  443. * buckets in suboptimal order.
  444. *
  445. * On disk they're stored in a packed array, and in as many buckets are required
  446. * to fit them all. The buckets we use to store them form a list; the journal
  447. * header points to the first bucket, the first bucket points to the second
  448. * bucket, et cetera.
  449. *
  450. * This code is used by the allocation code; periodically (whenever it runs out
  451. * of buckets to allocate from) the allocation code will invalidate some
  452. * buckets, but it can't use those buckets until their new gens are safely on
  453. * disk.
  454. */
  455. static void prio_endio(struct bio *bio)
  456. {
  457. struct cache *ca = bio->bi_private;
  458. cache_set_err_on(bio->bi_status, ca->set, "accessing priorities");
  459. bch_bbio_free(bio, ca->set);
  460. closure_put(&ca->prio);
  461. }
  462. static void prio_io(struct cache *ca, uint64_t bucket, blk_opf_t opf)
  463. {
  464. struct closure *cl = &ca->prio;
  465. struct bio *bio = bch_bbio_alloc(ca->set);
  466. closure_init_stack(cl);
  467. bio->bi_iter.bi_sector = bucket * ca->sb.bucket_size;
  468. bio_set_dev(bio, ca->bdev);
  469. bio->bi_iter.bi_size = meta_bucket_bytes(&ca->sb);
  470. bio->bi_end_io = prio_endio;
  471. bio->bi_private = ca;
  472. bio->bi_opf = opf | REQ_SYNC | REQ_META;
  473. bch_bio_map(bio, ca->disk_buckets);
  474. closure_bio_submit(ca->set, bio, &ca->prio);
  475. closure_sync(cl);
  476. }
  477. int bch_prio_write(struct cache *ca, bool wait)
  478. {
  479. int i;
  480. struct bucket *b;
  481. struct closure cl;
  482. pr_debug("free_prio=%zu, free_none=%zu, free_inc=%zu\n",
  483. fifo_used(&ca->free[RESERVE_PRIO]),
  484. fifo_used(&ca->free[RESERVE_NONE]),
  485. fifo_used(&ca->free_inc));
  486. /*
  487. * Pre-check if there are enough free buckets. In the non-blocking
  488. * scenario it's better to fail early rather than starting to allocate
  489. * buckets and do a cleanup later in case of failure.
  490. */
  491. if (!wait) {
  492. size_t avail = fifo_used(&ca->free[RESERVE_PRIO]) +
  493. fifo_used(&ca->free[RESERVE_NONE]);
  494. if (prio_buckets(ca) > avail)
  495. return -ENOMEM;
  496. }
  497. closure_init_stack(&cl);
  498. lockdep_assert_held(&ca->set->bucket_lock);
  499. ca->disk_buckets->seq++;
  500. atomic_long_add(ca->sb.bucket_size * prio_buckets(ca),
  501. &ca->meta_sectors_written);
  502. for (i = prio_buckets(ca) - 1; i >= 0; --i) {
  503. long bucket;
  504. struct prio_set *p = ca->disk_buckets;
  505. struct bucket_disk *d = p->data;
  506. struct bucket_disk *end = d + prios_per_bucket(ca);
  507. for (b = ca->buckets + i * prios_per_bucket(ca);
  508. b < ca->buckets + ca->sb.nbuckets && d < end;
  509. b++, d++) {
  510. d->prio = cpu_to_le16(b->prio);
  511. d->gen = b->gen;
  512. }
  513. p->next_bucket = ca->prio_buckets[i + 1];
  514. p->magic = pset_magic(&ca->sb);
  515. p->csum = bch_crc64(&p->magic, meta_bucket_bytes(&ca->sb) - 8);
  516. bucket = bch_bucket_alloc(ca, RESERVE_PRIO, wait);
  517. BUG_ON(bucket == -1);
  518. mutex_unlock(&ca->set->bucket_lock);
  519. prio_io(ca, bucket, REQ_OP_WRITE);
  520. mutex_lock(&ca->set->bucket_lock);
  521. ca->prio_buckets[i] = bucket;
  522. atomic_dec_bug(&ca->buckets[bucket].pin);
  523. }
  524. mutex_unlock(&ca->set->bucket_lock);
  525. bch_journal_meta(ca->set, &cl);
  526. closure_sync(&cl);
  527. mutex_lock(&ca->set->bucket_lock);
  528. /*
  529. * Don't want the old priorities to get garbage collected until after we
  530. * finish writing the new ones, and they're journalled
  531. */
  532. for (i = 0; i < prio_buckets(ca); i++) {
  533. if (ca->prio_last_buckets[i])
  534. __bch_bucket_free(ca,
  535. &ca->buckets[ca->prio_last_buckets[i]]);
  536. ca->prio_last_buckets[i] = ca->prio_buckets[i];
  537. }
  538. return 0;
  539. }
  540. static int prio_read(struct cache *ca, uint64_t bucket)
  541. {
  542. struct prio_set *p = ca->disk_buckets;
  543. struct bucket_disk *d = p->data + prios_per_bucket(ca), *end = d;
  544. struct bucket *b;
  545. unsigned int bucket_nr = 0;
  546. int ret = -EIO;
  547. for (b = ca->buckets;
  548. b < ca->buckets + ca->sb.nbuckets;
  549. b++, d++) {
  550. if (d == end) {
  551. ca->prio_buckets[bucket_nr] = bucket;
  552. ca->prio_last_buckets[bucket_nr] = bucket;
  553. bucket_nr++;
  554. prio_io(ca, bucket, REQ_OP_READ);
  555. if (p->csum !=
  556. bch_crc64(&p->magic, meta_bucket_bytes(&ca->sb) - 8)) {
  557. pr_warn("bad csum reading priorities\n");
  558. goto out;
  559. }
  560. if (p->magic != pset_magic(&ca->sb)) {
  561. pr_warn("bad magic reading priorities\n");
  562. goto out;
  563. }
  564. bucket = p->next_bucket;
  565. d = p->data;
  566. }
  567. b->prio = le16_to_cpu(d->prio);
  568. b->gen = b->last_gc = d->gen;
  569. }
  570. ret = 0;
  571. out:
  572. return ret;
  573. }
  574. /* Bcache device */
  575. static int open_dev(struct gendisk *disk, blk_mode_t mode)
  576. {
  577. struct bcache_device *d = disk->private_data;
  578. if (test_bit(BCACHE_DEV_CLOSING, &d->flags))
  579. return -ENXIO;
  580. closure_get(&d->cl);
  581. return 0;
  582. }
  583. static void release_dev(struct gendisk *b)
  584. {
  585. struct bcache_device *d = b->private_data;
  586. closure_put(&d->cl);
  587. }
  588. static int ioctl_dev(struct block_device *b, blk_mode_t mode,
  589. unsigned int cmd, unsigned long arg)
  590. {
  591. struct bcache_device *d = b->bd_disk->private_data;
  592. return d->ioctl(d, mode, cmd, arg);
  593. }
  594. static const struct block_device_operations bcache_cached_ops = {
  595. .submit_bio = cached_dev_submit_bio,
  596. .open = open_dev,
  597. .release = release_dev,
  598. .ioctl = ioctl_dev,
  599. .owner = THIS_MODULE,
  600. };
  601. static const struct block_device_operations bcache_flash_ops = {
  602. .submit_bio = flash_dev_submit_bio,
  603. .open = open_dev,
  604. .release = release_dev,
  605. .ioctl = ioctl_dev,
  606. .owner = THIS_MODULE,
  607. };
  608. void bcache_device_stop(struct bcache_device *d)
  609. {
  610. if (!test_and_set_bit(BCACHE_DEV_CLOSING, &d->flags))
  611. /*
  612. * closure_fn set to
  613. * - cached device: cached_dev_flush()
  614. * - flash dev: flash_dev_flush()
  615. */
  616. closure_queue(&d->cl);
  617. }
  618. static void bcache_device_unlink(struct bcache_device *d)
  619. {
  620. lockdep_assert_held(&bch_register_lock);
  621. if (d->c && !test_and_set_bit(BCACHE_DEV_UNLINK_DONE, &d->flags)) {
  622. struct cache *ca = d->c->cache;
  623. sysfs_remove_link(&d->c->kobj, d->name);
  624. sysfs_remove_link(&d->kobj, "cache");
  625. bd_unlink_disk_holder(ca->bdev, d->disk);
  626. }
  627. }
  628. static void bcache_device_link(struct bcache_device *d, struct cache_set *c,
  629. const char *name)
  630. {
  631. struct cache *ca = c->cache;
  632. int ret;
  633. bd_link_disk_holder(ca->bdev, d->disk);
  634. snprintf(d->name, BCACHEDEVNAME_SIZE,
  635. "%s%u", name, d->id);
  636. ret = sysfs_create_link(&d->kobj, &c->kobj, "cache");
  637. if (ret < 0)
  638. pr_err("Couldn't create device -> cache set symlink\n");
  639. ret = sysfs_create_link(&c->kobj, &d->kobj, d->name);
  640. if (ret < 0)
  641. pr_err("Couldn't create cache set -> device symlink\n");
  642. clear_bit(BCACHE_DEV_UNLINK_DONE, &d->flags);
  643. }
  644. static void bcache_device_detach(struct bcache_device *d)
  645. {
  646. lockdep_assert_held(&bch_register_lock);
  647. atomic_dec(&d->c->attached_dev_nr);
  648. if (test_bit(BCACHE_DEV_DETACHING, &d->flags)) {
  649. struct uuid_entry *u = d->c->uuids + d->id;
  650. SET_UUID_FLASH_ONLY(u, 0);
  651. memcpy(u->uuid, invalid_uuid, 16);
  652. u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
  653. bch_uuid_write(d->c);
  654. }
  655. bcache_device_unlink(d);
  656. d->c->devices[d->id] = NULL;
  657. closure_put(&d->c->caching);
  658. d->c = NULL;
  659. }
  660. static void bcache_device_attach(struct bcache_device *d, struct cache_set *c,
  661. unsigned int id)
  662. {
  663. d->id = id;
  664. d->c = c;
  665. c->devices[id] = d;
  666. if (id >= c->devices_max_used)
  667. c->devices_max_used = id + 1;
  668. closure_get(&c->caching);
  669. }
  670. static inline int first_minor_to_idx(int first_minor)
  671. {
  672. return (first_minor/BCACHE_MINORS);
  673. }
  674. static inline int idx_to_first_minor(int idx)
  675. {
  676. return (idx * BCACHE_MINORS);
  677. }
  678. static void bcache_device_free(struct bcache_device *d)
  679. {
  680. struct gendisk *disk = d->disk;
  681. lockdep_assert_held(&bch_register_lock);
  682. if (disk)
  683. pr_info("%s stopped\n", disk->disk_name);
  684. else
  685. pr_err("bcache device (NULL gendisk) stopped\n");
  686. if (d->c)
  687. bcache_device_detach(d);
  688. if (disk) {
  689. ida_free(&bcache_device_idx,
  690. first_minor_to_idx(disk->first_minor));
  691. put_disk(disk);
  692. }
  693. bioset_exit(&d->bio_split);
  694. bioset_exit(&d->bio_detached);
  695. kvfree(d->full_dirty_stripes);
  696. kvfree(d->stripe_sectors_dirty);
  697. closure_debug_destroy(&d->cl);
  698. }
  699. static int bcache_device_init(struct bcache_device *d, unsigned int block_size,
  700. sector_t sectors, struct block_device *cached_bdev,
  701. const struct block_device_operations *ops)
  702. {
  703. const size_t max_stripes = min_t(size_t, INT_MAX,
  704. SIZE_MAX / sizeof(atomic_t));
  705. struct queue_limits lim = {
  706. .max_hw_sectors = UINT_MAX,
  707. .max_sectors = UINT_MAX,
  708. .max_segment_size = UINT_MAX,
  709. .max_segments = BIO_MAX_VECS,
  710. .max_hw_discard_sectors = UINT_MAX,
  711. .io_min = block_size,
  712. .logical_block_size = block_size,
  713. .physical_block_size = block_size,
  714. .features = BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA,
  715. };
  716. uint64_t n;
  717. int idx;
  718. if (cached_bdev) {
  719. d->stripe_size = bdev_io_opt(cached_bdev) >> SECTOR_SHIFT;
  720. lim.io_opt = umax(block_size, bdev_io_opt(cached_bdev));
  721. }
  722. if (!d->stripe_size)
  723. d->stripe_size = 1 << 31;
  724. else if (d->stripe_size < BCH_MIN_STRIPE_SZ)
  725. d->stripe_size = roundup(BCH_MIN_STRIPE_SZ, d->stripe_size);
  726. n = DIV_ROUND_UP_ULL(sectors, d->stripe_size);
  727. if (!n || n > max_stripes) {
  728. pr_err("nr_stripes too large or invalid: %llu (start sector beyond end of disk?)\n",
  729. n);
  730. return -ENOMEM;
  731. }
  732. d->nr_stripes = n;
  733. n = d->nr_stripes * sizeof(atomic_t);
  734. d->stripe_sectors_dirty = kvzalloc(n, GFP_KERNEL);
  735. if (!d->stripe_sectors_dirty)
  736. return -ENOMEM;
  737. n = BITS_TO_LONGS(d->nr_stripes) * sizeof(unsigned long);
  738. d->full_dirty_stripes = kvzalloc(n, GFP_KERNEL);
  739. if (!d->full_dirty_stripes)
  740. goto out_free_stripe_sectors_dirty;
  741. idx = ida_alloc_max(&bcache_device_idx, BCACHE_DEVICE_IDX_MAX - 1,
  742. GFP_KERNEL);
  743. if (idx < 0)
  744. goto out_free_full_dirty_stripes;
  745. if (bioset_init(&d->bio_split, 4, offsetof(struct bbio, bio),
  746. BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER))
  747. goto out_ida_remove;
  748. if (bioset_init(&d->bio_detached, 4,
  749. offsetof(struct detached_dev_io_private, bio),
  750. BIOSET_NEED_BVECS|BIOSET_NEED_RESCUER))
  751. goto out_bioset_split_exit;
  752. if (lim.logical_block_size > PAGE_SIZE && cached_bdev) {
  753. /*
  754. * This should only happen with BCACHE_SB_VERSION_BDEV.
  755. * Block/page size is checked for BCACHE_SB_VERSION_CDEV.
  756. */
  757. pr_info("bcache%i: sb/logical block size (%u) greater than page size (%lu) falling back to device logical block size (%u)\n",
  758. idx, lim.logical_block_size,
  759. PAGE_SIZE, bdev_logical_block_size(cached_bdev));
  760. /* This also adjusts physical block size/min io size if needed */
  761. lim.logical_block_size = bdev_logical_block_size(cached_bdev);
  762. }
  763. d->disk = blk_alloc_disk(&lim, NUMA_NO_NODE);
  764. if (IS_ERR(d->disk))
  765. goto out_bioset_detach_exit;
  766. set_capacity(d->disk, sectors);
  767. snprintf(d->disk->disk_name, DISK_NAME_LEN, "bcache%i", idx);
  768. d->disk->major = bcache_major;
  769. d->disk->first_minor = idx_to_first_minor(idx);
  770. d->disk->minors = BCACHE_MINORS;
  771. d->disk->fops = ops;
  772. d->disk->private_data = d;
  773. return 0;
  774. out_bioset_detach_exit:
  775. bioset_exit(&d->bio_detached);
  776. out_bioset_split_exit:
  777. bioset_exit(&d->bio_split);
  778. out_ida_remove:
  779. ida_free(&bcache_device_idx, idx);
  780. out_free_full_dirty_stripes:
  781. kvfree(d->full_dirty_stripes);
  782. out_free_stripe_sectors_dirty:
  783. kvfree(d->stripe_sectors_dirty);
  784. return -ENOMEM;
  785. }
  786. /* Cached device */
  787. static void calc_cached_dev_sectors(struct cache_set *c)
  788. {
  789. uint64_t sectors = 0;
  790. struct cached_dev *dc;
  791. list_for_each_entry(dc, &c->cached_devs, list)
  792. sectors += bdev_nr_sectors(dc->bdev);
  793. c->cached_dev_sectors = sectors;
  794. }
  795. #define BACKING_DEV_OFFLINE_TIMEOUT 5
  796. static int cached_dev_status_update(void *arg)
  797. {
  798. struct cached_dev *dc = arg;
  799. struct request_queue *q;
  800. /*
  801. * If this delayed worker is stopping outside, directly quit here.
  802. * dc->io_disable might be set via sysfs interface, so check it
  803. * here too.
  804. */
  805. while (!kthread_should_stop() && !dc->io_disable) {
  806. q = bdev_get_queue(dc->bdev);
  807. if (blk_queue_dying(q))
  808. dc->offline_seconds++;
  809. else
  810. dc->offline_seconds = 0;
  811. if (dc->offline_seconds >= BACKING_DEV_OFFLINE_TIMEOUT) {
  812. pr_err("%pg: device offline for %d seconds\n",
  813. dc->bdev,
  814. BACKING_DEV_OFFLINE_TIMEOUT);
  815. pr_err("%s: disable I/O request due to backing device offline\n",
  816. dc->disk.name);
  817. dc->io_disable = true;
  818. /* let others know earlier that io_disable is true */
  819. smp_mb();
  820. bcache_device_stop(&dc->disk);
  821. break;
  822. }
  823. schedule_timeout_interruptible(HZ);
  824. }
  825. wait_for_kthread_stop();
  826. return 0;
  827. }
  828. int bch_cached_dev_run(struct cached_dev *dc)
  829. {
  830. int ret = 0;
  831. struct bcache_device *d = &dc->disk;
  832. char *buf = kmemdup_nul(dc->sb.label, SB_LABEL_SIZE, GFP_KERNEL);
  833. char *env[] = {
  834. "DRIVER=bcache",
  835. kasprintf(GFP_KERNEL, "CACHED_UUID=%pU", dc->sb.uuid),
  836. kasprintf(GFP_KERNEL, "CACHED_LABEL=%s", buf ? : ""),
  837. NULL,
  838. };
  839. if (dc->io_disable) {
  840. pr_err("I/O disabled on cached dev %pg\n", dc->bdev);
  841. ret = -EIO;
  842. goto out;
  843. }
  844. if (atomic_xchg(&dc->running, 1)) {
  845. pr_info("cached dev %pg is running already\n", dc->bdev);
  846. ret = -EBUSY;
  847. goto out;
  848. }
  849. if (!d->c &&
  850. BDEV_STATE(&dc->sb) != BDEV_STATE_NONE) {
  851. struct closure cl;
  852. closure_init_stack(&cl);
  853. SET_BDEV_STATE(&dc->sb, BDEV_STATE_STALE);
  854. bch_write_bdev_super(dc, &cl);
  855. closure_sync(&cl);
  856. }
  857. ret = add_disk(d->disk);
  858. if (ret)
  859. goto out;
  860. bd_link_disk_holder(dc->bdev, dc->disk.disk);
  861. /*
  862. * won't show up in the uevent file, use udevadm monitor -e instead
  863. * only class / kset properties are persistent
  864. */
  865. kobject_uevent_env(&disk_to_dev(d->disk)->kobj, KOBJ_CHANGE, env);
  866. if (sysfs_create_link(&d->kobj, &disk_to_dev(d->disk)->kobj, "dev") ||
  867. sysfs_create_link(&disk_to_dev(d->disk)->kobj,
  868. &d->kobj, "bcache")) {
  869. pr_err("Couldn't create bcache dev <-> disk sysfs symlinks\n");
  870. ret = -ENOMEM;
  871. goto out;
  872. }
  873. dc->status_update_thread = kthread_run(cached_dev_status_update,
  874. dc, "bcache_status_update");
  875. if (IS_ERR(dc->status_update_thread)) {
  876. pr_warn("failed to create bcache_status_update kthread, continue to run without monitoring backing device status\n");
  877. }
  878. out:
  879. kfree(env[1]);
  880. kfree(env[2]);
  881. kfree(buf);
  882. return ret;
  883. }
  884. /*
  885. * If BCACHE_DEV_RATE_DW_RUNNING is set, it means routine of the delayed
  886. * work dc->writeback_rate_update is running. Wait until the routine
  887. * quits (BCACHE_DEV_RATE_DW_RUNNING is clear), then continue to
  888. * cancel it. If BCACHE_DEV_RATE_DW_RUNNING is not clear after time_out
  889. * seconds, give up waiting here and continue to cancel it too.
  890. */
  891. static void cancel_writeback_rate_update_dwork(struct cached_dev *dc)
  892. {
  893. int time_out = WRITEBACK_RATE_UPDATE_SECS_MAX * HZ;
  894. do {
  895. if (!test_bit(BCACHE_DEV_RATE_DW_RUNNING,
  896. &dc->disk.flags))
  897. break;
  898. time_out--;
  899. schedule_timeout_interruptible(1);
  900. } while (time_out > 0);
  901. if (time_out == 0)
  902. pr_warn("give up waiting for dc->writeback_write_update to quit\n");
  903. cancel_delayed_work_sync(&dc->writeback_rate_update);
  904. }
  905. static void cached_dev_detach_finish(struct work_struct *w)
  906. {
  907. struct cached_dev *dc = container_of(w, struct cached_dev, detach);
  908. struct cache_set *c = dc->disk.c;
  909. BUG_ON(!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags));
  910. BUG_ON(refcount_read(&dc->count));
  911. if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
  912. cancel_writeback_rate_update_dwork(dc);
  913. if (!IS_ERR_OR_NULL(dc->writeback_thread)) {
  914. kthread_stop(dc->writeback_thread);
  915. dc->writeback_thread = NULL;
  916. }
  917. mutex_lock(&bch_register_lock);
  918. bcache_device_detach(&dc->disk);
  919. list_move(&dc->list, &uncached_devices);
  920. calc_cached_dev_sectors(c);
  921. clear_bit(BCACHE_DEV_DETACHING, &dc->disk.flags);
  922. clear_bit(BCACHE_DEV_UNLINK_DONE, &dc->disk.flags);
  923. mutex_unlock(&bch_register_lock);
  924. pr_info("Caching disabled for %pg\n", dc->bdev);
  925. /* Drop ref we took in cached_dev_detach() */
  926. closure_put(&dc->disk.cl);
  927. }
  928. void bch_cached_dev_detach(struct cached_dev *dc)
  929. {
  930. lockdep_assert_held(&bch_register_lock);
  931. if (test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
  932. return;
  933. if (test_and_set_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
  934. return;
  935. /*
  936. * Block the device from being closed and freed until we're finished
  937. * detaching
  938. */
  939. closure_get(&dc->disk.cl);
  940. bch_writeback_queue(dc);
  941. cached_dev_put(dc);
  942. }
  943. int bch_cached_dev_attach(struct cached_dev *dc, struct cache_set *c,
  944. uint8_t *set_uuid)
  945. {
  946. uint32_t rtime = cpu_to_le32((u32)ktime_get_real_seconds());
  947. struct uuid_entry *u;
  948. struct cached_dev *exist_dc, *t;
  949. int ret = 0;
  950. if ((set_uuid && memcmp(set_uuid, c->set_uuid, 16)) ||
  951. (!set_uuid && memcmp(dc->sb.set_uuid, c->set_uuid, 16)))
  952. return -ENOENT;
  953. if (dc->disk.c) {
  954. pr_err("Can't attach %pg: already attached\n", dc->bdev);
  955. return -EINVAL;
  956. }
  957. if (test_bit(CACHE_SET_STOPPING, &c->flags)) {
  958. pr_err("Can't attach %pg: shutting down\n", dc->bdev);
  959. return -EINVAL;
  960. }
  961. if (dc->sb.block_size < c->cache->sb.block_size) {
  962. /* Will die */
  963. pr_err("Couldn't attach %pg: block size less than set's block size\n",
  964. dc->bdev);
  965. return -EINVAL;
  966. }
  967. /* Check whether already attached */
  968. list_for_each_entry_safe(exist_dc, t, &c->cached_devs, list) {
  969. if (!memcmp(dc->sb.uuid, exist_dc->sb.uuid, 16)) {
  970. pr_err("Tried to attach %pg but duplicate UUID already attached\n",
  971. dc->bdev);
  972. return -EINVAL;
  973. }
  974. }
  975. u = uuid_find(c, dc->sb.uuid);
  976. if (u &&
  977. (BDEV_STATE(&dc->sb) == BDEV_STATE_STALE ||
  978. BDEV_STATE(&dc->sb) == BDEV_STATE_NONE)) {
  979. memcpy(u->uuid, invalid_uuid, 16);
  980. u->invalidated = cpu_to_le32((u32)ktime_get_real_seconds());
  981. u = NULL;
  982. }
  983. if (!u) {
  984. if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
  985. pr_err("Couldn't find uuid for %pg in set\n", dc->bdev);
  986. return -ENOENT;
  987. }
  988. u = uuid_find_empty(c);
  989. if (!u) {
  990. pr_err("Not caching %pg, no room for UUID\n", dc->bdev);
  991. return -EINVAL;
  992. }
  993. }
  994. /*
  995. * Deadlocks since we're called via sysfs...
  996. * sysfs_remove_file(&dc->kobj, &sysfs_attach);
  997. */
  998. if (bch_is_zero(u->uuid, 16)) {
  999. struct closure cl;
  1000. closure_init_stack(&cl);
  1001. memcpy(u->uuid, dc->sb.uuid, 16);
  1002. memcpy(u->label, dc->sb.label, SB_LABEL_SIZE);
  1003. u->first_reg = u->last_reg = rtime;
  1004. bch_uuid_write(c);
  1005. memcpy(dc->sb.set_uuid, c->set_uuid, 16);
  1006. SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
  1007. bch_write_bdev_super(dc, &cl);
  1008. closure_sync(&cl);
  1009. } else {
  1010. u->last_reg = rtime;
  1011. bch_uuid_write(c);
  1012. }
  1013. bcache_device_attach(&dc->disk, c, u - c->uuids);
  1014. list_move(&dc->list, &c->cached_devs);
  1015. calc_cached_dev_sectors(c);
  1016. /*
  1017. * dc->c must be set before dc->count != 0 - paired with the mb in
  1018. * cached_dev_get()
  1019. */
  1020. smp_wmb();
  1021. refcount_set(&dc->count, 1);
  1022. /* Block writeback thread, but spawn it */
  1023. down_write(&dc->writeback_lock);
  1024. if (bch_cached_dev_writeback_start(dc)) {
  1025. up_write(&dc->writeback_lock);
  1026. pr_err("Couldn't start writeback facilities for %s\n",
  1027. dc->disk.disk->disk_name);
  1028. return -ENOMEM;
  1029. }
  1030. if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
  1031. atomic_set(&dc->has_dirty, 1);
  1032. bch_writeback_queue(dc);
  1033. }
  1034. bch_sectors_dirty_init(&dc->disk);
  1035. ret = bch_cached_dev_run(dc);
  1036. if (ret && (ret != -EBUSY)) {
  1037. up_write(&dc->writeback_lock);
  1038. /*
  1039. * bch_register_lock is held, bcache_device_stop() is not
  1040. * able to be directly called. The kthread and kworker
  1041. * created previously in bch_cached_dev_writeback_start()
  1042. * have to be stopped manually here.
  1043. */
  1044. kthread_stop(dc->writeback_thread);
  1045. cancel_writeback_rate_update_dwork(dc);
  1046. pr_err("Couldn't run cached device %pg\n", dc->bdev);
  1047. return ret;
  1048. }
  1049. bcache_device_link(&dc->disk, c, "bdev");
  1050. atomic_inc(&c->attached_dev_nr);
  1051. if (bch_has_feature_obso_large_bucket(&(c->cache->sb))) {
  1052. pr_err("The obsoleted large bucket layout is unsupported, set the bcache device into read-only\n");
  1053. pr_err("Please update to the latest bcache-tools to create the cache device\n");
  1054. set_disk_ro(dc->disk.disk, 1);
  1055. }
  1056. /* Allow the writeback thread to proceed */
  1057. up_write(&dc->writeback_lock);
  1058. pr_info("Caching %pg as %s on set %pU\n",
  1059. dc->bdev,
  1060. dc->disk.disk->disk_name,
  1061. dc->disk.c->set_uuid);
  1062. return 0;
  1063. }
  1064. /* when dc->disk.kobj released */
  1065. void bch_cached_dev_release(struct kobject *kobj)
  1066. {
  1067. struct cached_dev *dc = container_of(kobj, struct cached_dev,
  1068. disk.kobj);
  1069. kfree(dc);
  1070. module_put(THIS_MODULE);
  1071. }
  1072. static CLOSURE_CALLBACK(cached_dev_free)
  1073. {
  1074. closure_type(dc, struct cached_dev, disk.cl);
  1075. if (test_and_clear_bit(BCACHE_DEV_WB_RUNNING, &dc->disk.flags))
  1076. cancel_writeback_rate_update_dwork(dc);
  1077. if (!IS_ERR_OR_NULL(dc->writeback_thread))
  1078. kthread_stop(dc->writeback_thread);
  1079. if (!IS_ERR_OR_NULL(dc->status_update_thread))
  1080. kthread_stop(dc->status_update_thread);
  1081. mutex_lock(&bch_register_lock);
  1082. if (atomic_read(&dc->running)) {
  1083. bd_unlink_disk_holder(dc->bdev, dc->disk.disk);
  1084. del_gendisk(dc->disk.disk);
  1085. }
  1086. bcache_device_free(&dc->disk);
  1087. list_del(&dc->list);
  1088. mutex_unlock(&bch_register_lock);
  1089. if (dc->sb_disk)
  1090. folio_put(virt_to_folio(dc->sb_disk));
  1091. if (dc->bdev_file)
  1092. fput(dc->bdev_file);
  1093. wake_up(&unregister_wait);
  1094. kobject_put(&dc->disk.kobj);
  1095. }
  1096. static CLOSURE_CALLBACK(cached_dev_flush)
  1097. {
  1098. closure_type(dc, struct cached_dev, disk.cl);
  1099. struct bcache_device *d = &dc->disk;
  1100. mutex_lock(&bch_register_lock);
  1101. bcache_device_unlink(d);
  1102. mutex_unlock(&bch_register_lock);
  1103. bch_cache_accounting_destroy(&dc->accounting);
  1104. kobject_del(&d->kobj);
  1105. continue_at(cl, cached_dev_free, system_percpu_wq);
  1106. }
  1107. static int cached_dev_init(struct cached_dev *dc, unsigned int block_size)
  1108. {
  1109. int ret;
  1110. struct io *io;
  1111. struct request_queue *q = bdev_get_queue(dc->bdev);
  1112. __module_get(THIS_MODULE);
  1113. INIT_LIST_HEAD(&dc->list);
  1114. closure_init(&dc->disk.cl, NULL);
  1115. set_closure_fn(&dc->disk.cl, cached_dev_flush, system_percpu_wq);
  1116. kobject_init(&dc->disk.kobj, &bch_cached_dev_ktype);
  1117. INIT_WORK(&dc->detach, cached_dev_detach_finish);
  1118. sema_init(&dc->sb_write_mutex, 1);
  1119. INIT_LIST_HEAD(&dc->io_lru);
  1120. spin_lock_init(&dc->io_lock);
  1121. bch_cache_accounting_init(&dc->accounting, &dc->disk.cl);
  1122. dc->sequential_cutoff = 4 << 20;
  1123. for (io = dc->io; io < dc->io + RECENT_IO; io++) {
  1124. list_add(&io->lru, &dc->io_lru);
  1125. hlist_add_head(&io->hash, dc->io_hash + RECENT_IO);
  1126. }
  1127. if (bdev_io_opt(dc->bdev))
  1128. dc->partial_stripes_expensive = !!(q->limits.features &
  1129. BLK_FEAT_RAID_PARTIAL_STRIPES_EXPENSIVE);
  1130. ret = bcache_device_init(&dc->disk, block_size,
  1131. bdev_nr_sectors(dc->bdev) - dc->sb.data_offset,
  1132. dc->bdev, &bcache_cached_ops);
  1133. if (ret)
  1134. return ret;
  1135. atomic_set(&dc->io_errors, 0);
  1136. dc->io_disable = false;
  1137. dc->error_limit = DEFAULT_CACHED_DEV_ERROR_LIMIT;
  1138. /* default to auto */
  1139. dc->stop_when_cache_set_failed = BCH_CACHED_DEV_STOP_AUTO;
  1140. bch_cached_dev_request_init(dc);
  1141. bch_cached_dev_writeback_init(dc);
  1142. return 0;
  1143. }
  1144. /* Cached device - bcache superblock */
  1145. static int register_bdev(struct cache_sb *sb, struct cache_sb_disk *sb_disk,
  1146. struct file *bdev_file,
  1147. struct cached_dev *dc)
  1148. {
  1149. const char *err = "cannot allocate memory";
  1150. struct cache_set *c;
  1151. int ret = -ENOMEM;
  1152. memcpy(&dc->sb, sb, sizeof(struct cache_sb));
  1153. dc->bdev_file = bdev_file;
  1154. dc->bdev = file_bdev(bdev_file);
  1155. dc->sb_disk = sb_disk;
  1156. if (cached_dev_init(dc, sb->block_size << 9))
  1157. goto err;
  1158. err = "error creating kobject";
  1159. if (kobject_add(&dc->disk.kobj, bdev_kobj(dc->bdev), "bcache"))
  1160. goto err;
  1161. if (bch_cache_accounting_add_kobjs(&dc->accounting, &dc->disk.kobj))
  1162. goto err;
  1163. pr_info("registered backing device %pg\n", dc->bdev);
  1164. list_add(&dc->list, &uncached_devices);
  1165. /* attach to a matched cache set if it exists */
  1166. list_for_each_entry(c, &bch_cache_sets, list)
  1167. bch_cached_dev_attach(dc, c, NULL);
  1168. if (BDEV_STATE(&dc->sb) == BDEV_STATE_NONE ||
  1169. BDEV_STATE(&dc->sb) == BDEV_STATE_STALE) {
  1170. err = "failed to run cached device";
  1171. ret = bch_cached_dev_run(dc);
  1172. if (ret)
  1173. goto err;
  1174. }
  1175. return 0;
  1176. err:
  1177. pr_notice("error %pg: %s\n", dc->bdev, err);
  1178. bcache_device_stop(&dc->disk);
  1179. return ret;
  1180. }
  1181. /* Flash only volumes */
  1182. /* When d->kobj released */
  1183. void bch_flash_dev_release(struct kobject *kobj)
  1184. {
  1185. struct bcache_device *d = container_of(kobj, struct bcache_device,
  1186. kobj);
  1187. kfree(d);
  1188. }
  1189. static CLOSURE_CALLBACK(flash_dev_free)
  1190. {
  1191. closure_type(d, struct bcache_device, cl);
  1192. mutex_lock(&bch_register_lock);
  1193. atomic_long_sub(bcache_dev_sectors_dirty(d),
  1194. &d->c->flash_dev_dirty_sectors);
  1195. del_gendisk(d->disk);
  1196. bcache_device_free(d);
  1197. mutex_unlock(&bch_register_lock);
  1198. kobject_put(&d->kobj);
  1199. }
  1200. static CLOSURE_CALLBACK(flash_dev_flush)
  1201. {
  1202. closure_type(d, struct bcache_device, cl);
  1203. mutex_lock(&bch_register_lock);
  1204. bcache_device_unlink(d);
  1205. mutex_unlock(&bch_register_lock);
  1206. kobject_del(&d->kobj);
  1207. continue_at(cl, flash_dev_free, system_percpu_wq);
  1208. }
  1209. static int flash_dev_run(struct cache_set *c, struct uuid_entry *u)
  1210. {
  1211. int err = -ENOMEM;
  1212. struct bcache_device *d = kzalloc_obj(struct bcache_device);
  1213. if (!d)
  1214. goto err_ret;
  1215. closure_init(&d->cl, NULL);
  1216. set_closure_fn(&d->cl, flash_dev_flush, system_percpu_wq);
  1217. kobject_init(&d->kobj, &bch_flash_dev_ktype);
  1218. if (bcache_device_init(d, block_bytes(c->cache), u->sectors,
  1219. NULL, &bcache_flash_ops))
  1220. goto err;
  1221. bcache_device_attach(d, c, u - c->uuids);
  1222. bch_sectors_dirty_init(d);
  1223. bch_flash_dev_request_init(d);
  1224. err = add_disk(d->disk);
  1225. if (err)
  1226. goto err;
  1227. err = kobject_add(&d->kobj, &disk_to_dev(d->disk)->kobj, "bcache");
  1228. if (err)
  1229. goto err;
  1230. bcache_device_link(d, c, "volume");
  1231. if (bch_has_feature_obso_large_bucket(&c->cache->sb)) {
  1232. pr_err("The obsoleted large bucket layout is unsupported, set the bcache device into read-only\n");
  1233. pr_err("Please update to the latest bcache-tools to create the cache device\n");
  1234. set_disk_ro(d->disk, 1);
  1235. }
  1236. return 0;
  1237. err:
  1238. kobject_put(&d->kobj);
  1239. err_ret:
  1240. return err;
  1241. }
  1242. static int flash_devs_run(struct cache_set *c)
  1243. {
  1244. int ret = 0;
  1245. struct uuid_entry *u;
  1246. for (u = c->uuids;
  1247. u < c->uuids + c->nr_uuids && !ret;
  1248. u++)
  1249. if (UUID_FLASH_ONLY(u))
  1250. ret = flash_dev_run(c, u);
  1251. return ret;
  1252. }
  1253. int bch_flash_dev_create(struct cache_set *c, uint64_t size)
  1254. {
  1255. struct uuid_entry *u;
  1256. if (test_bit(CACHE_SET_STOPPING, &c->flags))
  1257. return -EINTR;
  1258. if (!test_bit(CACHE_SET_RUNNING, &c->flags))
  1259. return -EPERM;
  1260. u = uuid_find_empty(c);
  1261. if (!u) {
  1262. pr_err("Can't create volume, no room for UUID\n");
  1263. return -EINVAL;
  1264. }
  1265. get_random_bytes(u->uuid, 16);
  1266. memset(u->label, 0, 32);
  1267. u->first_reg = u->last_reg = cpu_to_le32((u32)ktime_get_real_seconds());
  1268. SET_UUID_FLASH_ONLY(u, 1);
  1269. u->sectors = size >> 9;
  1270. bch_uuid_write(c);
  1271. return flash_dev_run(c, u);
  1272. }
  1273. bool bch_cached_dev_error(struct cached_dev *dc)
  1274. {
  1275. if (!dc || test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
  1276. return false;
  1277. dc->io_disable = true;
  1278. /* make others know io_disable is true earlier */
  1279. smp_mb();
  1280. pr_err("stop %s: too many IO errors on backing device %pg\n",
  1281. dc->disk.disk->disk_name, dc->bdev);
  1282. bcache_device_stop(&dc->disk);
  1283. return true;
  1284. }
  1285. /* Cache set */
  1286. __printf(2, 3)
  1287. bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...)
  1288. {
  1289. struct va_format vaf;
  1290. va_list args;
  1291. if (c->on_error != ON_ERROR_PANIC &&
  1292. test_bit(CACHE_SET_STOPPING, &c->flags))
  1293. return false;
  1294. if (test_and_set_bit(CACHE_SET_IO_DISABLE, &c->flags))
  1295. pr_info("CACHE_SET_IO_DISABLE already set\n");
  1296. /*
  1297. * XXX: we can be called from atomic context
  1298. * acquire_console_sem();
  1299. */
  1300. va_start(args, fmt);
  1301. vaf.fmt = fmt;
  1302. vaf.va = &args;
  1303. pr_err("error on %pU: %pV, disabling caching\n",
  1304. c->set_uuid, &vaf);
  1305. va_end(args);
  1306. if (c->on_error == ON_ERROR_PANIC)
  1307. panic("panic forced after error\n");
  1308. bch_cache_set_unregister(c);
  1309. return true;
  1310. }
  1311. /* When c->kobj released */
  1312. void bch_cache_set_release(struct kobject *kobj)
  1313. {
  1314. struct cache_set *c = container_of(kobj, struct cache_set, kobj);
  1315. kfree(c);
  1316. module_put(THIS_MODULE);
  1317. }
  1318. static CLOSURE_CALLBACK(cache_set_free)
  1319. {
  1320. closure_type(c, struct cache_set, cl);
  1321. struct cache *ca;
  1322. debugfs_remove(c->debug);
  1323. bch_open_buckets_free(c);
  1324. bch_btree_cache_free(c);
  1325. bch_journal_free(c);
  1326. mutex_lock(&bch_register_lock);
  1327. bch_bset_sort_state_free(&c->sort);
  1328. free_pages((unsigned long) c->uuids, ilog2(meta_bucket_pages(&c->cache->sb)));
  1329. ca = c->cache;
  1330. if (ca) {
  1331. ca->set = NULL;
  1332. c->cache = NULL;
  1333. kobject_put(&ca->kobj);
  1334. }
  1335. if (c->moving_gc_wq)
  1336. destroy_workqueue(c->moving_gc_wq);
  1337. bioset_exit(&c->bio_split);
  1338. mempool_exit(&c->fill_iter);
  1339. mempool_exit(&c->bio_meta);
  1340. mempool_exit(&c->search);
  1341. kfree(c->devices);
  1342. list_del(&c->list);
  1343. mutex_unlock(&bch_register_lock);
  1344. pr_info("Cache set %pU unregistered\n", c->set_uuid);
  1345. wake_up(&unregister_wait);
  1346. closure_debug_destroy(&c->cl);
  1347. kobject_put(&c->kobj);
  1348. }
  1349. static CLOSURE_CALLBACK(cache_set_flush)
  1350. {
  1351. closure_type(c, struct cache_set, caching);
  1352. struct cache *ca = c->cache;
  1353. struct btree *b;
  1354. bch_cache_accounting_destroy(&c->accounting);
  1355. kobject_put(&c->internal);
  1356. kobject_del(&c->kobj);
  1357. if (!IS_ERR_OR_NULL(c->gc_thread))
  1358. kthread_stop(c->gc_thread);
  1359. if (!IS_ERR_OR_NULL(c->root))
  1360. list_add(&c->root->list, &c->btree_cache);
  1361. /*
  1362. * Avoid flushing cached nodes if cache set is retiring
  1363. * due to too many I/O errors detected.
  1364. */
  1365. if (!test_bit(CACHE_SET_IO_DISABLE, &c->flags))
  1366. list_for_each_entry(b, &c->btree_cache, list) {
  1367. mutex_lock(&b->write_lock);
  1368. if (btree_node_dirty(b))
  1369. __bch_btree_node_write(b, NULL);
  1370. mutex_unlock(&b->write_lock);
  1371. }
  1372. /*
  1373. * If the register_cache_set() call to bch_cache_set_alloc() failed,
  1374. * ca has not been assigned a value and return error.
  1375. * So we need check ca is not NULL during bch_cache_set_unregister().
  1376. */
  1377. if (ca && ca->alloc_thread)
  1378. kthread_stop(ca->alloc_thread);
  1379. if (c->journal.cur) {
  1380. cancel_delayed_work_sync(&c->journal.work);
  1381. /* flush last journal entry if needed */
  1382. c->journal.work.work.func(&c->journal.work.work);
  1383. }
  1384. closure_return(cl);
  1385. }
  1386. /*
  1387. * This function is only called when CACHE_SET_IO_DISABLE is set, which means
  1388. * cache set is unregistering due to too many I/O errors. In this condition,
  1389. * the bcache device might be stopped, it depends on stop_when_cache_set_failed
  1390. * value and whether the broken cache has dirty data:
  1391. *
  1392. * dc->stop_when_cache_set_failed dc->has_dirty stop bcache device
  1393. * BCH_CACHED_STOP_AUTO 0 NO
  1394. * BCH_CACHED_STOP_AUTO 1 YES
  1395. * BCH_CACHED_DEV_STOP_ALWAYS 0 YES
  1396. * BCH_CACHED_DEV_STOP_ALWAYS 1 YES
  1397. *
  1398. * The expected behavior is, if stop_when_cache_set_failed is configured to
  1399. * "auto" via sysfs interface, the bcache device will not be stopped if the
  1400. * backing device is clean on the broken cache device.
  1401. */
  1402. static void conditional_stop_bcache_device(struct cache_set *c,
  1403. struct bcache_device *d,
  1404. struct cached_dev *dc)
  1405. {
  1406. if (dc->stop_when_cache_set_failed == BCH_CACHED_DEV_STOP_ALWAYS) {
  1407. pr_warn("stop_when_cache_set_failed of %s is \"always\", stop it for failed cache set %pU.\n",
  1408. d->disk->disk_name, c->set_uuid);
  1409. bcache_device_stop(d);
  1410. } else if (atomic_read(&dc->has_dirty)) {
  1411. /*
  1412. * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
  1413. * and dc->has_dirty == 1
  1414. */
  1415. pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is dirty, stop it to avoid potential data corruption.\n",
  1416. d->disk->disk_name);
  1417. /*
  1418. * There might be a small time gap that cache set is
  1419. * released but bcache device is not. Inside this time
  1420. * gap, regular I/O requests will directly go into
  1421. * backing device as no cache set attached to. This
  1422. * behavior may also introduce potential inconsistence
  1423. * data in writeback mode while cache is dirty.
  1424. * Therefore before calling bcache_device_stop() due
  1425. * to a broken cache device, dc->io_disable should be
  1426. * explicitly set to true.
  1427. */
  1428. dc->io_disable = true;
  1429. /* make others know io_disable is true earlier */
  1430. smp_mb();
  1431. bcache_device_stop(d);
  1432. } else {
  1433. /*
  1434. * dc->stop_when_cache_set_failed == BCH_CACHED_STOP_AUTO
  1435. * and dc->has_dirty == 0
  1436. */
  1437. pr_warn("stop_when_cache_set_failed of %s is \"auto\" and cache is clean, keep it alive.\n",
  1438. d->disk->disk_name);
  1439. }
  1440. }
  1441. static CLOSURE_CALLBACK(__cache_set_unregister)
  1442. {
  1443. closure_type(c, struct cache_set, caching);
  1444. struct cached_dev *dc;
  1445. struct bcache_device *d;
  1446. size_t i;
  1447. mutex_lock(&bch_register_lock);
  1448. for (i = 0; i < c->devices_max_used; i++) {
  1449. d = c->devices[i];
  1450. if (!d)
  1451. continue;
  1452. if (!UUID_FLASH_ONLY(&c->uuids[i]) &&
  1453. test_bit(CACHE_SET_UNREGISTERING, &c->flags)) {
  1454. dc = container_of(d, struct cached_dev, disk);
  1455. bch_cached_dev_detach(dc);
  1456. if (test_bit(CACHE_SET_IO_DISABLE, &c->flags))
  1457. conditional_stop_bcache_device(c, d, dc);
  1458. } else {
  1459. bcache_device_stop(d);
  1460. }
  1461. }
  1462. mutex_unlock(&bch_register_lock);
  1463. continue_at(cl, cache_set_flush, system_percpu_wq);
  1464. }
  1465. void bch_cache_set_stop(struct cache_set *c)
  1466. {
  1467. if (!test_and_set_bit(CACHE_SET_STOPPING, &c->flags))
  1468. /* closure_fn set to __cache_set_unregister() */
  1469. closure_queue(&c->caching);
  1470. }
  1471. void bch_cache_set_unregister(struct cache_set *c)
  1472. {
  1473. set_bit(CACHE_SET_UNREGISTERING, &c->flags);
  1474. bch_cache_set_stop(c);
  1475. }
  1476. #define alloc_meta_bucket_pages(gfp, sb) \
  1477. ((void *) __get_free_pages(__GFP_ZERO|__GFP_COMP|gfp, ilog2(meta_bucket_pages(sb))))
  1478. struct cache_set *bch_cache_set_alloc(struct cache_sb *sb)
  1479. {
  1480. int iter_size;
  1481. struct cache *ca = container_of(sb, struct cache, sb);
  1482. struct cache_set *c = kzalloc_obj(struct cache_set);
  1483. if (!c)
  1484. return NULL;
  1485. __module_get(THIS_MODULE);
  1486. closure_init(&c->cl, NULL);
  1487. set_closure_fn(&c->cl, cache_set_free, system_percpu_wq);
  1488. closure_init(&c->caching, &c->cl);
  1489. set_closure_fn(&c->caching, __cache_set_unregister, system_percpu_wq);
  1490. /* Maybe create continue_at_noreturn() and use it here? */
  1491. closure_set_stopped(&c->cl);
  1492. closure_put(&c->cl);
  1493. kobject_init(&c->kobj, &bch_cache_set_ktype);
  1494. kobject_init(&c->internal, &bch_cache_set_internal_ktype);
  1495. bch_cache_accounting_init(&c->accounting, &c->cl);
  1496. memcpy(c->set_uuid, sb->set_uuid, 16);
  1497. c->cache = ca;
  1498. c->cache->set = c;
  1499. c->bucket_bits = ilog2(sb->bucket_size);
  1500. c->block_bits = ilog2(sb->block_size);
  1501. c->nr_uuids = meta_bucket_bytes(sb) / sizeof(struct uuid_entry);
  1502. c->devices_max_used = 0;
  1503. atomic_set(&c->attached_dev_nr, 0);
  1504. c->btree_pages = meta_bucket_pages(sb);
  1505. if (c->btree_pages > BTREE_MAX_PAGES)
  1506. c->btree_pages = max_t(int, c->btree_pages / 4,
  1507. BTREE_MAX_PAGES);
  1508. sema_init(&c->sb_write_mutex, 1);
  1509. mutex_init(&c->bucket_lock);
  1510. init_waitqueue_head(&c->btree_cache_wait);
  1511. spin_lock_init(&c->btree_cannibalize_lock);
  1512. init_waitqueue_head(&c->bucket_wait);
  1513. init_waitqueue_head(&c->gc_wait);
  1514. sema_init(&c->uuid_write_mutex, 1);
  1515. spin_lock_init(&c->btree_gc_time.lock);
  1516. spin_lock_init(&c->btree_split_time.lock);
  1517. spin_lock_init(&c->btree_read_time.lock);
  1518. bch_moving_init_cache_set(c);
  1519. INIT_LIST_HEAD(&c->list);
  1520. INIT_LIST_HEAD(&c->cached_devs);
  1521. INIT_LIST_HEAD(&c->btree_cache);
  1522. INIT_LIST_HEAD(&c->btree_cache_freeable);
  1523. INIT_LIST_HEAD(&c->btree_cache_freed);
  1524. INIT_LIST_HEAD(&c->data_buckets);
  1525. iter_size = sizeof(struct btree_iter) +
  1526. ((meta_bucket_pages(sb) * PAGE_SECTORS) / sb->block_size) *
  1527. sizeof(struct btree_iter_set);
  1528. c->devices = kcalloc(c->nr_uuids, sizeof(void *), GFP_KERNEL);
  1529. if (!c->devices)
  1530. goto err;
  1531. if (mempool_init_slab_pool(&c->search, 32, bch_search_cache))
  1532. goto err;
  1533. if (mempool_init_kmalloc_pool(&c->bio_meta, 2,
  1534. sizeof(struct bbio) +
  1535. sizeof(struct bio_vec) * meta_bucket_pages(sb)))
  1536. goto err;
  1537. if (mempool_init_kmalloc_pool(&c->fill_iter, 1, iter_size))
  1538. goto err;
  1539. if (bioset_init(&c->bio_split, 4, offsetof(struct bbio, bio),
  1540. BIOSET_NEED_RESCUER))
  1541. goto err;
  1542. c->uuids = alloc_meta_bucket_pages(GFP_KERNEL, sb);
  1543. if (!c->uuids)
  1544. goto err;
  1545. c->moving_gc_wq = alloc_workqueue("bcache_gc",
  1546. WQ_MEM_RECLAIM | WQ_PERCPU, 0);
  1547. if (!c->moving_gc_wq)
  1548. goto err;
  1549. if (bch_journal_alloc(c))
  1550. goto err;
  1551. if (bch_btree_cache_alloc(c))
  1552. goto err;
  1553. if (bch_open_buckets_alloc(c))
  1554. goto err;
  1555. if (bch_bset_sort_state_init(&c->sort, ilog2(c->btree_pages)))
  1556. goto err;
  1557. c->congested_read_threshold_us = 2000;
  1558. c->congested_write_threshold_us = 20000;
  1559. c->error_limit = DEFAULT_IO_ERROR_LIMIT;
  1560. c->idle_max_writeback_rate_enabled = 1;
  1561. WARN_ON(test_and_clear_bit(CACHE_SET_IO_DISABLE, &c->flags));
  1562. return c;
  1563. err:
  1564. bch_cache_set_unregister(c);
  1565. return NULL;
  1566. }
  1567. static int run_cache_set(struct cache_set *c)
  1568. {
  1569. const char *err = "cannot allocate memory";
  1570. struct cached_dev *dc, *t;
  1571. struct cache *ca = c->cache;
  1572. struct closure cl;
  1573. LIST_HEAD(journal);
  1574. struct journal_replay *l;
  1575. closure_init_stack(&cl);
  1576. c->nbuckets = ca->sb.nbuckets;
  1577. set_gc_sectors(c);
  1578. if (CACHE_SYNC(&c->cache->sb)) {
  1579. struct bkey *k;
  1580. struct jset *j;
  1581. err = "cannot allocate memory for journal";
  1582. if (bch_journal_read(c, &journal))
  1583. goto err;
  1584. pr_debug("btree_journal_read() done\n");
  1585. err = "no journal entries found";
  1586. if (list_empty(&journal))
  1587. goto err;
  1588. j = &list_entry(journal.prev, struct journal_replay, list)->j;
  1589. err = "IO error reading priorities";
  1590. if (prio_read(ca, j->prio_bucket[ca->sb.nr_this_dev]))
  1591. goto err;
  1592. /*
  1593. * If prio_read() fails it'll call cache_set_error and we'll
  1594. * tear everything down right away, but if we perhaps checked
  1595. * sooner we could avoid journal replay.
  1596. */
  1597. k = &j->btree_root;
  1598. err = "bad btree root";
  1599. if (__bch_btree_ptr_invalid(c, k))
  1600. goto err;
  1601. err = "error reading btree root";
  1602. c->root = bch_btree_node_get(c, NULL, k,
  1603. j->btree_level,
  1604. true, NULL);
  1605. if (IS_ERR(c->root))
  1606. goto err;
  1607. list_del_init(&c->root->list);
  1608. rw_unlock(true, c->root);
  1609. err = uuid_read(c, j, &cl);
  1610. if (err)
  1611. goto err;
  1612. err = "error in recovery";
  1613. if (bch_btree_check(c))
  1614. goto err;
  1615. bch_journal_mark(c, &journal);
  1616. bch_initial_gc_finish(c);
  1617. pr_debug("btree_check() done\n");
  1618. /*
  1619. * bcache_journal_next() can't happen sooner, or
  1620. * btree_gc_finish() will give spurious errors about last_gc >
  1621. * gc_gen - this is a hack but oh well.
  1622. */
  1623. bch_journal_next(&c->journal);
  1624. err = "error starting allocator thread";
  1625. if (bch_cache_allocator_start(ca))
  1626. goto err;
  1627. /*
  1628. * First place it's safe to allocate: btree_check() and
  1629. * btree_gc_finish() have to run before we have buckets to
  1630. * allocate, and bch_bucket_alloc_set() might cause a journal
  1631. * entry to be written so bcache_journal_next() has to be called
  1632. * first.
  1633. *
  1634. * If the uuids were in the old format we have to rewrite them
  1635. * before the next journal entry is written:
  1636. */
  1637. if (j->version < BCACHE_JSET_VERSION_UUID)
  1638. __uuid_write(c);
  1639. err = "bcache: replay journal failed";
  1640. if (bch_journal_replay(c, &journal))
  1641. goto err;
  1642. } else {
  1643. unsigned int j;
  1644. pr_notice("invalidating existing data\n");
  1645. ca->sb.keys = clamp_t(int, ca->sb.nbuckets >> 7,
  1646. 2, SB_JOURNAL_BUCKETS);
  1647. for (j = 0; j < ca->sb.keys; j++)
  1648. ca->sb.d[j] = ca->sb.first_bucket + j;
  1649. bch_initial_gc_finish(c);
  1650. err = "error starting allocator thread";
  1651. if (bch_cache_allocator_start(ca))
  1652. goto err;
  1653. mutex_lock(&c->bucket_lock);
  1654. bch_prio_write(ca, true);
  1655. mutex_unlock(&c->bucket_lock);
  1656. err = "cannot allocate new UUID bucket";
  1657. if (__uuid_write(c))
  1658. goto err;
  1659. err = "cannot allocate new btree root";
  1660. c->root = __bch_btree_node_alloc(c, NULL, 0, true, NULL);
  1661. if (IS_ERR(c->root))
  1662. goto err;
  1663. mutex_lock(&c->root->write_lock);
  1664. bkey_copy_key(&c->root->key, &MAX_KEY);
  1665. bch_btree_node_write(c->root, &cl);
  1666. mutex_unlock(&c->root->write_lock);
  1667. bch_btree_set_root(c->root);
  1668. rw_unlock(true, c->root);
  1669. /*
  1670. * We don't want to write the first journal entry until
  1671. * everything is set up - fortunately journal entries won't be
  1672. * written until the SET_CACHE_SYNC() here:
  1673. */
  1674. SET_CACHE_SYNC(&c->cache->sb, true);
  1675. bch_journal_next(&c->journal);
  1676. bch_journal_meta(c, &cl);
  1677. }
  1678. err = "error starting gc thread";
  1679. if (bch_gc_thread_start(c))
  1680. goto err;
  1681. closure_sync(&cl);
  1682. c->cache->sb.last_mount = (u32)ktime_get_real_seconds();
  1683. bcache_write_super(c);
  1684. if (bch_has_feature_obso_large_bucket(&c->cache->sb))
  1685. pr_err("Detect obsoleted large bucket layout, all attached bcache device will be read-only\n");
  1686. list_for_each_entry_safe(dc, t, &uncached_devices, list)
  1687. bch_cached_dev_attach(dc, c, NULL);
  1688. flash_devs_run(c);
  1689. bch_journal_space_reserve(&c->journal);
  1690. set_bit(CACHE_SET_RUNNING, &c->flags);
  1691. return 0;
  1692. err:
  1693. while (!list_empty(&journal)) {
  1694. l = list_first_entry(&journal, struct journal_replay, list);
  1695. list_del(&l->list);
  1696. kfree(l);
  1697. }
  1698. closure_sync(&cl);
  1699. bch_cache_set_error(c, "%s", err);
  1700. return -EIO;
  1701. }
  1702. static const char *register_cache_set(struct cache *ca)
  1703. {
  1704. char buf[12];
  1705. const char *err = "cannot allocate memory";
  1706. struct cache_set *c;
  1707. list_for_each_entry(c, &bch_cache_sets, list)
  1708. if (!memcmp(c->set_uuid, ca->sb.set_uuid, 16)) {
  1709. if (c->cache)
  1710. return "duplicate cache set member";
  1711. goto found;
  1712. }
  1713. c = bch_cache_set_alloc(&ca->sb);
  1714. if (!c)
  1715. return err;
  1716. err = "error creating kobject";
  1717. if (kobject_add(&c->kobj, bcache_kobj, "%pU", c->set_uuid) ||
  1718. kobject_add(&c->internal, &c->kobj, "internal"))
  1719. goto err;
  1720. if (bch_cache_accounting_add_kobjs(&c->accounting, &c->kobj))
  1721. goto err;
  1722. bch_debug_init_cache_set(c);
  1723. list_add(&c->list, &bch_cache_sets);
  1724. found:
  1725. sprintf(buf, "cache%i", ca->sb.nr_this_dev);
  1726. if (sysfs_create_link(&ca->kobj, &c->kobj, "set") ||
  1727. sysfs_create_link(&c->kobj, &ca->kobj, buf))
  1728. goto err;
  1729. kobject_get(&ca->kobj);
  1730. ca->set = c;
  1731. ca->set->cache = ca;
  1732. err = "failed to run cache set";
  1733. if (run_cache_set(c) < 0)
  1734. goto err;
  1735. return NULL;
  1736. err:
  1737. bch_cache_set_unregister(c);
  1738. return err;
  1739. }
  1740. /* Cache device */
  1741. /* When ca->kobj released */
  1742. void bch_cache_release(struct kobject *kobj)
  1743. {
  1744. struct cache *ca = container_of(kobj, struct cache, kobj);
  1745. unsigned int i;
  1746. if (ca->set) {
  1747. BUG_ON(ca->set->cache != ca);
  1748. ca->set->cache = NULL;
  1749. }
  1750. free_pages((unsigned long) ca->disk_buckets, ilog2(meta_bucket_pages(&ca->sb)));
  1751. kfree(ca->prio_buckets);
  1752. vfree(ca->buckets);
  1753. free_heap(&ca->heap);
  1754. free_fifo(&ca->free_inc);
  1755. for (i = 0; i < RESERVE_NR; i++)
  1756. free_fifo(&ca->free[i]);
  1757. if (ca->sb_disk)
  1758. folio_put(virt_to_folio(ca->sb_disk));
  1759. if (ca->bdev_file)
  1760. fput(ca->bdev_file);
  1761. kfree(ca);
  1762. module_put(THIS_MODULE);
  1763. }
  1764. static int cache_alloc(struct cache *ca)
  1765. {
  1766. size_t free;
  1767. size_t btree_buckets;
  1768. struct bucket *b;
  1769. int ret = -ENOMEM;
  1770. const char *err = NULL;
  1771. __module_get(THIS_MODULE);
  1772. kobject_init(&ca->kobj, &bch_cache_ktype);
  1773. bio_init_inline(&ca->journal.bio, NULL, 8, 0);
  1774. /*
  1775. * When the cache disk is first registered, ca->sb.njournal_buckets
  1776. * is zero, and it is assigned in run_cache_set().
  1777. *
  1778. * When ca->sb.njournal_buckets is not zero, journal exists,
  1779. * and in bch_journal_replay(), tree node may split.
  1780. * The worst situation is all journal buckets are valid journal,
  1781. * and all the keys need to replay, so the number of RESERVE_BTREE
  1782. * type buckets should be as much as journal buckets.
  1783. *
  1784. * If the number of RESERVE_BTREE type buckets is too few, the
  1785. * bch_allocator_thread() may hang up and unable to allocate
  1786. * bucket. The situation is roughly as follows:
  1787. *
  1788. * 1. In bch_data_insert_keys(), if the operation is not op->replace,
  1789. * it will call the bch_journal(), which increments the journal_ref
  1790. * counter. This counter is only decremented after bch_btree_insert
  1791. * completes.
  1792. *
  1793. * 2. When calling bch_btree_insert, if the btree needs to split,
  1794. * it will call btree_split() and btree_check_reserve() to check
  1795. * whether there are enough reserved buckets in the RESERVE_BTREE
  1796. * slot. If not enough, bcache_btree_root() will repeatedly retry.
  1797. *
  1798. * 3. Normally, the bch_allocator_thread is responsible for filling
  1799. * the reservation slots from the free_inc bucket list. When the
  1800. * free_inc bucket list is exhausted, the bch_allocator_thread
  1801. * will call invalidate_buckets() until free_inc is refilled.
  1802. * Then bch_allocator_thread calls bch_prio_write() once. and
  1803. * bch_prio_write() will call bch_journal_meta() and waits for
  1804. * the journal write to complete.
  1805. *
  1806. * 4. During journal_write, journal_write_unlocked() is be called.
  1807. * If journal full occurs, journal_reclaim() and btree_flush_write()
  1808. * will be called sequentially, then retry journal_write.
  1809. *
  1810. * 5. When 2 and 4 occur together, IO will hung up and cannot recover.
  1811. *
  1812. * Therefore, reserve more RESERVE_BTREE type buckets.
  1813. */
  1814. btree_buckets = clamp_t(size_t, ca->sb.nbuckets >> 7,
  1815. 32, SB_JOURNAL_BUCKETS);
  1816. free = roundup_pow_of_two(ca->sb.nbuckets) >> 10;
  1817. if (!free) {
  1818. ret = -EPERM;
  1819. err = "ca->sb.nbuckets is too small";
  1820. goto err_free;
  1821. }
  1822. if (!init_fifo(&ca->free[RESERVE_BTREE], btree_buckets,
  1823. GFP_KERNEL)) {
  1824. err = "ca->free[RESERVE_BTREE] alloc failed";
  1825. goto err_btree_alloc;
  1826. }
  1827. if (!init_fifo_exact(&ca->free[RESERVE_PRIO], prio_buckets(ca),
  1828. GFP_KERNEL)) {
  1829. err = "ca->free[RESERVE_PRIO] alloc failed";
  1830. goto err_prio_alloc;
  1831. }
  1832. if (!init_fifo(&ca->free[RESERVE_MOVINGGC], free, GFP_KERNEL)) {
  1833. err = "ca->free[RESERVE_MOVINGGC] alloc failed";
  1834. goto err_movinggc_alloc;
  1835. }
  1836. if (!init_fifo(&ca->free[RESERVE_NONE], free, GFP_KERNEL)) {
  1837. err = "ca->free[RESERVE_NONE] alloc failed";
  1838. goto err_none_alloc;
  1839. }
  1840. if (!init_fifo(&ca->free_inc, free << 2, GFP_KERNEL)) {
  1841. err = "ca->free_inc alloc failed";
  1842. goto err_free_inc_alloc;
  1843. }
  1844. if (!init_heap(&ca->heap, free << 3, GFP_KERNEL)) {
  1845. err = "ca->heap alloc failed";
  1846. goto err_heap_alloc;
  1847. }
  1848. ca->buckets = vzalloc(array_size(sizeof(struct bucket),
  1849. ca->sb.nbuckets));
  1850. if (!ca->buckets) {
  1851. err = "ca->buckets alloc failed";
  1852. goto err_buckets_alloc;
  1853. }
  1854. ca->prio_buckets = kzalloc(array3_size(sizeof(uint64_t),
  1855. prio_buckets(ca), 2),
  1856. GFP_KERNEL);
  1857. if (!ca->prio_buckets) {
  1858. err = "ca->prio_buckets alloc failed";
  1859. goto err_prio_buckets_alloc;
  1860. }
  1861. ca->disk_buckets = alloc_meta_bucket_pages(GFP_KERNEL, &ca->sb);
  1862. if (!ca->disk_buckets) {
  1863. err = "ca->disk_buckets alloc failed";
  1864. goto err_disk_buckets_alloc;
  1865. }
  1866. ca->prio_last_buckets = ca->prio_buckets + prio_buckets(ca);
  1867. for_each_bucket(b, ca)
  1868. atomic_set(&b->pin, 0);
  1869. return 0;
  1870. err_disk_buckets_alloc:
  1871. kfree(ca->prio_buckets);
  1872. err_prio_buckets_alloc:
  1873. vfree(ca->buckets);
  1874. err_buckets_alloc:
  1875. free_heap(&ca->heap);
  1876. err_heap_alloc:
  1877. free_fifo(&ca->free_inc);
  1878. err_free_inc_alloc:
  1879. free_fifo(&ca->free[RESERVE_NONE]);
  1880. err_none_alloc:
  1881. free_fifo(&ca->free[RESERVE_MOVINGGC]);
  1882. err_movinggc_alloc:
  1883. free_fifo(&ca->free[RESERVE_PRIO]);
  1884. err_prio_alloc:
  1885. free_fifo(&ca->free[RESERVE_BTREE]);
  1886. err_btree_alloc:
  1887. err_free:
  1888. module_put(THIS_MODULE);
  1889. if (err)
  1890. pr_notice("error %pg: %s\n", ca->bdev, err);
  1891. return ret;
  1892. }
  1893. static int register_cache(struct cache_sb *sb, struct cache_sb_disk *sb_disk,
  1894. struct file *bdev_file,
  1895. struct cache *ca)
  1896. {
  1897. const char *err = NULL; /* must be set for any error case */
  1898. int ret = 0;
  1899. memcpy(&ca->sb, sb, sizeof(struct cache_sb));
  1900. ca->bdev_file = bdev_file;
  1901. ca->bdev = file_bdev(bdev_file);
  1902. ca->sb_disk = sb_disk;
  1903. ret = cache_alloc(ca);
  1904. if (ret != 0) {
  1905. if (ret == -ENOMEM)
  1906. err = "cache_alloc(): -ENOMEM";
  1907. else if (ret == -EPERM)
  1908. err = "cache_alloc(): cache device is too small";
  1909. else
  1910. err = "cache_alloc(): unknown error";
  1911. pr_notice("error %pg: %s\n", file_bdev(bdev_file), err);
  1912. /*
  1913. * If we failed here, it means ca->kobj is not initialized yet,
  1914. * kobject_put() won't be called and there is no chance to
  1915. * call fput() to bdev in bch_cache_release(). So
  1916. * we explicitly call fput() on the block device here.
  1917. */
  1918. fput(bdev_file);
  1919. return ret;
  1920. }
  1921. if (kobject_add(&ca->kobj, bdev_kobj(file_bdev(bdev_file)), "bcache")) {
  1922. pr_notice("error %pg: error calling kobject_add\n",
  1923. file_bdev(bdev_file));
  1924. ret = -ENOMEM;
  1925. goto out;
  1926. }
  1927. mutex_lock(&bch_register_lock);
  1928. err = register_cache_set(ca);
  1929. mutex_unlock(&bch_register_lock);
  1930. if (err) {
  1931. ret = -ENODEV;
  1932. goto out;
  1933. }
  1934. pr_info("registered cache device %pg\n", file_bdev(ca->bdev_file));
  1935. out:
  1936. kobject_put(&ca->kobj);
  1937. return ret;
  1938. }
  1939. /* Global interfaces/init */
  1940. static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
  1941. const char *buffer, size_t size);
  1942. static ssize_t bch_pending_bdevs_cleanup(struct kobject *k,
  1943. struct kobj_attribute *attr,
  1944. const char *buffer, size_t size);
  1945. kobj_attribute_write(register, register_bcache);
  1946. kobj_attribute_write(register_quiet, register_bcache);
  1947. kobj_attribute_write(pendings_cleanup, bch_pending_bdevs_cleanup);
  1948. static bool bch_is_open_backing(dev_t dev)
  1949. {
  1950. struct cache_set *c, *tc;
  1951. struct cached_dev *dc, *t;
  1952. list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
  1953. list_for_each_entry_safe(dc, t, &c->cached_devs, list)
  1954. if (dc->bdev->bd_dev == dev)
  1955. return true;
  1956. list_for_each_entry_safe(dc, t, &uncached_devices, list)
  1957. if (dc->bdev->bd_dev == dev)
  1958. return true;
  1959. return false;
  1960. }
  1961. static bool bch_is_open_cache(dev_t dev)
  1962. {
  1963. struct cache_set *c, *tc;
  1964. list_for_each_entry_safe(c, tc, &bch_cache_sets, list) {
  1965. struct cache *ca = c->cache;
  1966. if (ca->bdev->bd_dev == dev)
  1967. return true;
  1968. }
  1969. return false;
  1970. }
  1971. static bool bch_is_open(dev_t dev)
  1972. {
  1973. return bch_is_open_cache(dev) || bch_is_open_backing(dev);
  1974. }
  1975. struct async_reg_args {
  1976. struct delayed_work reg_work;
  1977. char *path;
  1978. struct cache_sb *sb;
  1979. struct cache_sb_disk *sb_disk;
  1980. struct file *bdev_file;
  1981. void *holder;
  1982. };
  1983. static void register_bdev_worker(struct work_struct *work)
  1984. {
  1985. int fail = false;
  1986. struct async_reg_args *args =
  1987. container_of(work, struct async_reg_args, reg_work.work);
  1988. mutex_lock(&bch_register_lock);
  1989. if (register_bdev(args->sb, args->sb_disk, args->bdev_file,
  1990. args->holder) < 0)
  1991. fail = true;
  1992. mutex_unlock(&bch_register_lock);
  1993. if (fail)
  1994. pr_info("error %s: fail to register backing device\n",
  1995. args->path);
  1996. kfree(args->sb);
  1997. kfree(args->path);
  1998. kfree(args);
  1999. module_put(THIS_MODULE);
  2000. }
  2001. static void register_cache_worker(struct work_struct *work)
  2002. {
  2003. int fail = false;
  2004. struct async_reg_args *args =
  2005. container_of(work, struct async_reg_args, reg_work.work);
  2006. /* blkdev_put() will be called in bch_cache_release() */
  2007. if (register_cache(args->sb, args->sb_disk, args->bdev_file,
  2008. args->holder))
  2009. fail = true;
  2010. if (fail)
  2011. pr_info("error %s: fail to register cache device\n",
  2012. args->path);
  2013. kfree(args->sb);
  2014. kfree(args->path);
  2015. kfree(args);
  2016. module_put(THIS_MODULE);
  2017. }
  2018. static void register_device_async(struct async_reg_args *args)
  2019. {
  2020. if (SB_IS_BDEV(args->sb))
  2021. INIT_DELAYED_WORK(&args->reg_work, register_bdev_worker);
  2022. else
  2023. INIT_DELAYED_WORK(&args->reg_work, register_cache_worker);
  2024. /* 10 jiffies is enough for a delay */
  2025. queue_delayed_work(system_percpu_wq, &args->reg_work, 10);
  2026. }
  2027. static void *alloc_holder_object(struct cache_sb *sb)
  2028. {
  2029. if (SB_IS_BDEV(sb))
  2030. return kzalloc_obj(struct cached_dev);
  2031. return kzalloc_obj(struct cache);
  2032. }
  2033. static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
  2034. const char *buffer, size_t size)
  2035. {
  2036. const char *err;
  2037. char *path = NULL;
  2038. struct cache_sb *sb;
  2039. struct cache_sb_disk *sb_disk;
  2040. struct file *bdev_file, *bdev_file2;
  2041. void *holder = NULL;
  2042. ssize_t ret;
  2043. bool async_registration = false;
  2044. bool quiet = false;
  2045. #ifdef CONFIG_BCACHE_ASYNC_REGISTRATION
  2046. async_registration = true;
  2047. #endif
  2048. ret = -EBUSY;
  2049. err = "failed to reference bcache module";
  2050. if (!try_module_get(THIS_MODULE))
  2051. goto out;
  2052. /* For latest state of bcache_is_reboot */
  2053. smp_mb();
  2054. err = "bcache is in reboot";
  2055. if (bcache_is_reboot)
  2056. goto out_module_put;
  2057. ret = -ENOMEM;
  2058. err = "cannot allocate memory";
  2059. path = kstrndup(buffer, size, GFP_KERNEL);
  2060. if (!path)
  2061. goto out_module_put;
  2062. sb = kmalloc_obj(struct cache_sb);
  2063. if (!sb)
  2064. goto out_free_path;
  2065. ret = -EINVAL;
  2066. err = "failed to open device";
  2067. bdev_file = bdev_file_open_by_path(strim(path), BLK_OPEN_READ, NULL, NULL);
  2068. if (IS_ERR(bdev_file))
  2069. goto out_free_sb;
  2070. err = read_super(sb, file_bdev(bdev_file), &sb_disk);
  2071. if (err)
  2072. goto out_blkdev_put;
  2073. holder = alloc_holder_object(sb);
  2074. if (!holder) {
  2075. ret = -ENOMEM;
  2076. err = "cannot allocate memory";
  2077. goto out_put_sb_folio;
  2078. }
  2079. /* Now reopen in exclusive mode with proper holder */
  2080. bdev_file2 = bdev_file_open_by_dev(file_bdev(bdev_file)->bd_dev,
  2081. BLK_OPEN_READ | BLK_OPEN_WRITE, holder, NULL);
  2082. fput(bdev_file);
  2083. bdev_file = bdev_file2;
  2084. if (IS_ERR(bdev_file)) {
  2085. ret = PTR_ERR(bdev_file);
  2086. bdev_file = NULL;
  2087. if (ret == -EBUSY) {
  2088. dev_t dev;
  2089. mutex_lock(&bch_register_lock);
  2090. if (lookup_bdev(strim(path), &dev) == 0 &&
  2091. bch_is_open(dev))
  2092. err = "device already registered";
  2093. else
  2094. err = "device busy";
  2095. mutex_unlock(&bch_register_lock);
  2096. if (attr == &ksysfs_register_quiet) {
  2097. quiet = true;
  2098. ret = size;
  2099. }
  2100. }
  2101. goto out_free_holder;
  2102. }
  2103. err = "failed to register device";
  2104. if (async_registration) {
  2105. /* register in asynchronous way */
  2106. struct async_reg_args *args =
  2107. kzalloc_obj(struct async_reg_args);
  2108. if (!args) {
  2109. ret = -ENOMEM;
  2110. err = "cannot allocate memory";
  2111. goto out_free_holder;
  2112. }
  2113. args->path = path;
  2114. args->sb = sb;
  2115. args->sb_disk = sb_disk;
  2116. args->bdev_file = bdev_file;
  2117. args->holder = holder;
  2118. register_device_async(args);
  2119. /* No wait and returns to user space */
  2120. goto async_done;
  2121. }
  2122. if (SB_IS_BDEV(sb)) {
  2123. mutex_lock(&bch_register_lock);
  2124. ret = register_bdev(sb, sb_disk, bdev_file, holder);
  2125. mutex_unlock(&bch_register_lock);
  2126. /* blkdev_put() will be called in cached_dev_free() */
  2127. if (ret < 0)
  2128. goto out_free_sb;
  2129. } else {
  2130. /* blkdev_put() will be called in bch_cache_release() */
  2131. ret = register_cache(sb, sb_disk, bdev_file, holder);
  2132. if (ret)
  2133. goto out_free_sb;
  2134. }
  2135. kfree(sb);
  2136. kfree(path);
  2137. module_put(THIS_MODULE);
  2138. async_done:
  2139. return size;
  2140. out_free_holder:
  2141. kfree(holder);
  2142. out_put_sb_folio:
  2143. folio_put(virt_to_folio(sb_disk));
  2144. out_blkdev_put:
  2145. if (bdev_file)
  2146. fput(bdev_file);
  2147. out_free_sb:
  2148. kfree(sb);
  2149. out_free_path:
  2150. kfree(path);
  2151. path = NULL;
  2152. out_module_put:
  2153. module_put(THIS_MODULE);
  2154. out:
  2155. if (!quiet)
  2156. pr_info("error %s: %s\n", path?path:"", err);
  2157. return ret;
  2158. }
  2159. struct pdev {
  2160. struct list_head list;
  2161. struct cached_dev *dc;
  2162. };
  2163. static ssize_t bch_pending_bdevs_cleanup(struct kobject *k,
  2164. struct kobj_attribute *attr,
  2165. const char *buffer,
  2166. size_t size)
  2167. {
  2168. LIST_HEAD(pending_devs);
  2169. ssize_t ret = size;
  2170. struct cached_dev *dc, *tdc;
  2171. struct pdev *pdev, *tpdev;
  2172. struct cache_set *c, *tc;
  2173. mutex_lock(&bch_register_lock);
  2174. list_for_each_entry_safe(dc, tdc, &uncached_devices, list) {
  2175. pdev = kmalloc_obj(struct pdev);
  2176. if (!pdev)
  2177. break;
  2178. pdev->dc = dc;
  2179. list_add(&pdev->list, &pending_devs);
  2180. }
  2181. list_for_each_entry_safe(pdev, tpdev, &pending_devs, list) {
  2182. char *pdev_set_uuid = pdev->dc->sb.set_uuid;
  2183. list_for_each_entry_safe(c, tc, &bch_cache_sets, list) {
  2184. char *set_uuid = c->set_uuid;
  2185. if (!memcmp(pdev_set_uuid, set_uuid, 16)) {
  2186. list_del(&pdev->list);
  2187. kfree(pdev);
  2188. break;
  2189. }
  2190. }
  2191. }
  2192. mutex_unlock(&bch_register_lock);
  2193. list_for_each_entry_safe(pdev, tpdev, &pending_devs, list) {
  2194. pr_info("delete pdev %p\n", pdev);
  2195. list_del(&pdev->list);
  2196. bcache_device_stop(&pdev->dc->disk);
  2197. kfree(pdev);
  2198. }
  2199. return ret;
  2200. }
  2201. static int bcache_reboot(struct notifier_block *n, unsigned long code, void *x)
  2202. {
  2203. if (bcache_is_reboot)
  2204. return NOTIFY_DONE;
  2205. if (code == SYS_DOWN ||
  2206. code == SYS_HALT ||
  2207. code == SYS_POWER_OFF) {
  2208. DEFINE_WAIT(wait);
  2209. unsigned long start = jiffies;
  2210. bool stopped = false;
  2211. struct cache_set *c, *tc;
  2212. struct cached_dev *dc, *tdc;
  2213. mutex_lock(&bch_register_lock);
  2214. if (bcache_is_reboot)
  2215. goto out;
  2216. /* New registration is rejected since now */
  2217. bcache_is_reboot = true;
  2218. /*
  2219. * Make registering caller (if there is) on other CPU
  2220. * core know bcache_is_reboot set to true earlier
  2221. */
  2222. smp_mb();
  2223. if (list_empty(&bch_cache_sets) &&
  2224. list_empty(&uncached_devices))
  2225. goto out;
  2226. mutex_unlock(&bch_register_lock);
  2227. pr_info("Stopping all devices:\n");
  2228. /*
  2229. * The reason bch_register_lock is not held to call
  2230. * bch_cache_set_stop() and bcache_device_stop() is to
  2231. * avoid potential deadlock during reboot, because cache
  2232. * set or bcache device stopping process will acquire
  2233. * bch_register_lock too.
  2234. *
  2235. * We are safe here because bcache_is_reboot sets to
  2236. * true already, register_bcache() will reject new
  2237. * registration now. bcache_is_reboot also makes sure
  2238. * bcache_reboot() won't be re-entered on by other thread,
  2239. * so there is no race in following list iteration by
  2240. * list_for_each_entry_safe().
  2241. */
  2242. list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
  2243. bch_cache_set_stop(c);
  2244. list_for_each_entry_safe(dc, tdc, &uncached_devices, list)
  2245. bcache_device_stop(&dc->disk);
  2246. /*
  2247. * Give an early chance for other kthreads and
  2248. * kworkers to stop themselves
  2249. */
  2250. schedule();
  2251. /* What's a condition variable? */
  2252. while (1) {
  2253. long timeout = start + 10 * HZ - jiffies;
  2254. mutex_lock(&bch_register_lock);
  2255. stopped = list_empty(&bch_cache_sets) &&
  2256. list_empty(&uncached_devices);
  2257. if (timeout < 0 || stopped)
  2258. break;
  2259. prepare_to_wait(&unregister_wait, &wait,
  2260. TASK_UNINTERRUPTIBLE);
  2261. mutex_unlock(&bch_register_lock);
  2262. schedule_timeout(timeout);
  2263. }
  2264. finish_wait(&unregister_wait, &wait);
  2265. if (stopped)
  2266. pr_info("All devices stopped\n");
  2267. else
  2268. pr_notice("Timeout waiting for devices to be closed\n");
  2269. out:
  2270. mutex_unlock(&bch_register_lock);
  2271. }
  2272. return NOTIFY_DONE;
  2273. }
  2274. static struct notifier_block reboot = {
  2275. .notifier_call = bcache_reboot,
  2276. .priority = INT_MAX, /* before any real devices */
  2277. };
  2278. static void bcache_exit(void)
  2279. {
  2280. bch_debug_exit();
  2281. bch_request_exit();
  2282. if (bcache_kobj)
  2283. kobject_put(bcache_kobj);
  2284. if (bcache_wq)
  2285. destroy_workqueue(bcache_wq);
  2286. if (bch_journal_wq)
  2287. destroy_workqueue(bch_journal_wq);
  2288. if (bch_flush_wq)
  2289. destroy_workqueue(bch_flush_wq);
  2290. bch_btree_exit();
  2291. if (bcache_major)
  2292. unregister_blkdev(bcache_major, "bcache");
  2293. unregister_reboot_notifier(&reboot);
  2294. mutex_destroy(&bch_register_lock);
  2295. }
  2296. /* Check and fixup module parameters */
  2297. static void check_module_parameters(void)
  2298. {
  2299. if (bch_cutoff_writeback_sync == 0)
  2300. bch_cutoff_writeback_sync = CUTOFF_WRITEBACK_SYNC;
  2301. else if (bch_cutoff_writeback_sync > CUTOFF_WRITEBACK_SYNC_MAX) {
  2302. pr_warn("set bch_cutoff_writeback_sync (%u) to max value %u\n",
  2303. bch_cutoff_writeback_sync, CUTOFF_WRITEBACK_SYNC_MAX);
  2304. bch_cutoff_writeback_sync = CUTOFF_WRITEBACK_SYNC_MAX;
  2305. }
  2306. if (bch_cutoff_writeback == 0)
  2307. bch_cutoff_writeback = CUTOFF_WRITEBACK;
  2308. else if (bch_cutoff_writeback > CUTOFF_WRITEBACK_MAX) {
  2309. pr_warn("set bch_cutoff_writeback (%u) to max value %u\n",
  2310. bch_cutoff_writeback, CUTOFF_WRITEBACK_MAX);
  2311. bch_cutoff_writeback = CUTOFF_WRITEBACK_MAX;
  2312. }
  2313. if (bch_cutoff_writeback > bch_cutoff_writeback_sync) {
  2314. pr_warn("set bch_cutoff_writeback (%u) to %u\n",
  2315. bch_cutoff_writeback, bch_cutoff_writeback_sync);
  2316. bch_cutoff_writeback = bch_cutoff_writeback_sync;
  2317. }
  2318. }
  2319. static int __init bcache_init(void)
  2320. {
  2321. static const struct attribute *files[] = {
  2322. &ksysfs_register.attr,
  2323. &ksysfs_register_quiet.attr,
  2324. &ksysfs_pendings_cleanup.attr,
  2325. NULL
  2326. };
  2327. check_module_parameters();
  2328. mutex_init(&bch_register_lock);
  2329. init_waitqueue_head(&unregister_wait);
  2330. register_reboot_notifier(&reboot);
  2331. bcache_major = register_blkdev(0, "bcache");
  2332. if (bcache_major < 0) {
  2333. unregister_reboot_notifier(&reboot);
  2334. mutex_destroy(&bch_register_lock);
  2335. return bcache_major;
  2336. }
  2337. if (bch_btree_init())
  2338. goto err;
  2339. bcache_wq = alloc_workqueue("bcache", WQ_MEM_RECLAIM | WQ_PERCPU, 0);
  2340. if (!bcache_wq)
  2341. goto err;
  2342. /*
  2343. * Let's not make this `WQ_MEM_RECLAIM` for the following reasons:
  2344. *
  2345. * 1. It used `system_percpu_wq` before which also does no memory reclaim.
  2346. * 2. With `WQ_MEM_RECLAIM` desktop stalls, increased boot times, and
  2347. * reduced throughput can be observed.
  2348. *
  2349. * We still want to user our own queue to not congest the `system_percpu_wq`.
  2350. */
  2351. bch_flush_wq = alloc_workqueue("bch_flush", WQ_PERCPU, 0);
  2352. if (!bch_flush_wq)
  2353. goto err;
  2354. bch_journal_wq = alloc_workqueue("bch_journal",
  2355. WQ_MEM_RECLAIM | WQ_PERCPU, 0);
  2356. if (!bch_journal_wq)
  2357. goto err;
  2358. bcache_kobj = kobject_create_and_add("bcache", fs_kobj);
  2359. if (!bcache_kobj)
  2360. goto err;
  2361. if (bch_request_init() ||
  2362. sysfs_create_files(bcache_kobj, files))
  2363. goto err;
  2364. bch_debug_init();
  2365. bcache_is_reboot = false;
  2366. return 0;
  2367. err:
  2368. bcache_exit();
  2369. return -ENOMEM;
  2370. }
  2371. /*
  2372. * Module hooks
  2373. */
  2374. module_exit(bcache_exit);
  2375. module_init(bcache_init);
  2376. module_param(bch_cutoff_writeback, uint, 0);
  2377. MODULE_PARM_DESC(bch_cutoff_writeback, "threshold to cutoff writeback");
  2378. module_param(bch_cutoff_writeback_sync, uint, 0);
  2379. MODULE_PARM_DESC(bch_cutoff_writeback_sync, "hard threshold to cutoff writeback");
  2380. MODULE_DESCRIPTION("Bcache: a Linux block layer cache");
  2381. MODULE_AUTHOR("Kent Overstreet <kent.overstreet@gmail.com>");
  2382. MODULE_LICENSE("GPL");