loop.c 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309
  1. /*
  2. * linux/drivers/block/loop.c
  3. *
  4. * Written by Theodore Ts'o, 3/29/93
  5. *
  6. * Copyright 1993 by Theodore Ts'o. Redistribution of this file is
  7. * permitted under the GNU General Public License.
  8. *
  9. * DES encryption plus some minor changes by Werner Almesberger, 30-MAY-1993
  10. * more DES encryption plus IDEA encryption by Nicholas J. Leon, June 20, 1996
  11. *
  12. * Modularized and updated for 1.1.16 kernel - Mitch Dsouza 28th May 1994
  13. * Adapted for 1.3.59 kernel - Andries Brouwer, 1 Feb 1996
  14. *
  15. * Fixed do_loop_request() re-entrancy - Vincent.Renardias@waw.com Mar 20, 1997
  16. *
  17. * Added devfs support - Richard Gooch <rgooch@atnf.csiro.au> 16-Jan-1998
  18. *
  19. * Handle sparse backing files correctly - Kenn Humborg, Jun 28, 1998
  20. *
  21. * Loadable modules and other fixes by AK, 1998
  22. *
  23. * Make real block number available to downstream transfer functions, enables
  24. * CBC (and relatives) mode encryption requiring unique IVs per data block.
  25. * Reed H. Petty, rhp@draper.net
  26. *
  27. * Maximum number of loop devices now dynamic via max_loop module parameter.
  28. * Russell Kroll <rkroll@exploits.org> 19990701
  29. *
  30. * Maximum number of loop devices when compiled-in now selectable by passing
  31. * max_loop=<1-255> to the kernel on boot.
  32. * Erik I. Bolsø, <eriki@himolde.no>, Oct 31, 1999
  33. *
  34. * Completely rewrite request handling to be make_request_fn style and
  35. * non blocking, pushing work to a helper thread. Lots of fixes from
  36. * Al Viro too.
  37. * Jens Axboe <axboe@suse.de>, Nov 2000
  38. *
  39. * Support up to 256 loop devices
  40. * Heinz Mauelshagen <mge@sistina.com>, Feb 2002
  41. *
  42. * Support for falling back on the write file operation when the address space
  43. * operations write_begin is not available on the backing filesystem.
  44. * Anton Altaparmakov, 16 Feb 2005
  45. *
  46. * Still To Fix:
  47. * - Advisory locking is ignored here.
  48. * - Should use an own CAP_* category instead of CAP_SYS_ADMIN
  49. *
  50. */
  51. #include <linux/module.h>
  52. #include <linux/moduleparam.h>
  53. #include <linux/sched.h>
  54. #include <linux/fs.h>
  55. #include <linux/file.h>
  56. #include <linux/stat.h>
  57. #include <linux/errno.h>
  58. #include <linux/major.h>
  59. #include <linux/wait.h>
  60. #include <linux/blkdev.h>
  61. #include <linux/blkpg.h>
  62. #include <linux/init.h>
  63. #include <linux/swap.h>
  64. #include <linux/slab.h>
  65. #include <linux/compat.h>
  66. #include <linux/suspend.h>
  67. #include <linux/freezer.h>
  68. #include <linux/mutex.h>
  69. #include <linux/writeback.h>
  70. #include <linux/completion.h>
  71. #include <linux/highmem.h>
  72. #include <linux/kthread.h>
  73. #include <linux/splice.h>
  74. #include <linux/sysfs.h>
  75. #include <linux/miscdevice.h>
  76. #include <linux/falloc.h>
  77. #include <linux/uio.h>
  78. #include <linux/ioprio.h>
  79. #include "loop.h"
  80. #include <linux/uaccess.h>
  81. static DEFINE_IDR(loop_index_idr);
  82. static DEFINE_MUTEX(loop_ctl_mutex);
  83. static int max_part;
  84. static int part_shift;
  85. static int transfer_xor(struct loop_device *lo, int cmd,
  86. struct page *raw_page, unsigned raw_off,
  87. struct page *loop_page, unsigned loop_off,
  88. int size, sector_t real_block)
  89. {
  90. char *raw_buf = kmap_atomic(raw_page) + raw_off;
  91. char *loop_buf = kmap_atomic(loop_page) + loop_off;
  92. char *in, *out, *key;
  93. int i, keysize;
  94. if (cmd == READ) {
  95. in = raw_buf;
  96. out = loop_buf;
  97. } else {
  98. in = loop_buf;
  99. out = raw_buf;
  100. }
  101. key = lo->lo_encrypt_key;
  102. keysize = lo->lo_encrypt_key_size;
  103. for (i = 0; i < size; i++)
  104. *out++ = *in++ ^ key[(i & 511) % keysize];
  105. kunmap_atomic(loop_buf);
  106. kunmap_atomic(raw_buf);
  107. cond_resched();
  108. return 0;
  109. }
  110. static int xor_init(struct loop_device *lo, const struct loop_info64 *info)
  111. {
  112. if (unlikely(info->lo_encrypt_key_size <= 0))
  113. return -EINVAL;
  114. return 0;
  115. }
  116. static struct loop_func_table none_funcs = {
  117. .number = LO_CRYPT_NONE,
  118. };
  119. static struct loop_func_table xor_funcs = {
  120. .number = LO_CRYPT_XOR,
  121. .transfer = transfer_xor,
  122. .init = xor_init
  123. };
  124. /* xfer_funcs[0] is special - its release function is never called */
  125. static struct loop_func_table *xfer_funcs[MAX_LO_CRYPT] = {
  126. &none_funcs,
  127. &xor_funcs
  128. };
  129. static loff_t get_size(loff_t offset, loff_t sizelimit, struct file *file)
  130. {
  131. loff_t loopsize;
  132. /* Compute loopsize in bytes */
  133. loopsize = i_size_read(file->f_mapping->host);
  134. if (offset > 0)
  135. loopsize -= offset;
  136. /* offset is beyond i_size, weird but possible */
  137. if (loopsize < 0)
  138. return 0;
  139. if (sizelimit > 0 && sizelimit < loopsize)
  140. loopsize = sizelimit;
  141. /*
  142. * Unfortunately, if we want to do I/O on the device,
  143. * the number of 512-byte sectors has to fit into a sector_t.
  144. */
  145. return loopsize >> 9;
  146. }
  147. static loff_t get_loop_size(struct loop_device *lo, struct file *file)
  148. {
  149. return get_size(lo->lo_offset, lo->lo_sizelimit, file);
  150. }
  151. static void __loop_update_dio(struct loop_device *lo, bool dio)
  152. {
  153. struct file *file = lo->lo_backing_file;
  154. struct address_space *mapping = file->f_mapping;
  155. struct inode *inode = mapping->host;
  156. unsigned short sb_bsize = 0;
  157. unsigned dio_align = 0;
  158. bool use_dio;
  159. if (inode->i_sb->s_bdev) {
  160. sb_bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
  161. dio_align = sb_bsize - 1;
  162. }
  163. /*
  164. * We support direct I/O only if lo_offset is aligned with the
  165. * logical I/O size of backing device, and the logical block
  166. * size of loop is bigger than the backing device's and the loop
  167. * needn't transform transfer.
  168. *
  169. * TODO: the above condition may be loosed in the future, and
  170. * direct I/O may be switched runtime at that time because most
  171. * of requests in sane applications should be PAGE_SIZE aligned
  172. */
  173. if (dio) {
  174. if (queue_logical_block_size(lo->lo_queue) >= sb_bsize &&
  175. !(lo->lo_offset & dio_align) &&
  176. mapping->a_ops->direct_IO &&
  177. !lo->transfer)
  178. use_dio = true;
  179. else
  180. use_dio = false;
  181. } else {
  182. use_dio = false;
  183. }
  184. if (lo->use_dio == use_dio)
  185. return;
  186. /* flush dirty pages before changing direct IO */
  187. vfs_fsync(file, 0);
  188. /*
  189. * The flag of LO_FLAGS_DIRECT_IO is handled similarly with
  190. * LO_FLAGS_READ_ONLY, both are set from kernel, and losetup
  191. * will get updated by ioctl(LOOP_GET_STATUS)
  192. */
  193. blk_mq_freeze_queue(lo->lo_queue);
  194. lo->use_dio = use_dio;
  195. if (use_dio) {
  196. blk_queue_flag_clear(QUEUE_FLAG_NOMERGES, lo->lo_queue);
  197. lo->lo_flags |= LO_FLAGS_DIRECT_IO;
  198. } else {
  199. blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
  200. lo->lo_flags &= ~LO_FLAGS_DIRECT_IO;
  201. }
  202. blk_mq_unfreeze_queue(lo->lo_queue);
  203. }
  204. static int
  205. figure_loop_size(struct loop_device *lo, loff_t offset, loff_t sizelimit)
  206. {
  207. loff_t size = get_size(offset, sizelimit, lo->lo_backing_file);
  208. sector_t x = (sector_t)size;
  209. struct block_device *bdev = lo->lo_device;
  210. if (unlikely((loff_t)x != size))
  211. return -EFBIG;
  212. if (lo->lo_offset != offset)
  213. lo->lo_offset = offset;
  214. if (lo->lo_sizelimit != sizelimit)
  215. lo->lo_sizelimit = sizelimit;
  216. set_capacity(lo->lo_disk, x);
  217. bd_set_size(bdev, (loff_t)get_capacity(bdev->bd_disk) << 9);
  218. /* let user-space know about the new size */
  219. kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
  220. return 0;
  221. }
  222. static inline int
  223. lo_do_transfer(struct loop_device *lo, int cmd,
  224. struct page *rpage, unsigned roffs,
  225. struct page *lpage, unsigned loffs,
  226. int size, sector_t rblock)
  227. {
  228. int ret;
  229. ret = lo->transfer(lo, cmd, rpage, roffs, lpage, loffs, size, rblock);
  230. if (likely(!ret))
  231. return 0;
  232. printk_ratelimited(KERN_ERR
  233. "loop: Transfer error at byte offset %llu, length %i.\n",
  234. (unsigned long long)rblock << 9, size);
  235. return ret;
  236. }
  237. static int lo_write_bvec(struct file *file, struct bio_vec *bvec, loff_t *ppos)
  238. {
  239. struct iov_iter i;
  240. ssize_t bw;
  241. iov_iter_bvec(&i, ITER_BVEC | WRITE, bvec, 1, bvec->bv_len);
  242. file_start_write(file);
  243. bw = vfs_iter_write(file, &i, ppos, 0);
  244. file_end_write(file);
  245. if (likely(bw == bvec->bv_len))
  246. return 0;
  247. printk_ratelimited(KERN_ERR
  248. "loop: Write error at byte offset %llu, length %i.\n",
  249. (unsigned long long)*ppos, bvec->bv_len);
  250. if (bw >= 0)
  251. bw = -EIO;
  252. return bw;
  253. }
  254. static int lo_write_simple(struct loop_device *lo, struct request *rq,
  255. loff_t pos)
  256. {
  257. struct bio_vec bvec;
  258. struct req_iterator iter;
  259. int ret = 0;
  260. rq_for_each_segment(bvec, rq, iter) {
  261. ret = lo_write_bvec(lo->lo_backing_file, &bvec, &pos);
  262. if (ret < 0)
  263. break;
  264. cond_resched();
  265. }
  266. return ret;
  267. }
  268. /*
  269. * This is the slow, transforming version that needs to double buffer the
  270. * data as it cannot do the transformations in place without having direct
  271. * access to the destination pages of the backing file.
  272. */
  273. static int lo_write_transfer(struct loop_device *lo, struct request *rq,
  274. loff_t pos)
  275. {
  276. struct bio_vec bvec, b;
  277. struct req_iterator iter;
  278. struct page *page;
  279. int ret = 0;
  280. page = alloc_page(GFP_NOIO);
  281. if (unlikely(!page))
  282. return -ENOMEM;
  283. rq_for_each_segment(bvec, rq, iter) {
  284. ret = lo_do_transfer(lo, WRITE, page, 0, bvec.bv_page,
  285. bvec.bv_offset, bvec.bv_len, pos >> 9);
  286. if (unlikely(ret))
  287. break;
  288. b.bv_page = page;
  289. b.bv_offset = 0;
  290. b.bv_len = bvec.bv_len;
  291. ret = lo_write_bvec(lo->lo_backing_file, &b, &pos);
  292. if (ret < 0)
  293. break;
  294. }
  295. __free_page(page);
  296. return ret;
  297. }
  298. static int lo_read_simple(struct loop_device *lo, struct request *rq,
  299. loff_t pos)
  300. {
  301. struct bio_vec bvec;
  302. struct req_iterator iter;
  303. struct iov_iter i;
  304. ssize_t len;
  305. rq_for_each_segment(bvec, rq, iter) {
  306. iov_iter_bvec(&i, ITER_BVEC, &bvec, 1, bvec.bv_len);
  307. len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
  308. if (len < 0)
  309. return len;
  310. flush_dcache_page(bvec.bv_page);
  311. if (len != bvec.bv_len) {
  312. struct bio *bio;
  313. __rq_for_each_bio(bio, rq)
  314. zero_fill_bio(bio);
  315. break;
  316. }
  317. cond_resched();
  318. }
  319. return 0;
  320. }
  321. static int lo_read_transfer(struct loop_device *lo, struct request *rq,
  322. loff_t pos)
  323. {
  324. struct bio_vec bvec, b;
  325. struct req_iterator iter;
  326. struct iov_iter i;
  327. struct page *page;
  328. ssize_t len;
  329. int ret = 0;
  330. page = alloc_page(GFP_NOIO);
  331. if (unlikely(!page))
  332. return -ENOMEM;
  333. rq_for_each_segment(bvec, rq, iter) {
  334. loff_t offset = pos;
  335. b.bv_page = page;
  336. b.bv_offset = 0;
  337. b.bv_len = bvec.bv_len;
  338. iov_iter_bvec(&i, ITER_BVEC, &b, 1, b.bv_len);
  339. len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
  340. if (len < 0) {
  341. ret = len;
  342. goto out_free_page;
  343. }
  344. ret = lo_do_transfer(lo, READ, page, 0, bvec.bv_page,
  345. bvec.bv_offset, len, offset >> 9);
  346. if (ret)
  347. goto out_free_page;
  348. flush_dcache_page(bvec.bv_page);
  349. if (len != bvec.bv_len) {
  350. struct bio *bio;
  351. __rq_for_each_bio(bio, rq)
  352. zero_fill_bio(bio);
  353. break;
  354. }
  355. }
  356. ret = 0;
  357. out_free_page:
  358. __free_page(page);
  359. return ret;
  360. }
  361. static int lo_fallocate(struct loop_device *lo, struct request *rq, loff_t pos,
  362. int mode)
  363. {
  364. /*
  365. * We use fallocate to manipulate the space mappings used by the image
  366. * a.k.a. discard/zerorange. However we do not support this if
  367. * encryption is enabled, because it may give an attacker useful
  368. * information.
  369. */
  370. struct file *file = lo->lo_backing_file;
  371. struct request_queue *q = lo->lo_queue;
  372. int ret;
  373. mode |= FALLOC_FL_KEEP_SIZE;
  374. if (!blk_queue_discard(q)) {
  375. ret = -EOPNOTSUPP;
  376. goto out;
  377. }
  378. ret = file->f_op->fallocate(file, mode, pos, blk_rq_bytes(rq));
  379. if (unlikely(ret && ret != -EINVAL && ret != -EOPNOTSUPP))
  380. ret = -EIO;
  381. out:
  382. return ret;
  383. }
  384. static int lo_req_flush(struct loop_device *lo, struct request *rq)
  385. {
  386. struct file *file = lo->lo_backing_file;
  387. int ret = vfs_fsync(file, 0);
  388. if (unlikely(ret && ret != -EINVAL))
  389. ret = -EIO;
  390. return ret;
  391. }
  392. static void lo_complete_rq(struct request *rq)
  393. {
  394. struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
  395. blk_status_t ret = BLK_STS_OK;
  396. if (!cmd->use_aio || cmd->ret < 0 || cmd->ret == blk_rq_bytes(rq) ||
  397. req_op(rq) != REQ_OP_READ) {
  398. if (cmd->ret < 0)
  399. ret = BLK_STS_IOERR;
  400. goto end_io;
  401. }
  402. /*
  403. * Short READ - if we got some data, advance our request and
  404. * retry it. If we got no data, end the rest with EIO.
  405. */
  406. if (cmd->ret) {
  407. blk_update_request(rq, BLK_STS_OK, cmd->ret);
  408. cmd->ret = 0;
  409. blk_mq_requeue_request(rq, true);
  410. } else {
  411. if (cmd->use_aio) {
  412. struct bio *bio = rq->bio;
  413. while (bio) {
  414. zero_fill_bio(bio);
  415. bio = bio->bi_next;
  416. }
  417. }
  418. ret = BLK_STS_IOERR;
  419. end_io:
  420. blk_mq_end_request(rq, ret);
  421. }
  422. }
  423. static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
  424. {
  425. struct request *rq = blk_mq_rq_from_pdu(cmd);
  426. if (!atomic_dec_and_test(&cmd->ref))
  427. return;
  428. kfree(cmd->bvec);
  429. cmd->bvec = NULL;
  430. blk_mq_complete_request(rq);
  431. }
  432. static void lo_rw_aio_complete(struct kiocb *iocb, long ret, long ret2)
  433. {
  434. struct loop_cmd *cmd = container_of(iocb, struct loop_cmd, iocb);
  435. if (cmd->css)
  436. css_put(cmd->css);
  437. cmd->ret = ret;
  438. lo_rw_aio_do_completion(cmd);
  439. }
  440. static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
  441. loff_t pos, bool rw)
  442. {
  443. struct iov_iter iter;
  444. struct bio_vec *bvec;
  445. struct request *rq = blk_mq_rq_from_pdu(cmd);
  446. struct bio *bio = rq->bio;
  447. struct file *file = lo->lo_backing_file;
  448. unsigned int offset;
  449. int segments = 0;
  450. int ret;
  451. if (rq->bio != rq->biotail) {
  452. struct req_iterator iter;
  453. struct bio_vec tmp;
  454. __rq_for_each_bio(bio, rq)
  455. segments += bio_segments(bio);
  456. bvec = kmalloc_array(segments, sizeof(struct bio_vec),
  457. GFP_NOIO);
  458. if (!bvec)
  459. return -EIO;
  460. cmd->bvec = bvec;
  461. /*
  462. * The bios of the request may be started from the middle of
  463. * the 'bvec' because of bio splitting, so we can't directly
  464. * copy bio->bi_iov_vec to new bvec. The rq_for_each_segment
  465. * API will take care of all details for us.
  466. */
  467. rq_for_each_segment(tmp, rq, iter) {
  468. *bvec = tmp;
  469. bvec++;
  470. }
  471. bvec = cmd->bvec;
  472. offset = 0;
  473. } else {
  474. /*
  475. * Same here, this bio may be started from the middle of the
  476. * 'bvec' because of bio splitting, so offset from the bvec
  477. * must be passed to iov iterator
  478. */
  479. offset = bio->bi_iter.bi_bvec_done;
  480. bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
  481. segments = bio_segments(bio);
  482. }
  483. atomic_set(&cmd->ref, 2);
  484. iov_iter_bvec(&iter, ITER_BVEC | rw, bvec,
  485. segments, blk_rq_bytes(rq));
  486. iter.iov_offset = offset;
  487. cmd->iocb.ki_pos = pos;
  488. cmd->iocb.ki_filp = file;
  489. cmd->iocb.ki_complete = lo_rw_aio_complete;
  490. cmd->iocb.ki_flags = IOCB_DIRECT;
  491. cmd->iocb.ki_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
  492. if (cmd->css)
  493. kthread_associate_blkcg(cmd->css);
  494. if (rw == WRITE)
  495. ret = call_write_iter(file, &cmd->iocb, &iter);
  496. else
  497. ret = call_read_iter(file, &cmd->iocb, &iter);
  498. lo_rw_aio_do_completion(cmd);
  499. kthread_associate_blkcg(NULL);
  500. if (ret != -EIOCBQUEUED)
  501. cmd->iocb.ki_complete(&cmd->iocb, ret, 0);
  502. return 0;
  503. }
  504. static int do_req_filebacked(struct loop_device *lo, struct request *rq)
  505. {
  506. struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
  507. loff_t pos = ((loff_t) blk_rq_pos(rq) << 9) + lo->lo_offset;
  508. /*
  509. * lo_write_simple and lo_read_simple should have been covered
  510. * by io submit style function like lo_rw_aio(), one blocker
  511. * is that lo_read_simple() need to call flush_dcache_page after
  512. * the page is written from kernel, and it isn't easy to handle
  513. * this in io submit style function which submits all segments
  514. * of the req at one time. And direct read IO doesn't need to
  515. * run flush_dcache_page().
  516. */
  517. switch (req_op(rq)) {
  518. case REQ_OP_FLUSH:
  519. return lo_req_flush(lo, rq);
  520. case REQ_OP_WRITE_ZEROES:
  521. /*
  522. * If the caller doesn't want deallocation, call zeroout to
  523. * write zeroes the range. Otherwise, punch them out.
  524. */
  525. return lo_fallocate(lo, rq, pos,
  526. (rq->cmd_flags & REQ_NOUNMAP) ?
  527. FALLOC_FL_ZERO_RANGE :
  528. FALLOC_FL_PUNCH_HOLE);
  529. case REQ_OP_DISCARD:
  530. return lo_fallocate(lo, rq, pos, FALLOC_FL_PUNCH_HOLE);
  531. case REQ_OP_WRITE:
  532. if (lo->transfer)
  533. return lo_write_transfer(lo, rq, pos);
  534. else if (cmd->use_aio)
  535. return lo_rw_aio(lo, cmd, pos, WRITE);
  536. else
  537. return lo_write_simple(lo, rq, pos);
  538. case REQ_OP_READ:
  539. if (lo->transfer)
  540. return lo_read_transfer(lo, rq, pos);
  541. else if (cmd->use_aio)
  542. return lo_rw_aio(lo, cmd, pos, READ);
  543. else
  544. return lo_read_simple(lo, rq, pos);
  545. default:
  546. WARN_ON_ONCE(1);
  547. return -EIO;
  548. break;
  549. }
  550. }
  551. static inline void loop_update_dio(struct loop_device *lo)
  552. {
  553. __loop_update_dio(lo, io_is_direct(lo->lo_backing_file) |
  554. lo->use_dio);
  555. }
  556. static void loop_reread_partitions(struct loop_device *lo,
  557. struct block_device *bdev)
  558. {
  559. int rc;
  560. rc = blkdev_reread_part(bdev);
  561. if (rc)
  562. pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
  563. __func__, lo->lo_number, lo->lo_file_name, rc);
  564. }
  565. static inline int is_loop_device(struct file *file)
  566. {
  567. struct inode *i = file->f_mapping->host;
  568. return i && S_ISBLK(i->i_mode) && MAJOR(i->i_rdev) == LOOP_MAJOR;
  569. }
  570. static int loop_validate_file(struct file *file, struct block_device *bdev)
  571. {
  572. struct inode *inode = file->f_mapping->host;
  573. struct file *f = file;
  574. /* Avoid recursion */
  575. while (is_loop_device(f)) {
  576. struct loop_device *l;
  577. if (f->f_mapping->host->i_bdev == bdev)
  578. return -EBADF;
  579. l = f->f_mapping->host->i_bdev->bd_disk->private_data;
  580. if (l->lo_state != Lo_bound) {
  581. return -EINVAL;
  582. }
  583. f = l->lo_backing_file;
  584. }
  585. if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
  586. return -EINVAL;
  587. return 0;
  588. }
  589. /*
  590. * loop_change_fd switched the backing store of a loopback device to
  591. * a new file. This is useful for operating system installers to free up
  592. * the original file and in High Availability environments to switch to
  593. * an alternative location for the content in case of server meltdown.
  594. * This can only work if the loop device is used read-only, and if the
  595. * new backing store is the same size and type as the old backing store.
  596. */
  597. static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
  598. unsigned int arg)
  599. {
  600. struct file *file = NULL, *old_file;
  601. int error;
  602. bool partscan;
  603. error = mutex_lock_killable(&loop_ctl_mutex);
  604. if (error)
  605. return error;
  606. error = -ENXIO;
  607. if (lo->lo_state != Lo_bound)
  608. goto out_err;
  609. /* the loop device has to be read-only */
  610. error = -EINVAL;
  611. if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
  612. goto out_err;
  613. error = -EBADF;
  614. file = fget(arg);
  615. if (!file)
  616. goto out_err;
  617. error = loop_validate_file(file, bdev);
  618. if (error)
  619. goto out_err;
  620. old_file = lo->lo_backing_file;
  621. error = -EINVAL;
  622. /* size of the new backing store needs to be the same */
  623. if (get_loop_size(lo, file) != get_loop_size(lo, old_file))
  624. goto out_err;
  625. /* and ... switch */
  626. blk_mq_freeze_queue(lo->lo_queue);
  627. mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
  628. lo->lo_backing_file = file;
  629. lo->old_gfp_mask = mapping_gfp_mask(file->f_mapping);
  630. mapping_set_gfp_mask(file->f_mapping,
  631. lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
  632. loop_update_dio(lo);
  633. blk_mq_unfreeze_queue(lo->lo_queue);
  634. partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
  635. mutex_unlock(&loop_ctl_mutex);
  636. /*
  637. * We must drop file reference outside of loop_ctl_mutex as dropping
  638. * the file ref can take bd_mutex which creates circular locking
  639. * dependency.
  640. */
  641. fput(old_file);
  642. if (partscan)
  643. loop_reread_partitions(lo, bdev);
  644. return 0;
  645. out_err:
  646. mutex_unlock(&loop_ctl_mutex);
  647. if (file)
  648. fput(file);
  649. return error;
  650. }
  651. /* loop sysfs attributes */
  652. static ssize_t loop_attr_show(struct device *dev, char *page,
  653. ssize_t (*callback)(struct loop_device *, char *))
  654. {
  655. struct gendisk *disk = dev_to_disk(dev);
  656. struct loop_device *lo = disk->private_data;
  657. return callback(lo, page);
  658. }
  659. #define LOOP_ATTR_RO(_name) \
  660. static ssize_t loop_attr_##_name##_show(struct loop_device *, char *); \
  661. static ssize_t loop_attr_do_show_##_name(struct device *d, \
  662. struct device_attribute *attr, char *b) \
  663. { \
  664. return loop_attr_show(d, b, loop_attr_##_name##_show); \
  665. } \
  666. static struct device_attribute loop_attr_##_name = \
  667. __ATTR(_name, 0444, loop_attr_do_show_##_name, NULL);
  668. static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
  669. {
  670. ssize_t ret;
  671. char *p = NULL;
  672. spin_lock_irq(&lo->lo_lock);
  673. if (lo->lo_backing_file)
  674. p = file_path(lo->lo_backing_file, buf, PAGE_SIZE - 1);
  675. spin_unlock_irq(&lo->lo_lock);
  676. if (IS_ERR_OR_NULL(p))
  677. ret = PTR_ERR(p);
  678. else {
  679. ret = strlen(p);
  680. memmove(buf, p, ret);
  681. buf[ret++] = '\n';
  682. buf[ret] = 0;
  683. }
  684. return ret;
  685. }
  686. static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
  687. {
  688. return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_offset);
  689. }
  690. static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
  691. {
  692. return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
  693. }
  694. static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
  695. {
  696. int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
  697. return sprintf(buf, "%s\n", autoclear ? "1" : "0");
  698. }
  699. static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
  700. {
  701. int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
  702. return sprintf(buf, "%s\n", partscan ? "1" : "0");
  703. }
  704. static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf)
  705. {
  706. int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO);
  707. return sprintf(buf, "%s\n", dio ? "1" : "0");
  708. }
  709. LOOP_ATTR_RO(backing_file);
  710. LOOP_ATTR_RO(offset);
  711. LOOP_ATTR_RO(sizelimit);
  712. LOOP_ATTR_RO(autoclear);
  713. LOOP_ATTR_RO(partscan);
  714. LOOP_ATTR_RO(dio);
  715. static struct attribute *loop_attrs[] = {
  716. &loop_attr_backing_file.attr,
  717. &loop_attr_offset.attr,
  718. &loop_attr_sizelimit.attr,
  719. &loop_attr_autoclear.attr,
  720. &loop_attr_partscan.attr,
  721. &loop_attr_dio.attr,
  722. NULL,
  723. };
  724. static struct attribute_group loop_attribute_group = {
  725. .name = "loop",
  726. .attrs= loop_attrs,
  727. };
  728. static void loop_sysfs_init(struct loop_device *lo)
  729. {
  730. lo->sysfs_inited = !sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
  731. &loop_attribute_group);
  732. }
  733. static void loop_sysfs_exit(struct loop_device *lo)
  734. {
  735. if (lo->sysfs_inited)
  736. sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
  737. &loop_attribute_group);
  738. }
  739. static void loop_config_discard(struct loop_device *lo)
  740. {
  741. struct file *file = lo->lo_backing_file;
  742. struct inode *inode = file->f_mapping->host;
  743. struct request_queue *q = lo->lo_queue;
  744. u32 granularity, max_discard_sectors;
  745. /*
  746. * If the backing device is a block device, mirror its zeroing
  747. * capability. Set the discard sectors to the block device's zeroing
  748. * capabilities because loop discards result in blkdev_issue_zeroout(),
  749. * not blkdev_issue_discard(). This maintains consistent behavior with
  750. * file-backed loop devices: discarded regions read back as zero.
  751. */
  752. if (S_ISBLK(inode->i_mode) && !lo->lo_encrypt_key_size) {
  753. struct request_queue *backingq;
  754. backingq = bdev_get_queue(inode->i_bdev);
  755. max_discard_sectors = backingq->limits.max_write_zeroes_sectors;
  756. granularity = backingq->limits.discard_granularity ?:
  757. queue_physical_block_size(backingq);
  758. /*
  759. * We use punch hole to reclaim the free space used by the
  760. * image a.k.a. discard. However we do not support discard if
  761. * encryption is enabled, because it may give an attacker
  762. * useful information.
  763. */
  764. } else if (!file->f_op->fallocate || lo->lo_encrypt_key_size) {
  765. max_discard_sectors = 0;
  766. granularity = 0;
  767. } else {
  768. max_discard_sectors = UINT_MAX >> 9;
  769. granularity = inode->i_sb->s_blocksize;
  770. }
  771. if (max_discard_sectors) {
  772. q->limits.discard_granularity = granularity;
  773. blk_queue_max_discard_sectors(q, max_discard_sectors);
  774. blk_queue_max_write_zeroes_sectors(q, max_discard_sectors);
  775. blk_queue_flag_set(QUEUE_FLAG_DISCARD, q);
  776. } else {
  777. q->limits.discard_granularity = 0;
  778. blk_queue_max_discard_sectors(q, 0);
  779. blk_queue_max_write_zeroes_sectors(q, 0);
  780. blk_queue_flag_clear(QUEUE_FLAG_DISCARD, q);
  781. }
  782. q->limits.discard_alignment = 0;
  783. }
  784. static void loop_unprepare_queue(struct loop_device *lo)
  785. {
  786. kthread_flush_worker(&lo->worker);
  787. kthread_stop(lo->worker_task);
  788. }
  789. static int loop_kthread_worker_fn(void *worker_ptr)
  790. {
  791. current->flags |= PF_LESS_THROTTLE | PF_MEMALLOC_NOIO;
  792. return kthread_worker_fn(worker_ptr);
  793. }
  794. static int loop_prepare_queue(struct loop_device *lo)
  795. {
  796. kthread_init_worker(&lo->worker);
  797. lo->worker_task = kthread_run(loop_kthread_worker_fn,
  798. &lo->worker, "loop%d", lo->lo_number);
  799. if (IS_ERR(lo->worker_task))
  800. return -ENOMEM;
  801. set_user_nice(lo->worker_task, MIN_NICE);
  802. return 0;
  803. }
  804. static int loop_set_fd(struct loop_device *lo, fmode_t mode,
  805. struct block_device *bdev, unsigned int arg)
  806. {
  807. struct file *file;
  808. struct inode *inode;
  809. struct address_space *mapping;
  810. int lo_flags = 0;
  811. int error;
  812. loff_t size;
  813. bool partscan;
  814. /* This is safe, since we have a reference from open(). */
  815. __module_get(THIS_MODULE);
  816. error = -EBADF;
  817. file = fget(arg);
  818. if (!file)
  819. goto out;
  820. error = mutex_lock_killable(&loop_ctl_mutex);
  821. if (error)
  822. goto out_putf;
  823. error = -EBUSY;
  824. if (lo->lo_state != Lo_unbound)
  825. goto out_unlock;
  826. error = loop_validate_file(file, bdev);
  827. if (error)
  828. goto out_unlock;
  829. mapping = file->f_mapping;
  830. inode = mapping->host;
  831. if (!(file->f_mode & FMODE_WRITE) || !(mode & FMODE_WRITE) ||
  832. !file->f_op->write_iter)
  833. lo_flags |= LO_FLAGS_READ_ONLY;
  834. error = -EFBIG;
  835. size = get_loop_size(lo, file);
  836. if ((loff_t)(sector_t)size != size)
  837. goto out_unlock;
  838. error = loop_prepare_queue(lo);
  839. if (error)
  840. goto out_unlock;
  841. error = 0;
  842. set_device_ro(bdev, (lo_flags & LO_FLAGS_READ_ONLY) != 0);
  843. lo->use_dio = false;
  844. lo->lo_device = bdev;
  845. lo->lo_flags = lo_flags;
  846. lo->lo_backing_file = file;
  847. lo->transfer = NULL;
  848. lo->ioctl = NULL;
  849. lo->lo_sizelimit = 0;
  850. lo->old_gfp_mask = mapping_gfp_mask(mapping);
  851. mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
  852. if (!(lo_flags & LO_FLAGS_READ_ONLY) && file->f_op->fsync)
  853. blk_queue_write_cache(lo->lo_queue, true, false);
  854. loop_update_dio(lo);
  855. set_capacity(lo->lo_disk, size);
  856. bd_set_size(bdev, size << 9);
  857. loop_sysfs_init(lo);
  858. /* let user-space know about the new size */
  859. kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
  860. set_blocksize(bdev, S_ISBLK(inode->i_mode) ?
  861. block_size(inode->i_bdev) : PAGE_SIZE);
  862. lo->lo_state = Lo_bound;
  863. if (part_shift)
  864. lo->lo_flags |= LO_FLAGS_PARTSCAN;
  865. partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
  866. /* Grab the block_device to prevent its destruction after we
  867. * put /dev/loopXX inode. Later in __loop_clr_fd() we bdput(bdev).
  868. */
  869. bdgrab(bdev);
  870. mutex_unlock(&loop_ctl_mutex);
  871. if (partscan)
  872. loop_reread_partitions(lo, bdev);
  873. return 0;
  874. out_unlock:
  875. mutex_unlock(&loop_ctl_mutex);
  876. out_putf:
  877. fput(file);
  878. out:
  879. /* This is safe: open() is still holding a reference. */
  880. module_put(THIS_MODULE);
  881. return error;
  882. }
  883. static int
  884. loop_release_xfer(struct loop_device *lo)
  885. {
  886. int err = 0;
  887. struct loop_func_table *xfer = lo->lo_encryption;
  888. if (xfer) {
  889. if (xfer->release)
  890. err = xfer->release(lo);
  891. lo->transfer = NULL;
  892. lo->lo_encryption = NULL;
  893. module_put(xfer->owner);
  894. }
  895. return err;
  896. }
  897. static int
  898. loop_init_xfer(struct loop_device *lo, struct loop_func_table *xfer,
  899. const struct loop_info64 *i)
  900. {
  901. int err = 0;
  902. if (xfer) {
  903. struct module *owner = xfer->owner;
  904. if (!try_module_get(owner))
  905. return -EINVAL;
  906. if (xfer->init)
  907. err = xfer->init(lo, i);
  908. if (err)
  909. module_put(owner);
  910. else
  911. lo->lo_encryption = xfer;
  912. }
  913. return err;
  914. }
  915. static int __loop_clr_fd(struct loop_device *lo, bool release)
  916. {
  917. struct file *filp = NULL;
  918. gfp_t gfp = lo->old_gfp_mask;
  919. struct block_device *bdev = lo->lo_device;
  920. int err = 0;
  921. bool partscan = false;
  922. int lo_number;
  923. mutex_lock(&loop_ctl_mutex);
  924. if (WARN_ON_ONCE(lo->lo_state != Lo_rundown)) {
  925. err = -ENXIO;
  926. goto out_unlock;
  927. }
  928. filp = lo->lo_backing_file;
  929. if (filp == NULL) {
  930. err = -EINVAL;
  931. goto out_unlock;
  932. }
  933. /* freeze request queue during the transition */
  934. blk_mq_freeze_queue(lo->lo_queue);
  935. spin_lock_irq(&lo->lo_lock);
  936. lo->lo_backing_file = NULL;
  937. spin_unlock_irq(&lo->lo_lock);
  938. loop_release_xfer(lo);
  939. lo->transfer = NULL;
  940. lo->ioctl = NULL;
  941. lo->lo_device = NULL;
  942. lo->lo_encryption = NULL;
  943. lo->lo_offset = 0;
  944. lo->lo_sizelimit = 0;
  945. lo->lo_encrypt_key_size = 0;
  946. memset(lo->lo_encrypt_key, 0, LO_KEY_SIZE);
  947. memset(lo->lo_crypt_name, 0, LO_NAME_SIZE);
  948. memset(lo->lo_file_name, 0, LO_NAME_SIZE);
  949. blk_queue_logical_block_size(lo->lo_queue, 512);
  950. blk_queue_physical_block_size(lo->lo_queue, 512);
  951. blk_queue_io_min(lo->lo_queue, 512);
  952. if (bdev) {
  953. bdput(bdev);
  954. invalidate_bdev(bdev);
  955. bdev->bd_inode->i_mapping->wb_err = 0;
  956. }
  957. set_capacity(lo->lo_disk, 0);
  958. loop_sysfs_exit(lo);
  959. if (bdev) {
  960. bd_set_size(bdev, 0);
  961. /* let user-space know about this change */
  962. kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
  963. }
  964. mapping_set_gfp_mask(filp->f_mapping, gfp);
  965. /* This is safe: open() is still holding a reference. */
  966. module_put(THIS_MODULE);
  967. blk_mq_unfreeze_queue(lo->lo_queue);
  968. partscan = lo->lo_flags & LO_FLAGS_PARTSCAN && bdev;
  969. lo_number = lo->lo_number;
  970. loop_unprepare_queue(lo);
  971. out_unlock:
  972. mutex_unlock(&loop_ctl_mutex);
  973. if (partscan) {
  974. /*
  975. * bd_mutex has been held already in release path, so don't
  976. * acquire it if this function is called in such case.
  977. *
  978. * If the reread partition isn't from release path, lo_refcnt
  979. * must be at least one and it can only become zero when the
  980. * current holder is released.
  981. */
  982. if (release)
  983. err = __blkdev_reread_part(bdev);
  984. else
  985. err = blkdev_reread_part(bdev);
  986. if (err)
  987. pr_warn("%s: partition scan of loop%d failed (rc=%d)\n",
  988. __func__, lo_number, err);
  989. /* Device is gone, no point in returning error */
  990. err = 0;
  991. }
  992. /*
  993. * lo->lo_state is set to Lo_unbound here after above partscan has
  994. * finished.
  995. *
  996. * There cannot be anybody else entering __loop_clr_fd() as
  997. * lo->lo_backing_file is already cleared and Lo_rundown state
  998. * protects us from all the other places trying to change the 'lo'
  999. * device.
  1000. */
  1001. mutex_lock(&loop_ctl_mutex);
  1002. lo->lo_flags = 0;
  1003. if (!part_shift)
  1004. lo->lo_disk->flags |= GENHD_FL_NO_PART_SCAN;
  1005. lo->lo_state = Lo_unbound;
  1006. mutex_unlock(&loop_ctl_mutex);
  1007. /*
  1008. * Need not hold loop_ctl_mutex to fput backing file.
  1009. * Calling fput holding loop_ctl_mutex triggers a circular
  1010. * lock dependency possibility warning as fput can take
  1011. * bd_mutex which is usually taken before loop_ctl_mutex.
  1012. */
  1013. if (filp)
  1014. fput(filp);
  1015. return err;
  1016. }
  1017. static int loop_clr_fd(struct loop_device *lo)
  1018. {
  1019. int err;
  1020. err = mutex_lock_killable(&loop_ctl_mutex);
  1021. if (err)
  1022. return err;
  1023. if (lo->lo_state != Lo_bound) {
  1024. mutex_unlock(&loop_ctl_mutex);
  1025. return -ENXIO;
  1026. }
  1027. /*
  1028. * If we've explicitly asked to tear down the loop device,
  1029. * and it has an elevated reference count, set it for auto-teardown when
  1030. * the last reference goes away. This stops $!~#$@ udev from
  1031. * preventing teardown because it decided that it needs to run blkid on
  1032. * the loopback device whenever they appear. xfstests is notorious for
  1033. * failing tests because blkid via udev races with a losetup
  1034. * <dev>/do something like mkfs/losetup -d <dev> causing the losetup -d
  1035. * command to fail with EBUSY.
  1036. */
  1037. if (atomic_read(&lo->lo_refcnt) > 1) {
  1038. lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
  1039. mutex_unlock(&loop_ctl_mutex);
  1040. return 0;
  1041. }
  1042. lo->lo_state = Lo_rundown;
  1043. mutex_unlock(&loop_ctl_mutex);
  1044. return __loop_clr_fd(lo, false);
  1045. }
  1046. static int
  1047. loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
  1048. {
  1049. int err;
  1050. struct loop_func_table *xfer;
  1051. kuid_t uid = current_uid();
  1052. struct block_device *bdev;
  1053. bool partscan = false;
  1054. err = mutex_lock_killable(&loop_ctl_mutex);
  1055. if (err)
  1056. return err;
  1057. if (lo->lo_encrypt_key_size &&
  1058. !uid_eq(lo->lo_key_owner, uid) &&
  1059. !capable(CAP_SYS_ADMIN)) {
  1060. err = -EPERM;
  1061. goto out_unlock;
  1062. }
  1063. if (lo->lo_state != Lo_bound) {
  1064. err = -ENXIO;
  1065. goto out_unlock;
  1066. }
  1067. if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE) {
  1068. err = -EINVAL;
  1069. goto out_unlock;
  1070. }
  1071. if (lo->lo_offset != info->lo_offset ||
  1072. lo->lo_sizelimit != info->lo_sizelimit) {
  1073. sync_blockdev(lo->lo_device);
  1074. invalidate_bdev(lo->lo_device);
  1075. }
  1076. /* I/O need to be drained during transfer transition */
  1077. blk_mq_freeze_queue(lo->lo_queue);
  1078. err = loop_release_xfer(lo);
  1079. if (err)
  1080. goto out_unfreeze;
  1081. if (info->lo_encrypt_type) {
  1082. unsigned int type = info->lo_encrypt_type;
  1083. if (type >= MAX_LO_CRYPT) {
  1084. err = -EINVAL;
  1085. goto out_unfreeze;
  1086. }
  1087. xfer = xfer_funcs[type];
  1088. if (xfer == NULL) {
  1089. err = -EINVAL;
  1090. goto out_unfreeze;
  1091. }
  1092. } else
  1093. xfer = NULL;
  1094. err = loop_init_xfer(lo, xfer, info);
  1095. if (err)
  1096. goto out_unfreeze;
  1097. if (lo->lo_offset != info->lo_offset ||
  1098. lo->lo_sizelimit != info->lo_sizelimit) {
  1099. /* kill_bdev should have truncated all the pages */
  1100. if (lo->lo_device->bd_inode->i_mapping->nrpages) {
  1101. err = -EAGAIN;
  1102. pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
  1103. __func__, lo->lo_number, lo->lo_file_name,
  1104. lo->lo_device->bd_inode->i_mapping->nrpages);
  1105. goto out_unfreeze;
  1106. }
  1107. if (figure_loop_size(lo, info->lo_offset, info->lo_sizelimit)) {
  1108. err = -EFBIG;
  1109. goto out_unfreeze;
  1110. }
  1111. }
  1112. loop_config_discard(lo);
  1113. memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
  1114. memcpy(lo->lo_crypt_name, info->lo_crypt_name, LO_NAME_SIZE);
  1115. lo->lo_file_name[LO_NAME_SIZE-1] = 0;
  1116. lo->lo_crypt_name[LO_NAME_SIZE-1] = 0;
  1117. if (!xfer)
  1118. xfer = &none_funcs;
  1119. lo->transfer = xfer->transfer;
  1120. lo->ioctl = xfer->ioctl;
  1121. if ((lo->lo_flags & LO_FLAGS_AUTOCLEAR) !=
  1122. (info->lo_flags & LO_FLAGS_AUTOCLEAR))
  1123. lo->lo_flags ^= LO_FLAGS_AUTOCLEAR;
  1124. lo->lo_encrypt_key_size = info->lo_encrypt_key_size;
  1125. lo->lo_init[0] = info->lo_init[0];
  1126. lo->lo_init[1] = info->lo_init[1];
  1127. if (info->lo_encrypt_key_size) {
  1128. memcpy(lo->lo_encrypt_key, info->lo_encrypt_key,
  1129. info->lo_encrypt_key_size);
  1130. lo->lo_key_owner = uid;
  1131. }
  1132. /* update dio if lo_offset or transfer is changed */
  1133. __loop_update_dio(lo, lo->use_dio);
  1134. out_unfreeze:
  1135. blk_mq_unfreeze_queue(lo->lo_queue);
  1136. if (!err && (info->lo_flags & LO_FLAGS_PARTSCAN) &&
  1137. !(lo->lo_flags & LO_FLAGS_PARTSCAN)) {
  1138. lo->lo_flags |= LO_FLAGS_PARTSCAN;
  1139. lo->lo_disk->flags &= ~GENHD_FL_NO_PART_SCAN;
  1140. bdev = lo->lo_device;
  1141. partscan = true;
  1142. }
  1143. out_unlock:
  1144. mutex_unlock(&loop_ctl_mutex);
  1145. if (partscan)
  1146. loop_reread_partitions(lo, bdev);
  1147. return err;
  1148. }
  1149. static int
  1150. loop_get_status(struct loop_device *lo, struct loop_info64 *info)
  1151. {
  1152. struct path path;
  1153. struct kstat stat;
  1154. int ret;
  1155. ret = mutex_lock_killable(&loop_ctl_mutex);
  1156. if (ret)
  1157. return ret;
  1158. if (lo->lo_state != Lo_bound) {
  1159. mutex_unlock(&loop_ctl_mutex);
  1160. return -ENXIO;
  1161. }
  1162. memset(info, 0, sizeof(*info));
  1163. info->lo_number = lo->lo_number;
  1164. info->lo_offset = lo->lo_offset;
  1165. info->lo_sizelimit = lo->lo_sizelimit;
  1166. info->lo_flags = lo->lo_flags;
  1167. memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
  1168. memcpy(info->lo_crypt_name, lo->lo_crypt_name, LO_NAME_SIZE);
  1169. info->lo_encrypt_type =
  1170. lo->lo_encryption ? lo->lo_encryption->number : 0;
  1171. if (lo->lo_encrypt_key_size && capable(CAP_SYS_ADMIN)) {
  1172. info->lo_encrypt_key_size = lo->lo_encrypt_key_size;
  1173. memcpy(info->lo_encrypt_key, lo->lo_encrypt_key,
  1174. lo->lo_encrypt_key_size);
  1175. }
  1176. /* Drop loop_ctl_mutex while we call into the filesystem. */
  1177. path = lo->lo_backing_file->f_path;
  1178. path_get(&path);
  1179. mutex_unlock(&loop_ctl_mutex);
  1180. ret = vfs_getattr(&path, &stat, STATX_INO, AT_STATX_SYNC_AS_STAT);
  1181. if (!ret) {
  1182. info->lo_device = huge_encode_dev(stat.dev);
  1183. info->lo_inode = stat.ino;
  1184. info->lo_rdevice = huge_encode_dev(stat.rdev);
  1185. }
  1186. path_put(&path);
  1187. return ret;
  1188. }
  1189. static void
  1190. loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
  1191. {
  1192. memset(info64, 0, sizeof(*info64));
  1193. info64->lo_number = info->lo_number;
  1194. info64->lo_device = info->lo_device;
  1195. info64->lo_inode = info->lo_inode;
  1196. info64->lo_rdevice = info->lo_rdevice;
  1197. info64->lo_offset = info->lo_offset;
  1198. info64->lo_sizelimit = 0;
  1199. info64->lo_encrypt_type = info->lo_encrypt_type;
  1200. info64->lo_encrypt_key_size = info->lo_encrypt_key_size;
  1201. info64->lo_flags = info->lo_flags;
  1202. info64->lo_init[0] = info->lo_init[0];
  1203. info64->lo_init[1] = info->lo_init[1];
  1204. if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
  1205. memcpy(info64->lo_crypt_name, info->lo_name, LO_NAME_SIZE);
  1206. else
  1207. memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
  1208. memcpy(info64->lo_encrypt_key, info->lo_encrypt_key, LO_KEY_SIZE);
  1209. }
  1210. static int
  1211. loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
  1212. {
  1213. memset(info, 0, sizeof(*info));
  1214. info->lo_number = info64->lo_number;
  1215. info->lo_device = info64->lo_device;
  1216. info->lo_inode = info64->lo_inode;
  1217. info->lo_rdevice = info64->lo_rdevice;
  1218. info->lo_offset = info64->lo_offset;
  1219. info->lo_encrypt_type = info64->lo_encrypt_type;
  1220. info->lo_encrypt_key_size = info64->lo_encrypt_key_size;
  1221. info->lo_flags = info64->lo_flags;
  1222. info->lo_init[0] = info64->lo_init[0];
  1223. info->lo_init[1] = info64->lo_init[1];
  1224. if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
  1225. memcpy(info->lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
  1226. else
  1227. memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
  1228. memcpy(info->lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
  1229. /* error in case values were truncated */
  1230. if (info->lo_device != info64->lo_device ||
  1231. info->lo_rdevice != info64->lo_rdevice ||
  1232. info->lo_inode != info64->lo_inode ||
  1233. info->lo_offset != info64->lo_offset)
  1234. return -EOVERFLOW;
  1235. return 0;
  1236. }
  1237. static int
  1238. loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
  1239. {
  1240. struct loop_info info;
  1241. struct loop_info64 info64;
  1242. if (copy_from_user(&info, arg, sizeof (struct loop_info)))
  1243. return -EFAULT;
  1244. loop_info64_from_old(&info, &info64);
  1245. return loop_set_status(lo, &info64);
  1246. }
  1247. static int
  1248. loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
  1249. {
  1250. struct loop_info64 info64;
  1251. if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
  1252. return -EFAULT;
  1253. return loop_set_status(lo, &info64);
  1254. }
  1255. static int
  1256. loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
  1257. struct loop_info info;
  1258. struct loop_info64 info64;
  1259. int err;
  1260. if (!arg)
  1261. return -EINVAL;
  1262. err = loop_get_status(lo, &info64);
  1263. if (!err)
  1264. err = loop_info64_to_old(&info64, &info);
  1265. if (!err && copy_to_user(arg, &info, sizeof(info)))
  1266. err = -EFAULT;
  1267. return err;
  1268. }
  1269. static int
  1270. loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
  1271. struct loop_info64 info64;
  1272. int err;
  1273. if (!arg)
  1274. return -EINVAL;
  1275. err = loop_get_status(lo, &info64);
  1276. if (!err && copy_to_user(arg, &info64, sizeof(info64)))
  1277. err = -EFAULT;
  1278. return err;
  1279. }
  1280. static int loop_set_capacity(struct loop_device *lo)
  1281. {
  1282. if (unlikely(lo->lo_state != Lo_bound))
  1283. return -ENXIO;
  1284. return figure_loop_size(lo, lo->lo_offset, lo->lo_sizelimit);
  1285. }
  1286. static int loop_set_dio(struct loop_device *lo, unsigned long arg)
  1287. {
  1288. int error = -ENXIO;
  1289. if (lo->lo_state != Lo_bound)
  1290. goto out;
  1291. __loop_update_dio(lo, !!arg);
  1292. if (lo->use_dio == !!arg)
  1293. return 0;
  1294. error = -EINVAL;
  1295. out:
  1296. return error;
  1297. }
  1298. static int loop_set_block_size(struct loop_device *lo, unsigned long arg)
  1299. {
  1300. int err = 0;
  1301. if (lo->lo_state != Lo_bound)
  1302. return -ENXIO;
  1303. if (arg < 512 || arg > PAGE_SIZE || !is_power_of_2(arg))
  1304. return -EINVAL;
  1305. if (lo->lo_queue->limits.logical_block_size != arg) {
  1306. sync_blockdev(lo->lo_device);
  1307. invalidate_bdev(lo->lo_device);
  1308. }
  1309. blk_mq_freeze_queue(lo->lo_queue);
  1310. /* invalidate_bdev should have truncated all the pages */
  1311. if (lo->lo_queue->limits.logical_block_size != arg &&
  1312. lo->lo_device->bd_inode->i_mapping->nrpages) {
  1313. err = -EAGAIN;
  1314. pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
  1315. __func__, lo->lo_number, lo->lo_file_name,
  1316. lo->lo_device->bd_inode->i_mapping->nrpages);
  1317. goto out_unfreeze;
  1318. }
  1319. blk_queue_logical_block_size(lo->lo_queue, arg);
  1320. blk_queue_physical_block_size(lo->lo_queue, arg);
  1321. blk_queue_io_min(lo->lo_queue, arg);
  1322. loop_update_dio(lo);
  1323. out_unfreeze:
  1324. blk_mq_unfreeze_queue(lo->lo_queue);
  1325. return err;
  1326. }
  1327. static int lo_simple_ioctl(struct loop_device *lo, unsigned int cmd,
  1328. unsigned long arg)
  1329. {
  1330. int err;
  1331. err = mutex_lock_killable(&loop_ctl_mutex);
  1332. if (err)
  1333. return err;
  1334. switch (cmd) {
  1335. case LOOP_SET_CAPACITY:
  1336. err = loop_set_capacity(lo);
  1337. break;
  1338. case LOOP_SET_DIRECT_IO:
  1339. err = loop_set_dio(lo, arg);
  1340. break;
  1341. case LOOP_SET_BLOCK_SIZE:
  1342. err = loop_set_block_size(lo, arg);
  1343. break;
  1344. default:
  1345. err = lo->ioctl ? lo->ioctl(lo, cmd, arg) : -EINVAL;
  1346. }
  1347. mutex_unlock(&loop_ctl_mutex);
  1348. return err;
  1349. }
  1350. static int lo_ioctl(struct block_device *bdev, fmode_t mode,
  1351. unsigned int cmd, unsigned long arg)
  1352. {
  1353. struct loop_device *lo = bdev->bd_disk->private_data;
  1354. int err;
  1355. switch (cmd) {
  1356. case LOOP_SET_FD:
  1357. return loop_set_fd(lo, mode, bdev, arg);
  1358. case LOOP_CHANGE_FD:
  1359. return loop_change_fd(lo, bdev, arg);
  1360. case LOOP_CLR_FD:
  1361. return loop_clr_fd(lo);
  1362. case LOOP_SET_STATUS:
  1363. err = -EPERM;
  1364. if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
  1365. err = loop_set_status_old(lo,
  1366. (struct loop_info __user *)arg);
  1367. }
  1368. break;
  1369. case LOOP_GET_STATUS:
  1370. return loop_get_status_old(lo, (struct loop_info __user *) arg);
  1371. case LOOP_SET_STATUS64:
  1372. err = -EPERM;
  1373. if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
  1374. err = loop_set_status64(lo,
  1375. (struct loop_info64 __user *) arg);
  1376. }
  1377. break;
  1378. case LOOP_GET_STATUS64:
  1379. return loop_get_status64(lo, (struct loop_info64 __user *) arg);
  1380. case LOOP_SET_CAPACITY:
  1381. case LOOP_SET_DIRECT_IO:
  1382. case LOOP_SET_BLOCK_SIZE:
  1383. if (!(mode & FMODE_WRITE) && !capable(CAP_SYS_ADMIN))
  1384. return -EPERM;
  1385. /* Fall through */
  1386. default:
  1387. err = lo_simple_ioctl(lo, cmd, arg);
  1388. break;
  1389. }
  1390. return err;
  1391. }
  1392. #ifdef CONFIG_COMPAT
  1393. struct compat_loop_info {
  1394. compat_int_t lo_number; /* ioctl r/o */
  1395. compat_dev_t lo_device; /* ioctl r/o */
  1396. compat_ulong_t lo_inode; /* ioctl r/o */
  1397. compat_dev_t lo_rdevice; /* ioctl r/o */
  1398. compat_int_t lo_offset;
  1399. compat_int_t lo_encrypt_type;
  1400. compat_int_t lo_encrypt_key_size; /* ioctl w/o */
  1401. compat_int_t lo_flags; /* ioctl r/o */
  1402. char lo_name[LO_NAME_SIZE];
  1403. unsigned char lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
  1404. compat_ulong_t lo_init[2];
  1405. char reserved[4];
  1406. };
  1407. /*
  1408. * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
  1409. * - noinlined to reduce stack space usage in main part of driver
  1410. */
  1411. static noinline int
  1412. loop_info64_from_compat(const struct compat_loop_info __user *arg,
  1413. struct loop_info64 *info64)
  1414. {
  1415. struct compat_loop_info info;
  1416. if (copy_from_user(&info, arg, sizeof(info)))
  1417. return -EFAULT;
  1418. memset(info64, 0, sizeof(*info64));
  1419. info64->lo_number = info.lo_number;
  1420. info64->lo_device = info.lo_device;
  1421. info64->lo_inode = info.lo_inode;
  1422. info64->lo_rdevice = info.lo_rdevice;
  1423. info64->lo_offset = info.lo_offset;
  1424. info64->lo_sizelimit = 0;
  1425. info64->lo_encrypt_type = info.lo_encrypt_type;
  1426. info64->lo_encrypt_key_size = info.lo_encrypt_key_size;
  1427. info64->lo_flags = info.lo_flags;
  1428. info64->lo_init[0] = info.lo_init[0];
  1429. info64->lo_init[1] = info.lo_init[1];
  1430. if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
  1431. memcpy(info64->lo_crypt_name, info.lo_name, LO_NAME_SIZE);
  1432. else
  1433. memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
  1434. memcpy(info64->lo_encrypt_key, info.lo_encrypt_key, LO_KEY_SIZE);
  1435. return 0;
  1436. }
  1437. /*
  1438. * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
  1439. * - noinlined to reduce stack space usage in main part of driver
  1440. */
  1441. static noinline int
  1442. loop_info64_to_compat(const struct loop_info64 *info64,
  1443. struct compat_loop_info __user *arg)
  1444. {
  1445. struct compat_loop_info info;
  1446. memset(&info, 0, sizeof(info));
  1447. info.lo_number = info64->lo_number;
  1448. info.lo_device = info64->lo_device;
  1449. info.lo_inode = info64->lo_inode;
  1450. info.lo_rdevice = info64->lo_rdevice;
  1451. info.lo_offset = info64->lo_offset;
  1452. info.lo_encrypt_type = info64->lo_encrypt_type;
  1453. info.lo_encrypt_key_size = info64->lo_encrypt_key_size;
  1454. info.lo_flags = info64->lo_flags;
  1455. info.lo_init[0] = info64->lo_init[0];
  1456. info.lo_init[1] = info64->lo_init[1];
  1457. if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
  1458. memcpy(info.lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
  1459. else
  1460. memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
  1461. memcpy(info.lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
  1462. /* error in case values were truncated */
  1463. if (info.lo_device != info64->lo_device ||
  1464. info.lo_rdevice != info64->lo_rdevice ||
  1465. info.lo_inode != info64->lo_inode ||
  1466. info.lo_offset != info64->lo_offset ||
  1467. info.lo_init[0] != info64->lo_init[0] ||
  1468. info.lo_init[1] != info64->lo_init[1])
  1469. return -EOVERFLOW;
  1470. if (copy_to_user(arg, &info, sizeof(info)))
  1471. return -EFAULT;
  1472. return 0;
  1473. }
  1474. static int
  1475. loop_set_status_compat(struct loop_device *lo,
  1476. const struct compat_loop_info __user *arg)
  1477. {
  1478. struct loop_info64 info64;
  1479. int ret;
  1480. ret = loop_info64_from_compat(arg, &info64);
  1481. if (ret < 0)
  1482. return ret;
  1483. return loop_set_status(lo, &info64);
  1484. }
  1485. static int
  1486. loop_get_status_compat(struct loop_device *lo,
  1487. struct compat_loop_info __user *arg)
  1488. {
  1489. struct loop_info64 info64;
  1490. int err;
  1491. if (!arg)
  1492. return -EINVAL;
  1493. err = loop_get_status(lo, &info64);
  1494. if (!err)
  1495. err = loop_info64_to_compat(&info64, arg);
  1496. return err;
  1497. }
  1498. static int lo_compat_ioctl(struct block_device *bdev, fmode_t mode,
  1499. unsigned int cmd, unsigned long arg)
  1500. {
  1501. struct loop_device *lo = bdev->bd_disk->private_data;
  1502. int err;
  1503. switch(cmd) {
  1504. case LOOP_SET_STATUS:
  1505. err = loop_set_status_compat(lo,
  1506. (const struct compat_loop_info __user *)arg);
  1507. break;
  1508. case LOOP_GET_STATUS:
  1509. err = loop_get_status_compat(lo,
  1510. (struct compat_loop_info __user *)arg);
  1511. break;
  1512. case LOOP_SET_CAPACITY:
  1513. case LOOP_CLR_FD:
  1514. case LOOP_GET_STATUS64:
  1515. case LOOP_SET_STATUS64:
  1516. arg = (unsigned long) compat_ptr(arg);
  1517. /* fall through */
  1518. case LOOP_SET_FD:
  1519. case LOOP_CHANGE_FD:
  1520. case LOOP_SET_BLOCK_SIZE:
  1521. case LOOP_SET_DIRECT_IO:
  1522. err = lo_ioctl(bdev, mode, cmd, arg);
  1523. break;
  1524. default:
  1525. err = -ENOIOCTLCMD;
  1526. break;
  1527. }
  1528. return err;
  1529. }
  1530. #endif
  1531. static int lo_open(struct block_device *bdev, fmode_t mode)
  1532. {
  1533. struct loop_device *lo;
  1534. int err;
  1535. err = mutex_lock_killable(&loop_ctl_mutex);
  1536. if (err)
  1537. return err;
  1538. lo = bdev->bd_disk->private_data;
  1539. if (!lo) {
  1540. err = -ENXIO;
  1541. goto out;
  1542. }
  1543. atomic_inc(&lo->lo_refcnt);
  1544. out:
  1545. mutex_unlock(&loop_ctl_mutex);
  1546. return err;
  1547. }
  1548. static void lo_release(struct gendisk *disk, fmode_t mode)
  1549. {
  1550. struct loop_device *lo;
  1551. mutex_lock(&loop_ctl_mutex);
  1552. lo = disk->private_data;
  1553. if (atomic_dec_return(&lo->lo_refcnt))
  1554. goto out_unlock;
  1555. if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
  1556. if (lo->lo_state != Lo_bound)
  1557. goto out_unlock;
  1558. lo->lo_state = Lo_rundown;
  1559. mutex_unlock(&loop_ctl_mutex);
  1560. /*
  1561. * In autoclear mode, stop the loop thread
  1562. * and remove configuration after last close.
  1563. */
  1564. __loop_clr_fd(lo, true);
  1565. return;
  1566. } else if (lo->lo_state == Lo_bound) {
  1567. /*
  1568. * Otherwise keep thread (if running) and config,
  1569. * but flush possible ongoing bios in thread.
  1570. */
  1571. blk_mq_freeze_queue(lo->lo_queue);
  1572. blk_mq_unfreeze_queue(lo->lo_queue);
  1573. }
  1574. out_unlock:
  1575. mutex_unlock(&loop_ctl_mutex);
  1576. }
  1577. static const struct block_device_operations lo_fops = {
  1578. .owner = THIS_MODULE,
  1579. .open = lo_open,
  1580. .release = lo_release,
  1581. .ioctl = lo_ioctl,
  1582. #ifdef CONFIG_COMPAT
  1583. .compat_ioctl = lo_compat_ioctl,
  1584. #endif
  1585. };
  1586. /*
  1587. * And now the modules code and kernel interface.
  1588. */
  1589. static int max_loop;
  1590. module_param(max_loop, int, 0444);
  1591. MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
  1592. module_param(max_part, int, 0444);
  1593. MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
  1594. MODULE_LICENSE("GPL");
  1595. MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
  1596. int loop_register_transfer(struct loop_func_table *funcs)
  1597. {
  1598. unsigned int n = funcs->number;
  1599. if (n >= MAX_LO_CRYPT || xfer_funcs[n])
  1600. return -EINVAL;
  1601. xfer_funcs[n] = funcs;
  1602. return 0;
  1603. }
  1604. static int unregister_transfer_cb(int id, void *ptr, void *data)
  1605. {
  1606. struct loop_device *lo = ptr;
  1607. struct loop_func_table *xfer = data;
  1608. mutex_lock(&loop_ctl_mutex);
  1609. if (lo->lo_encryption == xfer)
  1610. loop_release_xfer(lo);
  1611. mutex_unlock(&loop_ctl_mutex);
  1612. return 0;
  1613. }
  1614. int loop_unregister_transfer(int number)
  1615. {
  1616. unsigned int n = number;
  1617. struct loop_func_table *xfer;
  1618. if (n == 0 || n >= MAX_LO_CRYPT || (xfer = xfer_funcs[n]) == NULL)
  1619. return -EINVAL;
  1620. xfer_funcs[n] = NULL;
  1621. idr_for_each(&loop_index_idr, &unregister_transfer_cb, xfer);
  1622. return 0;
  1623. }
  1624. EXPORT_SYMBOL(loop_register_transfer);
  1625. EXPORT_SYMBOL(loop_unregister_transfer);
  1626. static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
  1627. const struct blk_mq_queue_data *bd)
  1628. {
  1629. struct request *rq = bd->rq;
  1630. struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
  1631. struct loop_device *lo = rq->q->queuedata;
  1632. blk_mq_start_request(rq);
  1633. if (lo->lo_state != Lo_bound)
  1634. return BLK_STS_IOERR;
  1635. switch (req_op(rq)) {
  1636. case REQ_OP_FLUSH:
  1637. case REQ_OP_DISCARD:
  1638. case REQ_OP_WRITE_ZEROES:
  1639. cmd->use_aio = false;
  1640. break;
  1641. default:
  1642. cmd->use_aio = lo->use_dio;
  1643. break;
  1644. }
  1645. /* always use the first bio's css */
  1646. #ifdef CONFIG_BLK_CGROUP
  1647. if (cmd->use_aio && rq->bio && rq->bio->bi_css) {
  1648. cmd->css = rq->bio->bi_css;
  1649. css_get(cmd->css);
  1650. } else
  1651. #endif
  1652. cmd->css = NULL;
  1653. kthread_queue_work(&lo->worker, &cmd->work);
  1654. return BLK_STS_OK;
  1655. }
  1656. static void loop_handle_cmd(struct loop_cmd *cmd)
  1657. {
  1658. struct request *rq = blk_mq_rq_from_pdu(cmd);
  1659. const bool write = op_is_write(req_op(rq));
  1660. struct loop_device *lo = rq->q->queuedata;
  1661. int ret = 0;
  1662. if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
  1663. ret = -EIO;
  1664. goto failed;
  1665. }
  1666. ret = do_req_filebacked(lo, rq);
  1667. failed:
  1668. /* complete non-aio request */
  1669. if (!cmd->use_aio || ret) {
  1670. cmd->ret = ret ? -EIO : 0;
  1671. blk_mq_complete_request(rq);
  1672. }
  1673. }
  1674. static void loop_queue_work(struct kthread_work *work)
  1675. {
  1676. struct loop_cmd *cmd =
  1677. container_of(work, struct loop_cmd, work);
  1678. loop_handle_cmd(cmd);
  1679. }
  1680. static int loop_init_request(struct blk_mq_tag_set *set, struct request *rq,
  1681. unsigned int hctx_idx, unsigned int numa_node)
  1682. {
  1683. struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
  1684. kthread_init_work(&cmd->work, loop_queue_work);
  1685. return 0;
  1686. }
  1687. static const struct blk_mq_ops loop_mq_ops = {
  1688. .queue_rq = loop_queue_rq,
  1689. .init_request = loop_init_request,
  1690. .complete = lo_complete_rq,
  1691. };
  1692. static int loop_add(struct loop_device **l, int i)
  1693. {
  1694. struct loop_device *lo;
  1695. struct gendisk *disk;
  1696. int err;
  1697. err = -ENOMEM;
  1698. lo = kzalloc(sizeof(*lo), GFP_KERNEL);
  1699. if (!lo)
  1700. goto out;
  1701. lo->lo_state = Lo_unbound;
  1702. /* allocate id, if @id >= 0, we're requesting that specific id */
  1703. if (i >= 0) {
  1704. err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
  1705. if (err == -ENOSPC)
  1706. err = -EEXIST;
  1707. } else {
  1708. err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
  1709. }
  1710. if (err < 0)
  1711. goto out_free_dev;
  1712. i = err;
  1713. err = -ENOMEM;
  1714. lo->tag_set.ops = &loop_mq_ops;
  1715. lo->tag_set.nr_hw_queues = 1;
  1716. lo->tag_set.queue_depth = 128;
  1717. lo->tag_set.numa_node = NUMA_NO_NODE;
  1718. lo->tag_set.cmd_size = sizeof(struct loop_cmd);
  1719. lo->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_SG_MERGE;
  1720. lo->tag_set.driver_data = lo;
  1721. err = blk_mq_alloc_tag_set(&lo->tag_set);
  1722. if (err)
  1723. goto out_free_idr;
  1724. lo->lo_queue = blk_mq_init_queue(&lo->tag_set);
  1725. if (IS_ERR_OR_NULL(lo->lo_queue)) {
  1726. err = PTR_ERR(lo->lo_queue);
  1727. goto out_cleanup_tags;
  1728. }
  1729. lo->lo_queue->queuedata = lo;
  1730. blk_queue_max_hw_sectors(lo->lo_queue, BLK_DEF_MAX_SECTORS);
  1731. /*
  1732. * By default, we do buffer IO, so it doesn't make sense to enable
  1733. * merge because the I/O submitted to backing file is handled page by
  1734. * page. For directio mode, merge does help to dispatch bigger request
  1735. * to underlayer disk. We will enable merge once directio is enabled.
  1736. */
  1737. blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
  1738. err = -ENOMEM;
  1739. disk = lo->lo_disk = alloc_disk(1 << part_shift);
  1740. if (!disk)
  1741. goto out_free_queue;
  1742. /*
  1743. * Disable partition scanning by default. The in-kernel partition
  1744. * scanning can be requested individually per-device during its
  1745. * setup. Userspace can always add and remove partitions from all
  1746. * devices. The needed partition minors are allocated from the
  1747. * extended minor space, the main loop device numbers will continue
  1748. * to match the loop minors, regardless of the number of partitions
  1749. * used.
  1750. *
  1751. * If max_part is given, partition scanning is globally enabled for
  1752. * all loop devices. The minors for the main loop devices will be
  1753. * multiples of max_part.
  1754. *
  1755. * Note: Global-for-all-devices, set-only-at-init, read-only module
  1756. * parameteters like 'max_loop' and 'max_part' make things needlessly
  1757. * complicated, are too static, inflexible and may surprise
  1758. * userspace tools. Parameters like this in general should be avoided.
  1759. */
  1760. if (!part_shift)
  1761. disk->flags |= GENHD_FL_NO_PART_SCAN;
  1762. disk->flags |= GENHD_FL_EXT_DEVT;
  1763. atomic_set(&lo->lo_refcnt, 0);
  1764. lo->lo_number = i;
  1765. spin_lock_init(&lo->lo_lock);
  1766. disk->major = LOOP_MAJOR;
  1767. disk->first_minor = i << part_shift;
  1768. disk->fops = &lo_fops;
  1769. disk->private_data = lo;
  1770. disk->queue = lo->lo_queue;
  1771. sprintf(disk->disk_name, "loop%d", i);
  1772. add_disk(disk);
  1773. *l = lo;
  1774. return lo->lo_number;
  1775. out_free_queue:
  1776. blk_cleanup_queue(lo->lo_queue);
  1777. out_cleanup_tags:
  1778. blk_mq_free_tag_set(&lo->tag_set);
  1779. out_free_idr:
  1780. idr_remove(&loop_index_idr, i);
  1781. out_free_dev:
  1782. kfree(lo);
  1783. out:
  1784. return err;
  1785. }
  1786. static void loop_remove(struct loop_device *lo)
  1787. {
  1788. del_gendisk(lo->lo_disk);
  1789. blk_cleanup_queue(lo->lo_queue);
  1790. blk_mq_free_tag_set(&lo->tag_set);
  1791. put_disk(lo->lo_disk);
  1792. kfree(lo);
  1793. }
  1794. static int find_free_cb(int id, void *ptr, void *data)
  1795. {
  1796. struct loop_device *lo = ptr;
  1797. struct loop_device **l = data;
  1798. if (lo->lo_state == Lo_unbound) {
  1799. *l = lo;
  1800. return 1;
  1801. }
  1802. return 0;
  1803. }
  1804. static int loop_lookup(struct loop_device **l, int i)
  1805. {
  1806. struct loop_device *lo;
  1807. int ret = -ENODEV;
  1808. if (i < 0) {
  1809. int err;
  1810. err = idr_for_each(&loop_index_idr, &find_free_cb, &lo);
  1811. if (err == 1) {
  1812. *l = lo;
  1813. ret = lo->lo_number;
  1814. }
  1815. goto out;
  1816. }
  1817. /* lookup and return a specific i */
  1818. lo = idr_find(&loop_index_idr, i);
  1819. if (lo) {
  1820. *l = lo;
  1821. ret = lo->lo_number;
  1822. }
  1823. out:
  1824. return ret;
  1825. }
  1826. static struct kobject *loop_probe(dev_t dev, int *part, void *data)
  1827. {
  1828. struct loop_device *lo;
  1829. struct kobject *kobj;
  1830. int err;
  1831. mutex_lock(&loop_ctl_mutex);
  1832. err = loop_lookup(&lo, MINOR(dev) >> part_shift);
  1833. if (err < 0)
  1834. err = loop_add(&lo, MINOR(dev) >> part_shift);
  1835. if (err < 0)
  1836. kobj = NULL;
  1837. else
  1838. kobj = get_disk_and_module(lo->lo_disk);
  1839. mutex_unlock(&loop_ctl_mutex);
  1840. *part = 0;
  1841. return kobj;
  1842. }
  1843. static long loop_control_ioctl(struct file *file, unsigned int cmd,
  1844. unsigned long parm)
  1845. {
  1846. struct loop_device *lo;
  1847. int ret;
  1848. ret = mutex_lock_killable(&loop_ctl_mutex);
  1849. if (ret)
  1850. return ret;
  1851. ret = -ENOSYS;
  1852. switch (cmd) {
  1853. case LOOP_CTL_ADD:
  1854. ret = loop_lookup(&lo, parm);
  1855. if (ret >= 0) {
  1856. ret = -EEXIST;
  1857. break;
  1858. }
  1859. ret = loop_add(&lo, parm);
  1860. break;
  1861. case LOOP_CTL_REMOVE:
  1862. ret = loop_lookup(&lo, parm);
  1863. if (ret < 0)
  1864. break;
  1865. if (lo->lo_state != Lo_unbound) {
  1866. ret = -EBUSY;
  1867. break;
  1868. }
  1869. if (atomic_read(&lo->lo_refcnt) > 0) {
  1870. ret = -EBUSY;
  1871. break;
  1872. }
  1873. lo->lo_disk->private_data = NULL;
  1874. idr_remove(&loop_index_idr, lo->lo_number);
  1875. loop_remove(lo);
  1876. break;
  1877. case LOOP_CTL_GET_FREE:
  1878. ret = loop_lookup(&lo, -1);
  1879. if (ret >= 0)
  1880. break;
  1881. ret = loop_add(&lo, -1);
  1882. }
  1883. mutex_unlock(&loop_ctl_mutex);
  1884. return ret;
  1885. }
  1886. static const struct file_operations loop_ctl_fops = {
  1887. .open = nonseekable_open,
  1888. .unlocked_ioctl = loop_control_ioctl,
  1889. .compat_ioctl = loop_control_ioctl,
  1890. .owner = THIS_MODULE,
  1891. .llseek = noop_llseek,
  1892. };
  1893. static struct miscdevice loop_misc = {
  1894. .minor = LOOP_CTRL_MINOR,
  1895. .name = "loop-control",
  1896. .fops = &loop_ctl_fops,
  1897. };
  1898. MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
  1899. MODULE_ALIAS("devname:loop-control");
  1900. static int __init loop_init(void)
  1901. {
  1902. int i, nr;
  1903. unsigned long range;
  1904. struct loop_device *lo;
  1905. int err;
  1906. part_shift = 0;
  1907. if (max_part > 0) {
  1908. part_shift = fls(max_part);
  1909. /*
  1910. * Adjust max_part according to part_shift as it is exported
  1911. * to user space so that user can decide correct minor number
  1912. * if [s]he want to create more devices.
  1913. *
  1914. * Note that -1 is required because partition 0 is reserved
  1915. * for the whole disk.
  1916. */
  1917. max_part = (1UL << part_shift) - 1;
  1918. }
  1919. if ((1UL << part_shift) > DISK_MAX_PARTS) {
  1920. err = -EINVAL;
  1921. goto err_out;
  1922. }
  1923. if (max_loop > 1UL << (MINORBITS - part_shift)) {
  1924. err = -EINVAL;
  1925. goto err_out;
  1926. }
  1927. /*
  1928. * If max_loop is specified, create that many devices upfront.
  1929. * This also becomes a hard limit. If max_loop is not specified,
  1930. * create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
  1931. * init time. Loop devices can be requested on-demand with the
  1932. * /dev/loop-control interface, or be instantiated by accessing
  1933. * a 'dead' device node.
  1934. */
  1935. if (max_loop) {
  1936. nr = max_loop;
  1937. range = max_loop << part_shift;
  1938. } else {
  1939. nr = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
  1940. range = 1UL << MINORBITS;
  1941. }
  1942. err = misc_register(&loop_misc);
  1943. if (err < 0)
  1944. goto err_out;
  1945. if (register_blkdev(LOOP_MAJOR, "loop")) {
  1946. err = -EIO;
  1947. goto misc_out;
  1948. }
  1949. blk_register_region(MKDEV(LOOP_MAJOR, 0), range,
  1950. THIS_MODULE, loop_probe, NULL, NULL);
  1951. /* pre-create number of devices given by config or max_loop */
  1952. mutex_lock(&loop_ctl_mutex);
  1953. for (i = 0; i < nr; i++)
  1954. loop_add(&lo, i);
  1955. mutex_unlock(&loop_ctl_mutex);
  1956. printk(KERN_INFO "loop: module loaded\n");
  1957. return 0;
  1958. misc_out:
  1959. misc_deregister(&loop_misc);
  1960. err_out:
  1961. return err;
  1962. }
  1963. static int loop_exit_cb(int id, void *ptr, void *data)
  1964. {
  1965. struct loop_device *lo = ptr;
  1966. loop_remove(lo);
  1967. return 0;
  1968. }
  1969. static void __exit loop_exit(void)
  1970. {
  1971. unsigned long range;
  1972. range = max_loop ? max_loop << part_shift : 1UL << MINORBITS;
  1973. mutex_lock(&loop_ctl_mutex);
  1974. idr_for_each(&loop_index_idr, &loop_exit_cb, NULL);
  1975. idr_destroy(&loop_index_idr);
  1976. blk_unregister_region(MKDEV(LOOP_MAJOR, 0), range);
  1977. unregister_blkdev(LOOP_MAJOR, "loop");
  1978. misc_deregister(&loop_misc);
  1979. mutex_unlock(&loop_ctl_mutex);
  1980. }
  1981. module_init(loop_init);
  1982. module_exit(loop_exit);
  1983. #ifndef MODULE
  1984. static int __init max_loop_setup(char *str)
  1985. {
  1986. max_loop = simple_strtol(str, NULL, 0);
  1987. return 1;
  1988. }
  1989. __setup("max_loop=", max_loop_setup);
  1990. #endif