loop.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright 1993 by Theodore Ts'o.
  4. */
  5. #include <linux/module.h>
  6. #include <linux/moduleparam.h>
  7. #include <linux/sched.h>
  8. #include <linux/fs.h>
  9. #include <linux/pagemap.h>
  10. #include <linux/file.h>
  11. #include <linux/stat.h>
  12. #include <linux/errno.h>
  13. #include <linux/major.h>
  14. #include <linux/wait.h>
  15. #include <linux/blkpg.h>
  16. #include <linux/init.h>
  17. #include <linux/swap.h>
  18. #include <linux/slab.h>
  19. #include <linux/compat.h>
  20. #include <linux/suspend.h>
  21. #include <linux/freezer.h>
  22. #include <linux/mutex.h>
  23. #include <linux/writeback.h>
  24. #include <linux/completion.h>
  25. #include <linux/highmem.h>
  26. #include <linux/splice.h>
  27. #include <linux/sysfs.h>
  28. #include <linux/miscdevice.h>
  29. #include <linux/falloc.h>
  30. #include <linux/uio.h>
  31. #include <linux/ioprio.h>
  32. #include <linux/blk-cgroup.h>
  33. #include <linux/sched/mm.h>
  34. #include <linux/statfs.h>
  35. #include <linux/uaccess.h>
  36. #include <linux/blk-mq.h>
  37. #include <linux/spinlock.h>
  38. #include <uapi/linux/loop.h>
  39. /* Possible states of device */
  40. enum {
  41. Lo_unbound,
  42. Lo_bound,
  43. Lo_rundown,
  44. Lo_deleting,
  45. };
  46. struct loop_func_table;
  47. struct loop_device {
  48. int lo_number;
  49. loff_t lo_offset;
  50. loff_t lo_sizelimit;
  51. int lo_flags;
  52. char lo_file_name[LO_NAME_SIZE];
  53. struct file * lo_backing_file;
  54. struct block_device *lo_device;
  55. gfp_t old_gfp_mask;
  56. spinlock_t lo_lock;
  57. int lo_state;
  58. spinlock_t lo_work_lock;
  59. struct workqueue_struct *workqueue;
  60. struct work_struct rootcg_work;
  61. struct list_head rootcg_cmd_list;
  62. struct list_head idle_worker_list;
  63. struct rb_root worker_tree;
  64. struct timer_list timer;
  65. bool use_dio;
  66. bool sysfs_inited;
  67. struct request_queue *lo_queue;
  68. struct blk_mq_tag_set tag_set;
  69. struct gendisk *lo_disk;
  70. struct mutex lo_mutex;
  71. bool idr_visible;
  72. };
  73. struct loop_cmd {
  74. struct list_head list_entry;
  75. bool use_aio; /* use AIO interface to handle I/O */
  76. atomic_t ref; /* only for aio */
  77. long ret;
  78. struct kiocb iocb;
  79. struct bio_vec *bvec;
  80. struct cgroup_subsys_state *blkcg_css;
  81. struct cgroup_subsys_state *memcg_css;
  82. };
  83. #define LOOP_IDLE_WORKER_TIMEOUT (60 * HZ)
  84. #define LOOP_DEFAULT_HW_Q_DEPTH 128
  85. static DEFINE_IDR(loop_index_idr);
  86. static DEFINE_MUTEX(loop_ctl_mutex);
  87. static DEFINE_MUTEX(loop_validate_mutex);
  88. /**
  89. * loop_global_lock_killable() - take locks for safe loop_validate_file() test
  90. *
  91. * @lo: struct loop_device
  92. * @global: true if @lo is about to bind another "struct loop_device", false otherwise
  93. *
  94. * Returns 0 on success, -EINTR otherwise.
  95. *
  96. * Since loop_validate_file() traverses on other "struct loop_device" if
  97. * is_loop_device() is true, we need a global lock for serializing concurrent
  98. * loop_configure()/loop_change_fd()/__loop_clr_fd() calls.
  99. */
  100. static int loop_global_lock_killable(struct loop_device *lo, bool global)
  101. {
  102. int err;
  103. if (global) {
  104. err = mutex_lock_killable(&loop_validate_mutex);
  105. if (err)
  106. return err;
  107. }
  108. err = mutex_lock_killable(&lo->lo_mutex);
  109. if (err && global)
  110. mutex_unlock(&loop_validate_mutex);
  111. return err;
  112. }
  113. /**
  114. * loop_global_unlock() - release locks taken by loop_global_lock_killable()
  115. *
  116. * @lo: struct loop_device
  117. * @global: true if @lo was about to bind another "struct loop_device", false otherwise
  118. */
  119. static void loop_global_unlock(struct loop_device *lo, bool global)
  120. {
  121. mutex_unlock(&lo->lo_mutex);
  122. if (global)
  123. mutex_unlock(&loop_validate_mutex);
  124. }
  125. static int max_part;
  126. static int part_shift;
  127. static loff_t get_size(loff_t offset, loff_t sizelimit, struct file *file)
  128. {
  129. loff_t loopsize;
  130. /* Compute loopsize in bytes */
  131. loopsize = i_size_read(file->f_mapping->host);
  132. if (offset > 0)
  133. loopsize -= offset;
  134. /* offset is beyond i_size, weird but possible */
  135. if (loopsize < 0)
  136. return 0;
  137. if (sizelimit > 0 && sizelimit < loopsize)
  138. loopsize = sizelimit;
  139. /*
  140. * Unfortunately, if we want to do I/O on the device,
  141. * the number of 512-byte sectors has to fit into a sector_t.
  142. */
  143. return loopsize >> 9;
  144. }
  145. static loff_t get_loop_size(struct loop_device *lo, struct file *file)
  146. {
  147. return get_size(lo->lo_offset, lo->lo_sizelimit, file);
  148. }
  149. /*
  150. * We support direct I/O only if lo_offset is aligned with the logical I/O size
  151. * of backing device, and the logical block size of loop is bigger than that of
  152. * the backing device.
  153. */
  154. static bool lo_bdev_can_use_dio(struct loop_device *lo,
  155. struct block_device *backing_bdev)
  156. {
  157. unsigned int sb_bsize = bdev_logical_block_size(backing_bdev);
  158. if (queue_logical_block_size(lo->lo_queue) < sb_bsize)
  159. return false;
  160. if (lo->lo_offset & (sb_bsize - 1))
  161. return false;
  162. return true;
  163. }
  164. static void __loop_update_dio(struct loop_device *lo, bool dio)
  165. {
  166. struct file *file = lo->lo_backing_file;
  167. struct inode *inode = file->f_mapping->host;
  168. struct block_device *backing_bdev = NULL;
  169. bool use_dio;
  170. if (S_ISBLK(inode->i_mode))
  171. backing_bdev = I_BDEV(inode);
  172. else if (inode->i_sb->s_bdev)
  173. backing_bdev = inode->i_sb->s_bdev;
  174. use_dio = dio && (file->f_mode & FMODE_CAN_ODIRECT) &&
  175. (!backing_bdev || lo_bdev_can_use_dio(lo, backing_bdev));
  176. if (lo->use_dio == use_dio)
  177. return;
  178. /* flush dirty pages before changing direct IO */
  179. vfs_fsync(file, 0);
  180. /*
  181. * The flag of LO_FLAGS_DIRECT_IO is handled similarly with
  182. * LO_FLAGS_READ_ONLY, both are set from kernel, and losetup
  183. * will get updated by ioctl(LOOP_GET_STATUS)
  184. */
  185. if (lo->lo_state == Lo_bound)
  186. blk_mq_freeze_queue(lo->lo_queue);
  187. lo->use_dio = use_dio;
  188. if (use_dio)
  189. lo->lo_flags |= LO_FLAGS_DIRECT_IO;
  190. else
  191. lo->lo_flags &= ~LO_FLAGS_DIRECT_IO;
  192. if (lo->lo_state == Lo_bound)
  193. blk_mq_unfreeze_queue(lo->lo_queue);
  194. }
  195. /**
  196. * loop_set_size() - sets device size and notifies userspace
  197. * @lo: struct loop_device to set the size for
  198. * @size: new size of the loop device
  199. *
  200. * Callers must validate that the size passed into this function fits into
  201. * a sector_t, eg using loop_validate_size()
  202. */
  203. static void loop_set_size(struct loop_device *lo, loff_t size)
  204. {
  205. if (!set_capacity_and_notify(lo->lo_disk, size))
  206. kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
  207. }
  208. static int lo_write_bvec(struct file *file, struct bio_vec *bvec, loff_t *ppos)
  209. {
  210. struct iov_iter i;
  211. ssize_t bw;
  212. iov_iter_bvec(&i, ITER_SOURCE, bvec, 1, bvec->bv_len);
  213. bw = vfs_iter_write(file, &i, ppos, 0);
  214. if (likely(bw == bvec->bv_len))
  215. return 0;
  216. printk_ratelimited(KERN_ERR
  217. "loop: Write error at byte offset %llu, length %i.\n",
  218. (unsigned long long)*ppos, bvec->bv_len);
  219. if (bw >= 0)
  220. bw = -EIO;
  221. return bw;
  222. }
  223. static int lo_write_simple(struct loop_device *lo, struct request *rq,
  224. loff_t pos)
  225. {
  226. struct bio_vec bvec;
  227. struct req_iterator iter;
  228. int ret = 0;
  229. rq_for_each_segment(bvec, rq, iter) {
  230. ret = lo_write_bvec(lo->lo_backing_file, &bvec, &pos);
  231. if (ret < 0)
  232. break;
  233. cond_resched();
  234. }
  235. return ret;
  236. }
  237. static int lo_read_simple(struct loop_device *lo, struct request *rq,
  238. loff_t pos)
  239. {
  240. struct bio_vec bvec;
  241. struct req_iterator iter;
  242. struct iov_iter i;
  243. ssize_t len;
  244. rq_for_each_segment(bvec, rq, iter) {
  245. iov_iter_bvec(&i, ITER_DEST, &bvec, 1, bvec.bv_len);
  246. len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
  247. if (len < 0)
  248. return len;
  249. flush_dcache_page(bvec.bv_page);
  250. if (len != bvec.bv_len) {
  251. struct bio *bio;
  252. __rq_for_each_bio(bio, rq)
  253. zero_fill_bio(bio);
  254. break;
  255. }
  256. cond_resched();
  257. }
  258. return 0;
  259. }
  260. static void loop_clear_limits(struct loop_device *lo, int mode)
  261. {
  262. struct queue_limits lim = queue_limits_start_update(lo->lo_queue);
  263. if (mode & FALLOC_FL_ZERO_RANGE)
  264. lim.max_write_zeroes_sectors = 0;
  265. if (mode & FALLOC_FL_PUNCH_HOLE) {
  266. lim.max_hw_discard_sectors = 0;
  267. lim.discard_granularity = 0;
  268. }
  269. queue_limits_commit_update(lo->lo_queue, &lim);
  270. }
  271. static int lo_fallocate(struct loop_device *lo, struct request *rq, loff_t pos,
  272. int mode)
  273. {
  274. /*
  275. * We use fallocate to manipulate the space mappings used by the image
  276. * a.k.a. discard/zerorange.
  277. */
  278. struct file *file = lo->lo_backing_file;
  279. int ret;
  280. mode |= FALLOC_FL_KEEP_SIZE;
  281. if (!bdev_max_discard_sectors(lo->lo_device))
  282. return -EOPNOTSUPP;
  283. ret = file->f_op->fallocate(file, mode, pos, blk_rq_bytes(rq));
  284. if (unlikely(ret && ret != -EINVAL && ret != -EOPNOTSUPP))
  285. return -EIO;
  286. /*
  287. * We initially configure the limits in a hope that fallocate is
  288. * supported and clear them here if that turns out not to be true.
  289. */
  290. if (unlikely(ret == -EOPNOTSUPP))
  291. loop_clear_limits(lo, mode);
  292. return ret;
  293. }
  294. static int lo_req_flush(struct loop_device *lo, struct request *rq)
  295. {
  296. int ret = vfs_fsync(lo->lo_backing_file, 0);
  297. if (unlikely(ret && ret != -EINVAL))
  298. ret = -EIO;
  299. return ret;
  300. }
  301. static void lo_complete_rq(struct request *rq)
  302. {
  303. struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
  304. blk_status_t ret = BLK_STS_OK;
  305. if (!cmd->use_aio || cmd->ret < 0 || cmd->ret == blk_rq_bytes(rq) ||
  306. req_op(rq) != REQ_OP_READ) {
  307. if (cmd->ret < 0)
  308. ret = errno_to_blk_status(cmd->ret);
  309. goto end_io;
  310. }
  311. /*
  312. * Short READ - if we got some data, advance our request and
  313. * retry it. If we got no data, end the rest with EIO.
  314. */
  315. if (cmd->ret) {
  316. blk_update_request(rq, BLK_STS_OK, cmd->ret);
  317. cmd->ret = 0;
  318. blk_mq_requeue_request(rq, true);
  319. } else {
  320. if (cmd->use_aio) {
  321. struct bio *bio = rq->bio;
  322. while (bio) {
  323. zero_fill_bio(bio);
  324. bio = bio->bi_next;
  325. }
  326. }
  327. ret = BLK_STS_IOERR;
  328. end_io:
  329. blk_mq_end_request(rq, ret);
  330. }
  331. }
  332. static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
  333. {
  334. struct request *rq = blk_mq_rq_from_pdu(cmd);
  335. if (!atomic_dec_and_test(&cmd->ref))
  336. return;
  337. kfree(cmd->bvec);
  338. cmd->bvec = NULL;
  339. if (likely(!blk_should_fake_timeout(rq->q)))
  340. blk_mq_complete_request(rq);
  341. }
  342. static void lo_rw_aio_complete(struct kiocb *iocb, long ret)
  343. {
  344. struct loop_cmd *cmd = container_of(iocb, struct loop_cmd, iocb);
  345. cmd->ret = ret;
  346. lo_rw_aio_do_completion(cmd);
  347. }
  348. static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
  349. loff_t pos, int rw)
  350. {
  351. struct iov_iter iter;
  352. struct req_iterator rq_iter;
  353. struct bio_vec *bvec;
  354. struct request *rq = blk_mq_rq_from_pdu(cmd);
  355. struct bio *bio = rq->bio;
  356. struct file *file = lo->lo_backing_file;
  357. struct bio_vec tmp;
  358. unsigned int offset;
  359. int nr_bvec = 0;
  360. int ret;
  361. rq_for_each_bvec(tmp, rq, rq_iter)
  362. nr_bvec++;
  363. if (rq->bio != rq->biotail) {
  364. bvec = kmalloc_array(nr_bvec, sizeof(struct bio_vec),
  365. GFP_NOIO);
  366. if (!bvec)
  367. return -EIO;
  368. cmd->bvec = bvec;
  369. /*
  370. * The bios of the request may be started from the middle of
  371. * the 'bvec' because of bio splitting, so we can't directly
  372. * copy bio->bi_iov_vec to new bvec. The rq_for_each_bvec
  373. * API will take care of all details for us.
  374. */
  375. rq_for_each_bvec(tmp, rq, rq_iter) {
  376. *bvec = tmp;
  377. bvec++;
  378. }
  379. bvec = cmd->bvec;
  380. offset = 0;
  381. } else {
  382. /*
  383. * Same here, this bio may be started from the middle of the
  384. * 'bvec' because of bio splitting, so offset from the bvec
  385. * must be passed to iov iterator
  386. */
  387. offset = bio->bi_iter.bi_bvec_done;
  388. bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
  389. }
  390. atomic_set(&cmd->ref, 2);
  391. iov_iter_bvec(&iter, rw, bvec, nr_bvec, blk_rq_bytes(rq));
  392. iter.iov_offset = offset;
  393. cmd->iocb.ki_pos = pos;
  394. cmd->iocb.ki_filp = file;
  395. cmd->iocb.ki_complete = lo_rw_aio_complete;
  396. cmd->iocb.ki_flags = IOCB_DIRECT;
  397. cmd->iocb.ki_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
  398. if (rw == ITER_SOURCE)
  399. ret = file->f_op->write_iter(&cmd->iocb, &iter);
  400. else
  401. ret = file->f_op->read_iter(&cmd->iocb, &iter);
  402. lo_rw_aio_do_completion(cmd);
  403. if (ret != -EIOCBQUEUED)
  404. lo_rw_aio_complete(&cmd->iocb, ret);
  405. return 0;
  406. }
  407. static int do_req_filebacked(struct loop_device *lo, struct request *rq)
  408. {
  409. struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
  410. loff_t pos = ((loff_t) blk_rq_pos(rq) << 9) + lo->lo_offset;
  411. /*
  412. * lo_write_simple and lo_read_simple should have been covered
  413. * by io submit style function like lo_rw_aio(), one blocker
  414. * is that lo_read_simple() need to call flush_dcache_page after
  415. * the page is written from kernel, and it isn't easy to handle
  416. * this in io submit style function which submits all segments
  417. * of the req at one time. And direct read IO doesn't need to
  418. * run flush_dcache_page().
  419. */
  420. switch (req_op(rq)) {
  421. case REQ_OP_FLUSH:
  422. return lo_req_flush(lo, rq);
  423. case REQ_OP_WRITE_ZEROES:
  424. /*
  425. * If the caller doesn't want deallocation, call zeroout to
  426. * write zeroes the range. Otherwise, punch them out.
  427. */
  428. return lo_fallocate(lo, rq, pos,
  429. (rq->cmd_flags & REQ_NOUNMAP) ?
  430. FALLOC_FL_ZERO_RANGE :
  431. FALLOC_FL_PUNCH_HOLE);
  432. case REQ_OP_DISCARD:
  433. return lo_fallocate(lo, rq, pos, FALLOC_FL_PUNCH_HOLE);
  434. case REQ_OP_WRITE:
  435. if (cmd->use_aio)
  436. return lo_rw_aio(lo, cmd, pos, ITER_SOURCE);
  437. else
  438. return lo_write_simple(lo, rq, pos);
  439. case REQ_OP_READ:
  440. if (cmd->use_aio)
  441. return lo_rw_aio(lo, cmd, pos, ITER_DEST);
  442. else
  443. return lo_read_simple(lo, rq, pos);
  444. default:
  445. WARN_ON_ONCE(1);
  446. return -EIO;
  447. }
  448. }
  449. static inline void loop_update_dio(struct loop_device *lo)
  450. {
  451. __loop_update_dio(lo, (lo->lo_backing_file->f_flags & O_DIRECT) |
  452. lo->use_dio);
  453. }
  454. static void loop_reread_partitions(struct loop_device *lo)
  455. {
  456. int rc;
  457. mutex_lock(&lo->lo_disk->open_mutex);
  458. rc = bdev_disk_changed(lo->lo_disk, false);
  459. mutex_unlock(&lo->lo_disk->open_mutex);
  460. if (rc)
  461. pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
  462. __func__, lo->lo_number, lo->lo_file_name, rc);
  463. }
  464. static inline int is_loop_device(struct file *file)
  465. {
  466. struct inode *i = file->f_mapping->host;
  467. return i && S_ISBLK(i->i_mode) && imajor(i) == LOOP_MAJOR;
  468. }
  469. static int loop_validate_file(struct file *file, struct block_device *bdev)
  470. {
  471. struct inode *inode = file->f_mapping->host;
  472. struct file *f = file;
  473. /* Avoid recursion */
  474. while (is_loop_device(f)) {
  475. struct loop_device *l;
  476. lockdep_assert_held(&loop_validate_mutex);
  477. if (f->f_mapping->host->i_rdev == bdev->bd_dev)
  478. return -EBADF;
  479. l = I_BDEV(f->f_mapping->host)->bd_disk->private_data;
  480. if (l->lo_state != Lo_bound)
  481. return -EINVAL;
  482. /* Order wrt setting lo->lo_backing_file in loop_configure(). */
  483. rmb();
  484. f = l->lo_backing_file;
  485. }
  486. if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
  487. return -EINVAL;
  488. return 0;
  489. }
  490. /*
  491. * loop_change_fd switched the backing store of a loopback device to
  492. * a new file. This is useful for operating system installers to free up
  493. * the original file and in High Availability environments to switch to
  494. * an alternative location for the content in case of server meltdown.
  495. * This can only work if the loop device is used read-only, and if the
  496. * new backing store is the same size and type as the old backing store.
  497. */
  498. static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
  499. unsigned int arg)
  500. {
  501. struct file *file = fget(arg);
  502. struct file *old_file;
  503. int error;
  504. bool partscan;
  505. bool is_loop;
  506. if (!file)
  507. return -EBADF;
  508. /* suppress uevents while reconfiguring the device */
  509. dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 1);
  510. is_loop = is_loop_device(file);
  511. error = loop_global_lock_killable(lo, is_loop);
  512. if (error)
  513. goto out_putf;
  514. error = -ENXIO;
  515. if (lo->lo_state != Lo_bound)
  516. goto out_err;
  517. /* the loop device has to be read-only */
  518. error = -EINVAL;
  519. if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
  520. goto out_err;
  521. error = loop_validate_file(file, bdev);
  522. if (error)
  523. goto out_err;
  524. old_file = lo->lo_backing_file;
  525. error = -EINVAL;
  526. /* size of the new backing store needs to be the same */
  527. if (get_loop_size(lo, file) != get_loop_size(lo, old_file))
  528. goto out_err;
  529. /* and ... switch */
  530. disk_force_media_change(lo->lo_disk);
  531. blk_mq_freeze_queue(lo->lo_queue);
  532. mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
  533. lo->lo_backing_file = file;
  534. lo->old_gfp_mask = mapping_gfp_mask(file->f_mapping);
  535. mapping_set_gfp_mask(file->f_mapping,
  536. lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
  537. loop_update_dio(lo);
  538. blk_mq_unfreeze_queue(lo->lo_queue);
  539. partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
  540. loop_global_unlock(lo, is_loop);
  541. /*
  542. * Flush loop_validate_file() before fput(), for l->lo_backing_file
  543. * might be pointing at old_file which might be the last reference.
  544. */
  545. if (!is_loop) {
  546. mutex_lock(&loop_validate_mutex);
  547. mutex_unlock(&loop_validate_mutex);
  548. }
  549. /*
  550. * We must drop file reference outside of lo_mutex as dropping
  551. * the file ref can take open_mutex which creates circular locking
  552. * dependency.
  553. */
  554. fput(old_file);
  555. if (partscan)
  556. loop_reread_partitions(lo);
  557. error = 0;
  558. done:
  559. /* enable and uncork uevent now that we are done */
  560. dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 0);
  561. return error;
  562. out_err:
  563. loop_global_unlock(lo, is_loop);
  564. out_putf:
  565. fput(file);
  566. goto done;
  567. }
  568. /* loop sysfs attributes */
  569. static ssize_t loop_attr_show(struct device *dev, char *page,
  570. ssize_t (*callback)(struct loop_device *, char *))
  571. {
  572. struct gendisk *disk = dev_to_disk(dev);
  573. struct loop_device *lo = disk->private_data;
  574. return callback(lo, page);
  575. }
  576. #define LOOP_ATTR_RO(_name) \
  577. static ssize_t loop_attr_##_name##_show(struct loop_device *, char *); \
  578. static ssize_t loop_attr_do_show_##_name(struct device *d, \
  579. struct device_attribute *attr, char *b) \
  580. { \
  581. return loop_attr_show(d, b, loop_attr_##_name##_show); \
  582. } \
  583. static struct device_attribute loop_attr_##_name = \
  584. __ATTR(_name, 0444, loop_attr_do_show_##_name, NULL);
  585. static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
  586. {
  587. ssize_t ret;
  588. char *p = NULL;
  589. spin_lock_irq(&lo->lo_lock);
  590. if (lo->lo_backing_file)
  591. p = file_path(lo->lo_backing_file, buf, PAGE_SIZE - 1);
  592. spin_unlock_irq(&lo->lo_lock);
  593. if (IS_ERR_OR_NULL(p))
  594. ret = PTR_ERR(p);
  595. else {
  596. ret = strlen(p);
  597. memmove(buf, p, ret);
  598. buf[ret++] = '\n';
  599. buf[ret] = 0;
  600. }
  601. return ret;
  602. }
  603. static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
  604. {
  605. return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_offset);
  606. }
  607. static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
  608. {
  609. return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
  610. }
  611. static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
  612. {
  613. int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
  614. return sysfs_emit(buf, "%s\n", autoclear ? "1" : "0");
  615. }
  616. static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
  617. {
  618. int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
  619. return sysfs_emit(buf, "%s\n", partscan ? "1" : "0");
  620. }
  621. static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf)
  622. {
  623. int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO);
  624. return sysfs_emit(buf, "%s\n", dio ? "1" : "0");
  625. }
  626. LOOP_ATTR_RO(backing_file);
  627. LOOP_ATTR_RO(offset);
  628. LOOP_ATTR_RO(sizelimit);
  629. LOOP_ATTR_RO(autoclear);
  630. LOOP_ATTR_RO(partscan);
  631. LOOP_ATTR_RO(dio);
  632. static struct attribute *loop_attrs[] = {
  633. &loop_attr_backing_file.attr,
  634. &loop_attr_offset.attr,
  635. &loop_attr_sizelimit.attr,
  636. &loop_attr_autoclear.attr,
  637. &loop_attr_partscan.attr,
  638. &loop_attr_dio.attr,
  639. NULL,
  640. };
  641. static struct attribute_group loop_attribute_group = {
  642. .name = "loop",
  643. .attrs= loop_attrs,
  644. };
  645. static void loop_sysfs_init(struct loop_device *lo)
  646. {
  647. lo->sysfs_inited = !sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
  648. &loop_attribute_group);
  649. }
  650. static void loop_sysfs_exit(struct loop_device *lo)
  651. {
  652. if (lo->sysfs_inited)
  653. sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
  654. &loop_attribute_group);
  655. }
  656. static void loop_config_discard(struct loop_device *lo,
  657. struct queue_limits *lim)
  658. {
  659. struct file *file = lo->lo_backing_file;
  660. struct inode *inode = file->f_mapping->host;
  661. u32 granularity = 0, max_discard_sectors = 0;
  662. struct kstatfs sbuf;
  663. /*
  664. * If the backing device is a block device, mirror its zeroing
  665. * capability. Set the discard sectors to the block device's zeroing
  666. * capabilities because loop discards result in blkdev_issue_zeroout(),
  667. * not blkdev_issue_discard(). This maintains consistent behavior with
  668. * file-backed loop devices: discarded regions read back as zero.
  669. */
  670. if (S_ISBLK(inode->i_mode)) {
  671. struct request_queue *backingq = bdev_get_queue(I_BDEV(inode));
  672. max_discard_sectors = backingq->limits.max_write_zeroes_sectors;
  673. granularity = bdev_discard_granularity(I_BDEV(inode)) ?:
  674. queue_physical_block_size(backingq);
  675. /*
  676. * We use punch hole to reclaim the free space used by the
  677. * image a.k.a. discard.
  678. */
  679. } else if (file->f_op->fallocate && !vfs_statfs(&file->f_path, &sbuf)) {
  680. max_discard_sectors = UINT_MAX >> 9;
  681. granularity = sbuf.f_bsize;
  682. }
  683. lim->max_hw_discard_sectors = max_discard_sectors;
  684. lim->max_write_zeroes_sectors = max_discard_sectors;
  685. if (max_discard_sectors)
  686. lim->discard_granularity = granularity;
  687. else
  688. lim->discard_granularity = 0;
  689. }
  690. struct loop_worker {
  691. struct rb_node rb_node;
  692. struct work_struct work;
  693. struct list_head cmd_list;
  694. struct list_head idle_list;
  695. struct loop_device *lo;
  696. struct cgroup_subsys_state *blkcg_css;
  697. unsigned long last_ran_at;
  698. };
  699. static void loop_workfn(struct work_struct *work);
  700. #ifdef CONFIG_BLK_CGROUP
  701. static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
  702. {
  703. return !css || css == blkcg_root_css;
  704. }
  705. #else
  706. static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
  707. {
  708. return !css;
  709. }
  710. #endif
  711. static void loop_queue_work(struct loop_device *lo, struct loop_cmd *cmd)
  712. {
  713. struct rb_node **node, *parent = NULL;
  714. struct loop_worker *cur_worker, *worker = NULL;
  715. struct work_struct *work;
  716. struct list_head *cmd_list;
  717. spin_lock_irq(&lo->lo_work_lock);
  718. if (queue_on_root_worker(cmd->blkcg_css))
  719. goto queue_work;
  720. node = &lo->worker_tree.rb_node;
  721. while (*node) {
  722. parent = *node;
  723. cur_worker = container_of(*node, struct loop_worker, rb_node);
  724. if (cur_worker->blkcg_css == cmd->blkcg_css) {
  725. worker = cur_worker;
  726. break;
  727. } else if ((long)cur_worker->blkcg_css < (long)cmd->blkcg_css) {
  728. node = &(*node)->rb_left;
  729. } else {
  730. node = &(*node)->rb_right;
  731. }
  732. }
  733. if (worker)
  734. goto queue_work;
  735. worker = kzalloc(sizeof(struct loop_worker), GFP_NOWAIT | __GFP_NOWARN);
  736. /*
  737. * In the event we cannot allocate a worker, just queue on the
  738. * rootcg worker and issue the I/O as the rootcg
  739. */
  740. if (!worker) {
  741. cmd->blkcg_css = NULL;
  742. if (cmd->memcg_css)
  743. css_put(cmd->memcg_css);
  744. cmd->memcg_css = NULL;
  745. goto queue_work;
  746. }
  747. worker->blkcg_css = cmd->blkcg_css;
  748. css_get(worker->blkcg_css);
  749. INIT_WORK(&worker->work, loop_workfn);
  750. INIT_LIST_HEAD(&worker->cmd_list);
  751. INIT_LIST_HEAD(&worker->idle_list);
  752. worker->lo = lo;
  753. rb_link_node(&worker->rb_node, parent, node);
  754. rb_insert_color(&worker->rb_node, &lo->worker_tree);
  755. queue_work:
  756. if (worker) {
  757. /*
  758. * We need to remove from the idle list here while
  759. * holding the lock so that the idle timer doesn't
  760. * free the worker
  761. */
  762. if (!list_empty(&worker->idle_list))
  763. list_del_init(&worker->idle_list);
  764. work = &worker->work;
  765. cmd_list = &worker->cmd_list;
  766. } else {
  767. work = &lo->rootcg_work;
  768. cmd_list = &lo->rootcg_cmd_list;
  769. }
  770. list_add_tail(&cmd->list_entry, cmd_list);
  771. queue_work(lo->workqueue, work);
  772. spin_unlock_irq(&lo->lo_work_lock);
  773. }
  774. static void loop_set_timer(struct loop_device *lo)
  775. {
  776. timer_reduce(&lo->timer, jiffies + LOOP_IDLE_WORKER_TIMEOUT);
  777. }
  778. static void loop_free_idle_workers(struct loop_device *lo, bool delete_all)
  779. {
  780. struct loop_worker *pos, *worker;
  781. spin_lock_irq(&lo->lo_work_lock);
  782. list_for_each_entry_safe(worker, pos, &lo->idle_worker_list,
  783. idle_list) {
  784. if (!delete_all &&
  785. time_is_after_jiffies(worker->last_ran_at +
  786. LOOP_IDLE_WORKER_TIMEOUT))
  787. break;
  788. list_del(&worker->idle_list);
  789. rb_erase(&worker->rb_node, &lo->worker_tree);
  790. css_put(worker->blkcg_css);
  791. kfree(worker);
  792. }
  793. if (!list_empty(&lo->idle_worker_list))
  794. loop_set_timer(lo);
  795. spin_unlock_irq(&lo->lo_work_lock);
  796. }
  797. static void loop_free_idle_workers_timer(struct timer_list *timer)
  798. {
  799. struct loop_device *lo = container_of(timer, struct loop_device, timer);
  800. return loop_free_idle_workers(lo, false);
  801. }
  802. /**
  803. * loop_set_status_from_info - configure device from loop_info
  804. * @lo: struct loop_device to configure
  805. * @info: struct loop_info64 to configure the device with
  806. *
  807. * Configures the loop device parameters according to the passed
  808. * in loop_info64 configuration.
  809. */
  810. static int
  811. loop_set_status_from_info(struct loop_device *lo,
  812. const struct loop_info64 *info)
  813. {
  814. if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE)
  815. return -EINVAL;
  816. switch (info->lo_encrypt_type) {
  817. case LO_CRYPT_NONE:
  818. break;
  819. case LO_CRYPT_XOR:
  820. pr_warn("support for the xor transformation has been removed.\n");
  821. return -EINVAL;
  822. case LO_CRYPT_CRYPTOAPI:
  823. pr_warn("support for cryptoloop has been removed. Use dm-crypt instead.\n");
  824. return -EINVAL;
  825. default:
  826. return -EINVAL;
  827. }
  828. /* Avoid assigning overflow values */
  829. if (info->lo_offset > LLONG_MAX || info->lo_sizelimit > LLONG_MAX)
  830. return -EOVERFLOW;
  831. lo->lo_offset = info->lo_offset;
  832. lo->lo_sizelimit = info->lo_sizelimit;
  833. memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
  834. lo->lo_file_name[LO_NAME_SIZE-1] = 0;
  835. lo->lo_flags = info->lo_flags;
  836. return 0;
  837. }
  838. static unsigned int loop_default_blocksize(struct loop_device *lo,
  839. struct block_device *backing_bdev)
  840. {
  841. /* In case of direct I/O, match underlying block size */
  842. if ((lo->lo_backing_file->f_flags & O_DIRECT) && backing_bdev)
  843. return bdev_logical_block_size(backing_bdev);
  844. return SECTOR_SIZE;
  845. }
  846. static int loop_reconfigure_limits(struct loop_device *lo, unsigned int bsize)
  847. {
  848. struct file *file = lo->lo_backing_file;
  849. struct inode *inode = file->f_mapping->host;
  850. struct block_device *backing_bdev = NULL;
  851. struct queue_limits lim;
  852. if (S_ISBLK(inode->i_mode))
  853. backing_bdev = I_BDEV(inode);
  854. else if (inode->i_sb->s_bdev)
  855. backing_bdev = inode->i_sb->s_bdev;
  856. if (!bsize)
  857. bsize = loop_default_blocksize(lo, backing_bdev);
  858. lim = queue_limits_start_update(lo->lo_queue);
  859. lim.logical_block_size = bsize;
  860. lim.physical_block_size = bsize;
  861. lim.io_min = bsize;
  862. lim.features &= ~(BLK_FEAT_WRITE_CACHE | BLK_FEAT_ROTATIONAL);
  863. if (file->f_op->fsync && !(lo->lo_flags & LO_FLAGS_READ_ONLY))
  864. lim.features |= BLK_FEAT_WRITE_CACHE;
  865. if (backing_bdev && !bdev_nonrot(backing_bdev))
  866. lim.features |= BLK_FEAT_ROTATIONAL;
  867. loop_config_discard(lo, &lim);
  868. return queue_limits_commit_update(lo->lo_queue, &lim);
  869. }
  870. static int loop_configure(struct loop_device *lo, blk_mode_t mode,
  871. struct block_device *bdev,
  872. const struct loop_config *config)
  873. {
  874. struct file *file = fget(config->fd);
  875. struct address_space *mapping;
  876. int error;
  877. loff_t size;
  878. bool partscan;
  879. bool is_loop;
  880. if (!file)
  881. return -EBADF;
  882. is_loop = is_loop_device(file);
  883. /* This is safe, since we have a reference from open(). */
  884. __module_get(THIS_MODULE);
  885. /*
  886. * If we don't hold exclusive handle for the device, upgrade to it
  887. * here to avoid changing device under exclusive owner.
  888. */
  889. if (!(mode & BLK_OPEN_EXCL)) {
  890. error = bd_prepare_to_claim(bdev, loop_configure, NULL);
  891. if (error)
  892. goto out_putf;
  893. }
  894. error = loop_global_lock_killable(lo, is_loop);
  895. if (error)
  896. goto out_bdev;
  897. error = -EBUSY;
  898. if (lo->lo_state != Lo_unbound)
  899. goto out_unlock;
  900. error = loop_validate_file(file, bdev);
  901. if (error)
  902. goto out_unlock;
  903. mapping = file->f_mapping;
  904. if ((config->info.lo_flags & ~LOOP_CONFIGURE_SETTABLE_FLAGS) != 0) {
  905. error = -EINVAL;
  906. goto out_unlock;
  907. }
  908. error = loop_set_status_from_info(lo, &config->info);
  909. if (error)
  910. goto out_unlock;
  911. if (!(file->f_mode & FMODE_WRITE) || !(mode & BLK_OPEN_WRITE) ||
  912. !file->f_op->write_iter)
  913. lo->lo_flags |= LO_FLAGS_READ_ONLY;
  914. if (!lo->workqueue) {
  915. lo->workqueue = alloc_workqueue("loop%d",
  916. WQ_UNBOUND | WQ_FREEZABLE,
  917. 0, lo->lo_number);
  918. if (!lo->workqueue) {
  919. error = -ENOMEM;
  920. goto out_unlock;
  921. }
  922. }
  923. /* suppress uevents while reconfiguring the device */
  924. dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 1);
  925. disk_force_media_change(lo->lo_disk);
  926. set_disk_ro(lo->lo_disk, (lo->lo_flags & LO_FLAGS_READ_ONLY) != 0);
  927. lo->use_dio = lo->lo_flags & LO_FLAGS_DIRECT_IO;
  928. lo->lo_device = bdev;
  929. lo->lo_backing_file = file;
  930. lo->old_gfp_mask = mapping_gfp_mask(mapping);
  931. mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
  932. error = loop_reconfigure_limits(lo, config->block_size);
  933. if (error)
  934. goto out_unlock;
  935. loop_update_dio(lo);
  936. loop_sysfs_init(lo);
  937. size = get_loop_size(lo, file);
  938. loop_set_size(lo, size);
  939. /* Order wrt reading lo_state in loop_validate_file(). */
  940. wmb();
  941. lo->lo_state = Lo_bound;
  942. if (part_shift)
  943. lo->lo_flags |= LO_FLAGS_PARTSCAN;
  944. partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
  945. if (partscan)
  946. clear_bit(GD_SUPPRESS_PART_SCAN, &lo->lo_disk->state);
  947. /* enable and uncork uevent now that we are done */
  948. dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 0);
  949. loop_global_unlock(lo, is_loop);
  950. if (partscan)
  951. loop_reread_partitions(lo);
  952. if (!(mode & BLK_OPEN_EXCL))
  953. bd_abort_claiming(bdev, loop_configure);
  954. return 0;
  955. out_unlock:
  956. loop_global_unlock(lo, is_loop);
  957. out_bdev:
  958. if (!(mode & BLK_OPEN_EXCL))
  959. bd_abort_claiming(bdev, loop_configure);
  960. out_putf:
  961. fput(file);
  962. /* This is safe: open() is still holding a reference. */
  963. module_put(THIS_MODULE);
  964. return error;
  965. }
  966. static void __loop_clr_fd(struct loop_device *lo)
  967. {
  968. struct queue_limits lim;
  969. struct file *filp;
  970. gfp_t gfp = lo->old_gfp_mask;
  971. spin_lock_irq(&lo->lo_lock);
  972. filp = lo->lo_backing_file;
  973. lo->lo_backing_file = NULL;
  974. spin_unlock_irq(&lo->lo_lock);
  975. lo->lo_device = NULL;
  976. lo->lo_offset = 0;
  977. lo->lo_sizelimit = 0;
  978. memset(lo->lo_file_name, 0, LO_NAME_SIZE);
  979. /* reset the block size to the default */
  980. lim = queue_limits_start_update(lo->lo_queue);
  981. lim.logical_block_size = SECTOR_SIZE;
  982. lim.physical_block_size = SECTOR_SIZE;
  983. lim.io_min = SECTOR_SIZE;
  984. queue_limits_commit_update(lo->lo_queue, &lim);
  985. invalidate_disk(lo->lo_disk);
  986. loop_sysfs_exit(lo);
  987. /* let user-space know about this change */
  988. kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
  989. mapping_set_gfp_mask(filp->f_mapping, gfp);
  990. /* This is safe: open() is still holding a reference. */
  991. module_put(THIS_MODULE);
  992. disk_force_media_change(lo->lo_disk);
  993. if (lo->lo_flags & LO_FLAGS_PARTSCAN) {
  994. int err;
  995. /*
  996. * open_mutex has been held already in release path, so don't
  997. * acquire it if this function is called in such case.
  998. *
  999. * If the reread partition isn't from release path, lo_refcnt
  1000. * must be at least one and it can only become zero when the
  1001. * current holder is released.
  1002. */
  1003. err = bdev_disk_changed(lo->lo_disk, false);
  1004. if (err)
  1005. pr_warn("%s: partition scan of loop%d failed (rc=%d)\n",
  1006. __func__, lo->lo_number, err);
  1007. /* Device is gone, no point in returning error */
  1008. }
  1009. /*
  1010. * lo->lo_state is set to Lo_unbound here after above partscan has
  1011. * finished. There cannot be anybody else entering __loop_clr_fd() as
  1012. * Lo_rundown state protects us from all the other places trying to
  1013. * change the 'lo' device.
  1014. */
  1015. lo->lo_flags = 0;
  1016. if (!part_shift)
  1017. set_bit(GD_SUPPRESS_PART_SCAN, &lo->lo_disk->state);
  1018. mutex_lock(&lo->lo_mutex);
  1019. lo->lo_state = Lo_unbound;
  1020. mutex_unlock(&lo->lo_mutex);
  1021. /*
  1022. * Need not hold lo_mutex to fput backing file. Calling fput holding
  1023. * lo_mutex triggers a circular lock dependency possibility warning as
  1024. * fput can take open_mutex which is usually taken before lo_mutex.
  1025. */
  1026. fput(filp);
  1027. }
  1028. static int loop_clr_fd(struct loop_device *lo)
  1029. {
  1030. int err;
  1031. /*
  1032. * Since lo_ioctl() is called without locks held, it is possible that
  1033. * loop_configure()/loop_change_fd() and loop_clr_fd() run in parallel.
  1034. *
  1035. * Therefore, use global lock when setting Lo_rundown state in order to
  1036. * make sure that loop_validate_file() will fail if the "struct file"
  1037. * which loop_configure()/loop_change_fd() found via fget() was this
  1038. * loop device.
  1039. */
  1040. err = loop_global_lock_killable(lo, true);
  1041. if (err)
  1042. return err;
  1043. if (lo->lo_state != Lo_bound) {
  1044. loop_global_unlock(lo, true);
  1045. return -ENXIO;
  1046. }
  1047. /*
  1048. * Mark the device for removing the backing device on last close.
  1049. * If we are the only opener, also switch the state to roundown here to
  1050. * prevent new openers from coming in.
  1051. */
  1052. lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
  1053. if (disk_openers(lo->lo_disk) == 1)
  1054. lo->lo_state = Lo_rundown;
  1055. loop_global_unlock(lo, true);
  1056. return 0;
  1057. }
  1058. static int
  1059. loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
  1060. {
  1061. int err;
  1062. int prev_lo_flags;
  1063. bool partscan = false;
  1064. bool size_changed = false;
  1065. err = mutex_lock_killable(&lo->lo_mutex);
  1066. if (err)
  1067. return err;
  1068. if (lo->lo_state != Lo_bound) {
  1069. err = -ENXIO;
  1070. goto out_unlock;
  1071. }
  1072. if (lo->lo_offset != info->lo_offset ||
  1073. lo->lo_sizelimit != info->lo_sizelimit) {
  1074. size_changed = true;
  1075. sync_blockdev(lo->lo_device);
  1076. invalidate_bdev(lo->lo_device);
  1077. }
  1078. /* I/O need to be drained during transfer transition */
  1079. blk_mq_freeze_queue(lo->lo_queue);
  1080. prev_lo_flags = lo->lo_flags;
  1081. err = loop_set_status_from_info(lo, info);
  1082. if (err)
  1083. goto out_unfreeze;
  1084. /* Mask out flags that can't be set using LOOP_SET_STATUS. */
  1085. lo->lo_flags &= LOOP_SET_STATUS_SETTABLE_FLAGS;
  1086. /* For those flags, use the previous values instead */
  1087. lo->lo_flags |= prev_lo_flags & ~LOOP_SET_STATUS_SETTABLE_FLAGS;
  1088. /* For flags that can't be cleared, use previous values too */
  1089. lo->lo_flags |= prev_lo_flags & ~LOOP_SET_STATUS_CLEARABLE_FLAGS;
  1090. if (size_changed) {
  1091. loff_t new_size = get_size(lo->lo_offset, lo->lo_sizelimit,
  1092. lo->lo_backing_file);
  1093. loop_set_size(lo, new_size);
  1094. }
  1095. /* update dio if lo_offset or transfer is changed */
  1096. __loop_update_dio(lo, lo->use_dio);
  1097. out_unfreeze:
  1098. blk_mq_unfreeze_queue(lo->lo_queue);
  1099. if (!err && (lo->lo_flags & LO_FLAGS_PARTSCAN) &&
  1100. !(prev_lo_flags & LO_FLAGS_PARTSCAN)) {
  1101. clear_bit(GD_SUPPRESS_PART_SCAN, &lo->lo_disk->state);
  1102. partscan = true;
  1103. }
  1104. out_unlock:
  1105. mutex_unlock(&lo->lo_mutex);
  1106. if (partscan)
  1107. loop_reread_partitions(lo);
  1108. return err;
  1109. }
  1110. static int
  1111. loop_get_status(struct loop_device *lo, struct loop_info64 *info)
  1112. {
  1113. struct path path;
  1114. struct kstat stat;
  1115. int ret;
  1116. ret = mutex_lock_killable(&lo->lo_mutex);
  1117. if (ret)
  1118. return ret;
  1119. if (lo->lo_state != Lo_bound) {
  1120. mutex_unlock(&lo->lo_mutex);
  1121. return -ENXIO;
  1122. }
  1123. memset(info, 0, sizeof(*info));
  1124. info->lo_number = lo->lo_number;
  1125. info->lo_offset = lo->lo_offset;
  1126. info->lo_sizelimit = lo->lo_sizelimit;
  1127. info->lo_flags = lo->lo_flags;
  1128. memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
  1129. /* Drop lo_mutex while we call into the filesystem. */
  1130. path = lo->lo_backing_file->f_path;
  1131. path_get(&path);
  1132. mutex_unlock(&lo->lo_mutex);
  1133. ret = vfs_getattr(&path, &stat, STATX_INO, AT_STATX_SYNC_AS_STAT);
  1134. if (!ret) {
  1135. info->lo_device = huge_encode_dev(stat.dev);
  1136. info->lo_inode = stat.ino;
  1137. info->lo_rdevice = huge_encode_dev(stat.rdev);
  1138. }
  1139. path_put(&path);
  1140. return ret;
  1141. }
  1142. static void
  1143. loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
  1144. {
  1145. memset(info64, 0, sizeof(*info64));
  1146. info64->lo_number = info->lo_number;
  1147. info64->lo_device = info->lo_device;
  1148. info64->lo_inode = info->lo_inode;
  1149. info64->lo_rdevice = info->lo_rdevice;
  1150. info64->lo_offset = info->lo_offset;
  1151. info64->lo_sizelimit = 0;
  1152. info64->lo_flags = info->lo_flags;
  1153. memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
  1154. }
  1155. static int
  1156. loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
  1157. {
  1158. memset(info, 0, sizeof(*info));
  1159. info->lo_number = info64->lo_number;
  1160. info->lo_device = info64->lo_device;
  1161. info->lo_inode = info64->lo_inode;
  1162. info->lo_rdevice = info64->lo_rdevice;
  1163. info->lo_offset = info64->lo_offset;
  1164. info->lo_flags = info64->lo_flags;
  1165. memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
  1166. /* error in case values were truncated */
  1167. if (info->lo_device != info64->lo_device ||
  1168. info->lo_rdevice != info64->lo_rdevice ||
  1169. info->lo_inode != info64->lo_inode ||
  1170. info->lo_offset != info64->lo_offset)
  1171. return -EOVERFLOW;
  1172. return 0;
  1173. }
  1174. static int
  1175. loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
  1176. {
  1177. struct loop_info info;
  1178. struct loop_info64 info64;
  1179. if (copy_from_user(&info, arg, sizeof (struct loop_info)))
  1180. return -EFAULT;
  1181. loop_info64_from_old(&info, &info64);
  1182. return loop_set_status(lo, &info64);
  1183. }
  1184. static int
  1185. loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
  1186. {
  1187. struct loop_info64 info64;
  1188. if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
  1189. return -EFAULT;
  1190. return loop_set_status(lo, &info64);
  1191. }
  1192. static int
  1193. loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
  1194. struct loop_info info;
  1195. struct loop_info64 info64;
  1196. int err;
  1197. if (!arg)
  1198. return -EINVAL;
  1199. err = loop_get_status(lo, &info64);
  1200. if (!err)
  1201. err = loop_info64_to_old(&info64, &info);
  1202. if (!err && copy_to_user(arg, &info, sizeof(info)))
  1203. err = -EFAULT;
  1204. return err;
  1205. }
  1206. static int
  1207. loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
  1208. struct loop_info64 info64;
  1209. int err;
  1210. if (!arg)
  1211. return -EINVAL;
  1212. err = loop_get_status(lo, &info64);
  1213. if (!err && copy_to_user(arg, &info64, sizeof(info64)))
  1214. err = -EFAULT;
  1215. return err;
  1216. }
  1217. static int loop_set_capacity(struct loop_device *lo)
  1218. {
  1219. loff_t size;
  1220. if (unlikely(lo->lo_state != Lo_bound))
  1221. return -ENXIO;
  1222. size = get_loop_size(lo, lo->lo_backing_file);
  1223. loop_set_size(lo, size);
  1224. return 0;
  1225. }
  1226. static int loop_set_dio(struct loop_device *lo, unsigned long arg)
  1227. {
  1228. int error = -ENXIO;
  1229. if (lo->lo_state != Lo_bound)
  1230. goto out;
  1231. __loop_update_dio(lo, !!arg);
  1232. if (lo->use_dio == !!arg)
  1233. return 0;
  1234. error = -EINVAL;
  1235. out:
  1236. return error;
  1237. }
  1238. static int loop_set_block_size(struct loop_device *lo, unsigned long arg)
  1239. {
  1240. int err = 0;
  1241. if (lo->lo_state != Lo_bound)
  1242. return -ENXIO;
  1243. if (lo->lo_queue->limits.logical_block_size == arg)
  1244. return 0;
  1245. sync_blockdev(lo->lo_device);
  1246. invalidate_bdev(lo->lo_device);
  1247. blk_mq_freeze_queue(lo->lo_queue);
  1248. err = loop_reconfigure_limits(lo, arg);
  1249. loop_update_dio(lo);
  1250. blk_mq_unfreeze_queue(lo->lo_queue);
  1251. return err;
  1252. }
  1253. static int lo_simple_ioctl(struct loop_device *lo, unsigned int cmd,
  1254. unsigned long arg)
  1255. {
  1256. int err;
  1257. err = mutex_lock_killable(&lo->lo_mutex);
  1258. if (err)
  1259. return err;
  1260. switch (cmd) {
  1261. case LOOP_SET_CAPACITY:
  1262. err = loop_set_capacity(lo);
  1263. break;
  1264. case LOOP_SET_DIRECT_IO:
  1265. err = loop_set_dio(lo, arg);
  1266. break;
  1267. case LOOP_SET_BLOCK_SIZE:
  1268. err = loop_set_block_size(lo, arg);
  1269. break;
  1270. default:
  1271. err = -EINVAL;
  1272. }
  1273. mutex_unlock(&lo->lo_mutex);
  1274. return err;
  1275. }
  1276. static int lo_ioctl(struct block_device *bdev, blk_mode_t mode,
  1277. unsigned int cmd, unsigned long arg)
  1278. {
  1279. struct loop_device *lo = bdev->bd_disk->private_data;
  1280. void __user *argp = (void __user *) arg;
  1281. int err;
  1282. switch (cmd) {
  1283. case LOOP_SET_FD: {
  1284. /*
  1285. * Legacy case - pass in a zeroed out struct loop_config with
  1286. * only the file descriptor set , which corresponds with the
  1287. * default parameters we'd have used otherwise.
  1288. */
  1289. struct loop_config config;
  1290. memset(&config, 0, sizeof(config));
  1291. config.fd = arg;
  1292. return loop_configure(lo, mode, bdev, &config);
  1293. }
  1294. case LOOP_CONFIGURE: {
  1295. struct loop_config config;
  1296. if (copy_from_user(&config, argp, sizeof(config)))
  1297. return -EFAULT;
  1298. return loop_configure(lo, mode, bdev, &config);
  1299. }
  1300. case LOOP_CHANGE_FD:
  1301. return loop_change_fd(lo, bdev, arg);
  1302. case LOOP_CLR_FD:
  1303. return loop_clr_fd(lo);
  1304. case LOOP_SET_STATUS:
  1305. err = -EPERM;
  1306. if ((mode & BLK_OPEN_WRITE) || capable(CAP_SYS_ADMIN))
  1307. err = loop_set_status_old(lo, argp);
  1308. break;
  1309. case LOOP_GET_STATUS:
  1310. return loop_get_status_old(lo, argp);
  1311. case LOOP_SET_STATUS64:
  1312. err = -EPERM;
  1313. if ((mode & BLK_OPEN_WRITE) || capable(CAP_SYS_ADMIN))
  1314. err = loop_set_status64(lo, argp);
  1315. break;
  1316. case LOOP_GET_STATUS64:
  1317. return loop_get_status64(lo, argp);
  1318. case LOOP_SET_CAPACITY:
  1319. case LOOP_SET_DIRECT_IO:
  1320. case LOOP_SET_BLOCK_SIZE:
  1321. if (!(mode & BLK_OPEN_WRITE) && !capable(CAP_SYS_ADMIN))
  1322. return -EPERM;
  1323. fallthrough;
  1324. default:
  1325. err = lo_simple_ioctl(lo, cmd, arg);
  1326. break;
  1327. }
  1328. return err;
  1329. }
  1330. #ifdef CONFIG_COMPAT
  1331. struct compat_loop_info {
  1332. compat_int_t lo_number; /* ioctl r/o */
  1333. compat_dev_t lo_device; /* ioctl r/o */
  1334. compat_ulong_t lo_inode; /* ioctl r/o */
  1335. compat_dev_t lo_rdevice; /* ioctl r/o */
  1336. compat_int_t lo_offset;
  1337. compat_int_t lo_encrypt_type; /* obsolete, ignored */
  1338. compat_int_t lo_encrypt_key_size; /* ioctl w/o */
  1339. compat_int_t lo_flags; /* ioctl r/o */
  1340. char lo_name[LO_NAME_SIZE];
  1341. unsigned char lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
  1342. compat_ulong_t lo_init[2];
  1343. char reserved[4];
  1344. };
  1345. /*
  1346. * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
  1347. * - noinlined to reduce stack space usage in main part of driver
  1348. */
  1349. static noinline int
  1350. loop_info64_from_compat(const struct compat_loop_info __user *arg,
  1351. struct loop_info64 *info64)
  1352. {
  1353. struct compat_loop_info info;
  1354. if (copy_from_user(&info, arg, sizeof(info)))
  1355. return -EFAULT;
  1356. memset(info64, 0, sizeof(*info64));
  1357. info64->lo_number = info.lo_number;
  1358. info64->lo_device = info.lo_device;
  1359. info64->lo_inode = info.lo_inode;
  1360. info64->lo_rdevice = info.lo_rdevice;
  1361. info64->lo_offset = info.lo_offset;
  1362. info64->lo_sizelimit = 0;
  1363. info64->lo_flags = info.lo_flags;
  1364. memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
  1365. return 0;
  1366. }
  1367. /*
  1368. * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
  1369. * - noinlined to reduce stack space usage in main part of driver
  1370. */
  1371. static noinline int
  1372. loop_info64_to_compat(const struct loop_info64 *info64,
  1373. struct compat_loop_info __user *arg)
  1374. {
  1375. struct compat_loop_info info;
  1376. memset(&info, 0, sizeof(info));
  1377. info.lo_number = info64->lo_number;
  1378. info.lo_device = info64->lo_device;
  1379. info.lo_inode = info64->lo_inode;
  1380. info.lo_rdevice = info64->lo_rdevice;
  1381. info.lo_offset = info64->lo_offset;
  1382. info.lo_flags = info64->lo_flags;
  1383. memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
  1384. /* error in case values were truncated */
  1385. if (info.lo_device != info64->lo_device ||
  1386. info.lo_rdevice != info64->lo_rdevice ||
  1387. info.lo_inode != info64->lo_inode ||
  1388. info.lo_offset != info64->lo_offset)
  1389. return -EOVERFLOW;
  1390. if (copy_to_user(arg, &info, sizeof(info)))
  1391. return -EFAULT;
  1392. return 0;
  1393. }
  1394. static int
  1395. loop_set_status_compat(struct loop_device *lo,
  1396. const struct compat_loop_info __user *arg)
  1397. {
  1398. struct loop_info64 info64;
  1399. int ret;
  1400. ret = loop_info64_from_compat(arg, &info64);
  1401. if (ret < 0)
  1402. return ret;
  1403. return loop_set_status(lo, &info64);
  1404. }
  1405. static int
  1406. loop_get_status_compat(struct loop_device *lo,
  1407. struct compat_loop_info __user *arg)
  1408. {
  1409. struct loop_info64 info64;
  1410. int err;
  1411. if (!arg)
  1412. return -EINVAL;
  1413. err = loop_get_status(lo, &info64);
  1414. if (!err)
  1415. err = loop_info64_to_compat(&info64, arg);
  1416. return err;
  1417. }
  1418. static int lo_compat_ioctl(struct block_device *bdev, blk_mode_t mode,
  1419. unsigned int cmd, unsigned long arg)
  1420. {
  1421. struct loop_device *lo = bdev->bd_disk->private_data;
  1422. int err;
  1423. switch(cmd) {
  1424. case LOOP_SET_STATUS:
  1425. err = loop_set_status_compat(lo,
  1426. (const struct compat_loop_info __user *)arg);
  1427. break;
  1428. case LOOP_GET_STATUS:
  1429. err = loop_get_status_compat(lo,
  1430. (struct compat_loop_info __user *)arg);
  1431. break;
  1432. case LOOP_SET_CAPACITY:
  1433. case LOOP_CLR_FD:
  1434. case LOOP_GET_STATUS64:
  1435. case LOOP_SET_STATUS64:
  1436. case LOOP_CONFIGURE:
  1437. arg = (unsigned long) compat_ptr(arg);
  1438. fallthrough;
  1439. case LOOP_SET_FD:
  1440. case LOOP_CHANGE_FD:
  1441. case LOOP_SET_BLOCK_SIZE:
  1442. case LOOP_SET_DIRECT_IO:
  1443. err = lo_ioctl(bdev, mode, cmd, arg);
  1444. break;
  1445. default:
  1446. err = -ENOIOCTLCMD;
  1447. break;
  1448. }
  1449. return err;
  1450. }
  1451. #endif
  1452. static int lo_open(struct gendisk *disk, blk_mode_t mode)
  1453. {
  1454. struct loop_device *lo = disk->private_data;
  1455. int err;
  1456. err = mutex_lock_killable(&lo->lo_mutex);
  1457. if (err)
  1458. return err;
  1459. if (lo->lo_state == Lo_deleting || lo->lo_state == Lo_rundown)
  1460. err = -ENXIO;
  1461. mutex_unlock(&lo->lo_mutex);
  1462. return err;
  1463. }
  1464. static void lo_release(struct gendisk *disk)
  1465. {
  1466. struct loop_device *lo = disk->private_data;
  1467. bool need_clear = false;
  1468. if (disk_openers(disk) > 0)
  1469. return;
  1470. /*
  1471. * Clear the backing device information if this is the last close of
  1472. * a device that's been marked for auto clear, or on which LOOP_CLR_FD
  1473. * has been called.
  1474. */
  1475. mutex_lock(&lo->lo_mutex);
  1476. if (lo->lo_state == Lo_bound && (lo->lo_flags & LO_FLAGS_AUTOCLEAR))
  1477. lo->lo_state = Lo_rundown;
  1478. need_clear = (lo->lo_state == Lo_rundown);
  1479. mutex_unlock(&lo->lo_mutex);
  1480. if (need_clear)
  1481. __loop_clr_fd(lo);
  1482. }
  1483. static void lo_free_disk(struct gendisk *disk)
  1484. {
  1485. struct loop_device *lo = disk->private_data;
  1486. if (lo->workqueue)
  1487. destroy_workqueue(lo->workqueue);
  1488. loop_free_idle_workers(lo, true);
  1489. timer_shutdown_sync(&lo->timer);
  1490. mutex_destroy(&lo->lo_mutex);
  1491. kfree(lo);
  1492. }
  1493. static const struct block_device_operations lo_fops = {
  1494. .owner = THIS_MODULE,
  1495. .open = lo_open,
  1496. .release = lo_release,
  1497. .ioctl = lo_ioctl,
  1498. #ifdef CONFIG_COMPAT
  1499. .compat_ioctl = lo_compat_ioctl,
  1500. #endif
  1501. .free_disk = lo_free_disk,
  1502. };
  1503. /*
  1504. * And now the modules code and kernel interface.
  1505. */
  1506. /*
  1507. * If max_loop is specified, create that many devices upfront.
  1508. * This also becomes a hard limit. If max_loop is not specified,
  1509. * the default isn't a hard limit (as before commit 85c50197716c
  1510. * changed the default value from 0 for max_loop=0 reasons), just
  1511. * create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
  1512. * init time. Loop devices can be requested on-demand with the
  1513. * /dev/loop-control interface, or be instantiated by accessing
  1514. * a 'dead' device node.
  1515. */
  1516. static int max_loop = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
  1517. #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
  1518. static bool max_loop_specified;
  1519. static int max_loop_param_set_int(const char *val,
  1520. const struct kernel_param *kp)
  1521. {
  1522. int ret;
  1523. ret = param_set_int(val, kp);
  1524. if (ret < 0)
  1525. return ret;
  1526. max_loop_specified = true;
  1527. return 0;
  1528. }
  1529. static const struct kernel_param_ops max_loop_param_ops = {
  1530. .set = max_loop_param_set_int,
  1531. .get = param_get_int,
  1532. };
  1533. module_param_cb(max_loop, &max_loop_param_ops, &max_loop, 0444);
  1534. MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
  1535. #else
  1536. module_param(max_loop, int, 0444);
  1537. MODULE_PARM_DESC(max_loop, "Initial number of loop devices");
  1538. #endif
  1539. module_param(max_part, int, 0444);
  1540. MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
  1541. static int hw_queue_depth = LOOP_DEFAULT_HW_Q_DEPTH;
  1542. static int loop_set_hw_queue_depth(const char *s, const struct kernel_param *p)
  1543. {
  1544. int qd, ret;
  1545. ret = kstrtoint(s, 0, &qd);
  1546. if (ret < 0)
  1547. return ret;
  1548. if (qd < 1)
  1549. return -EINVAL;
  1550. hw_queue_depth = qd;
  1551. return 0;
  1552. }
  1553. static const struct kernel_param_ops loop_hw_qdepth_param_ops = {
  1554. .set = loop_set_hw_queue_depth,
  1555. .get = param_get_int,
  1556. };
  1557. device_param_cb(hw_queue_depth, &loop_hw_qdepth_param_ops, &hw_queue_depth, 0444);
  1558. MODULE_PARM_DESC(hw_queue_depth, "Queue depth for each hardware queue. Default: " __stringify(LOOP_DEFAULT_HW_Q_DEPTH));
  1559. MODULE_DESCRIPTION("Loopback device support");
  1560. MODULE_LICENSE("GPL");
  1561. MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
  1562. static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
  1563. const struct blk_mq_queue_data *bd)
  1564. {
  1565. struct request *rq = bd->rq;
  1566. struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
  1567. struct loop_device *lo = rq->q->queuedata;
  1568. blk_mq_start_request(rq);
  1569. if (lo->lo_state != Lo_bound)
  1570. return BLK_STS_IOERR;
  1571. switch (req_op(rq)) {
  1572. case REQ_OP_FLUSH:
  1573. case REQ_OP_DISCARD:
  1574. case REQ_OP_WRITE_ZEROES:
  1575. cmd->use_aio = false;
  1576. break;
  1577. default:
  1578. cmd->use_aio = lo->use_dio;
  1579. break;
  1580. }
  1581. /* always use the first bio's css */
  1582. cmd->blkcg_css = NULL;
  1583. cmd->memcg_css = NULL;
  1584. #ifdef CONFIG_BLK_CGROUP
  1585. if (rq->bio) {
  1586. cmd->blkcg_css = bio_blkcg_css(rq->bio);
  1587. #ifdef CONFIG_MEMCG
  1588. if (cmd->blkcg_css) {
  1589. cmd->memcg_css =
  1590. cgroup_get_e_css(cmd->blkcg_css->cgroup,
  1591. &memory_cgrp_subsys);
  1592. }
  1593. #endif
  1594. }
  1595. #endif
  1596. loop_queue_work(lo, cmd);
  1597. return BLK_STS_OK;
  1598. }
  1599. static void loop_handle_cmd(struct loop_cmd *cmd)
  1600. {
  1601. struct cgroup_subsys_state *cmd_blkcg_css = cmd->blkcg_css;
  1602. struct cgroup_subsys_state *cmd_memcg_css = cmd->memcg_css;
  1603. struct request *rq = blk_mq_rq_from_pdu(cmd);
  1604. const bool write = op_is_write(req_op(rq));
  1605. struct loop_device *lo = rq->q->queuedata;
  1606. int ret = 0;
  1607. struct mem_cgroup *old_memcg = NULL;
  1608. const bool use_aio = cmd->use_aio;
  1609. if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
  1610. ret = -EIO;
  1611. goto failed;
  1612. }
  1613. if (cmd_blkcg_css)
  1614. kthread_associate_blkcg(cmd_blkcg_css);
  1615. if (cmd_memcg_css)
  1616. old_memcg = set_active_memcg(
  1617. mem_cgroup_from_css(cmd_memcg_css));
  1618. /*
  1619. * do_req_filebacked() may call blk_mq_complete_request() synchronously
  1620. * or asynchronously if using aio. Hence, do not touch 'cmd' after
  1621. * do_req_filebacked() has returned unless we are sure that 'cmd' has
  1622. * not yet been completed.
  1623. */
  1624. ret = do_req_filebacked(lo, rq);
  1625. if (cmd_blkcg_css)
  1626. kthread_associate_blkcg(NULL);
  1627. if (cmd_memcg_css) {
  1628. set_active_memcg(old_memcg);
  1629. css_put(cmd_memcg_css);
  1630. }
  1631. failed:
  1632. /* complete non-aio request */
  1633. if (!use_aio || ret) {
  1634. if (ret == -EOPNOTSUPP)
  1635. cmd->ret = ret;
  1636. else
  1637. cmd->ret = ret ? -EIO : 0;
  1638. if (likely(!blk_should_fake_timeout(rq->q)))
  1639. blk_mq_complete_request(rq);
  1640. }
  1641. }
  1642. static void loop_process_work(struct loop_worker *worker,
  1643. struct list_head *cmd_list, struct loop_device *lo)
  1644. {
  1645. int orig_flags = current->flags;
  1646. struct loop_cmd *cmd;
  1647. current->flags |= PF_LOCAL_THROTTLE | PF_MEMALLOC_NOIO;
  1648. spin_lock_irq(&lo->lo_work_lock);
  1649. while (!list_empty(cmd_list)) {
  1650. cmd = container_of(
  1651. cmd_list->next, struct loop_cmd, list_entry);
  1652. list_del(cmd_list->next);
  1653. spin_unlock_irq(&lo->lo_work_lock);
  1654. loop_handle_cmd(cmd);
  1655. cond_resched();
  1656. spin_lock_irq(&lo->lo_work_lock);
  1657. }
  1658. /*
  1659. * We only add to the idle list if there are no pending cmds
  1660. * *and* the worker will not run again which ensures that it
  1661. * is safe to free any worker on the idle list
  1662. */
  1663. if (worker && !work_pending(&worker->work)) {
  1664. worker->last_ran_at = jiffies;
  1665. list_add_tail(&worker->idle_list, &lo->idle_worker_list);
  1666. loop_set_timer(lo);
  1667. }
  1668. spin_unlock_irq(&lo->lo_work_lock);
  1669. current->flags = orig_flags;
  1670. }
  1671. static void loop_workfn(struct work_struct *work)
  1672. {
  1673. struct loop_worker *worker =
  1674. container_of(work, struct loop_worker, work);
  1675. loop_process_work(worker, &worker->cmd_list, worker->lo);
  1676. }
  1677. static void loop_rootcg_workfn(struct work_struct *work)
  1678. {
  1679. struct loop_device *lo =
  1680. container_of(work, struct loop_device, rootcg_work);
  1681. loop_process_work(NULL, &lo->rootcg_cmd_list, lo);
  1682. }
  1683. static const struct blk_mq_ops loop_mq_ops = {
  1684. .queue_rq = loop_queue_rq,
  1685. .complete = lo_complete_rq,
  1686. };
  1687. static int loop_add(int i)
  1688. {
  1689. struct queue_limits lim = {
  1690. /*
  1691. * Random number picked from the historic block max_sectors cap.
  1692. */
  1693. .max_hw_sectors = 2560u,
  1694. };
  1695. struct loop_device *lo;
  1696. struct gendisk *disk;
  1697. int err;
  1698. err = -ENOMEM;
  1699. lo = kzalloc(sizeof(*lo), GFP_KERNEL);
  1700. if (!lo)
  1701. goto out;
  1702. lo->worker_tree = RB_ROOT;
  1703. INIT_LIST_HEAD(&lo->idle_worker_list);
  1704. timer_setup(&lo->timer, loop_free_idle_workers_timer, TIMER_DEFERRABLE);
  1705. lo->lo_state = Lo_unbound;
  1706. err = mutex_lock_killable(&loop_ctl_mutex);
  1707. if (err)
  1708. goto out_free_dev;
  1709. /* allocate id, if @id >= 0, we're requesting that specific id */
  1710. if (i >= 0) {
  1711. err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
  1712. if (err == -ENOSPC)
  1713. err = -EEXIST;
  1714. } else {
  1715. err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
  1716. }
  1717. mutex_unlock(&loop_ctl_mutex);
  1718. if (err < 0)
  1719. goto out_free_dev;
  1720. i = err;
  1721. lo->tag_set.ops = &loop_mq_ops;
  1722. lo->tag_set.nr_hw_queues = 1;
  1723. lo->tag_set.queue_depth = hw_queue_depth;
  1724. lo->tag_set.numa_node = NUMA_NO_NODE;
  1725. lo->tag_set.cmd_size = sizeof(struct loop_cmd);
  1726. lo->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_STACKING |
  1727. BLK_MQ_F_NO_SCHED_BY_DEFAULT;
  1728. lo->tag_set.driver_data = lo;
  1729. err = blk_mq_alloc_tag_set(&lo->tag_set);
  1730. if (err)
  1731. goto out_free_idr;
  1732. disk = lo->lo_disk = blk_mq_alloc_disk(&lo->tag_set, &lim, lo);
  1733. if (IS_ERR(disk)) {
  1734. err = PTR_ERR(disk);
  1735. goto out_cleanup_tags;
  1736. }
  1737. lo->lo_queue = lo->lo_disk->queue;
  1738. /*
  1739. * Disable partition scanning by default. The in-kernel partition
  1740. * scanning can be requested individually per-device during its
  1741. * setup. Userspace can always add and remove partitions from all
  1742. * devices. The needed partition minors are allocated from the
  1743. * extended minor space, the main loop device numbers will continue
  1744. * to match the loop minors, regardless of the number of partitions
  1745. * used.
  1746. *
  1747. * If max_part is given, partition scanning is globally enabled for
  1748. * all loop devices. The minors for the main loop devices will be
  1749. * multiples of max_part.
  1750. *
  1751. * Note: Global-for-all-devices, set-only-at-init, read-only module
  1752. * parameteters like 'max_loop' and 'max_part' make things needlessly
  1753. * complicated, are too static, inflexible and may surprise
  1754. * userspace tools. Parameters like this in general should be avoided.
  1755. */
  1756. if (!part_shift)
  1757. set_bit(GD_SUPPRESS_PART_SCAN, &disk->state);
  1758. mutex_init(&lo->lo_mutex);
  1759. lo->lo_number = i;
  1760. spin_lock_init(&lo->lo_lock);
  1761. spin_lock_init(&lo->lo_work_lock);
  1762. INIT_WORK(&lo->rootcg_work, loop_rootcg_workfn);
  1763. INIT_LIST_HEAD(&lo->rootcg_cmd_list);
  1764. disk->major = LOOP_MAJOR;
  1765. disk->first_minor = i << part_shift;
  1766. disk->minors = 1 << part_shift;
  1767. disk->fops = &lo_fops;
  1768. disk->private_data = lo;
  1769. disk->queue = lo->lo_queue;
  1770. disk->events = DISK_EVENT_MEDIA_CHANGE;
  1771. disk->event_flags = DISK_EVENT_FLAG_UEVENT;
  1772. sprintf(disk->disk_name, "loop%d", i);
  1773. /* Make this loop device reachable from pathname. */
  1774. err = add_disk(disk);
  1775. if (err)
  1776. goto out_cleanup_disk;
  1777. /* Show this loop device. */
  1778. mutex_lock(&loop_ctl_mutex);
  1779. lo->idr_visible = true;
  1780. mutex_unlock(&loop_ctl_mutex);
  1781. return i;
  1782. out_cleanup_disk:
  1783. put_disk(disk);
  1784. out_cleanup_tags:
  1785. blk_mq_free_tag_set(&lo->tag_set);
  1786. out_free_idr:
  1787. mutex_lock(&loop_ctl_mutex);
  1788. idr_remove(&loop_index_idr, i);
  1789. mutex_unlock(&loop_ctl_mutex);
  1790. out_free_dev:
  1791. kfree(lo);
  1792. out:
  1793. return err;
  1794. }
  1795. static void loop_remove(struct loop_device *lo)
  1796. {
  1797. /* Make this loop device unreachable from pathname. */
  1798. del_gendisk(lo->lo_disk);
  1799. blk_mq_free_tag_set(&lo->tag_set);
  1800. mutex_lock(&loop_ctl_mutex);
  1801. idr_remove(&loop_index_idr, lo->lo_number);
  1802. mutex_unlock(&loop_ctl_mutex);
  1803. put_disk(lo->lo_disk);
  1804. }
  1805. #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
  1806. static void loop_probe(dev_t dev)
  1807. {
  1808. int idx = MINOR(dev) >> part_shift;
  1809. if (max_loop_specified && max_loop && idx >= max_loop)
  1810. return;
  1811. loop_add(idx);
  1812. }
  1813. #else
  1814. #define loop_probe NULL
  1815. #endif /* !CONFIG_BLOCK_LEGACY_AUTOLOAD */
  1816. static int loop_control_remove(int idx)
  1817. {
  1818. struct loop_device *lo;
  1819. int ret;
  1820. if (idx < 0) {
  1821. pr_warn_once("deleting an unspecified loop device is not supported.\n");
  1822. return -EINVAL;
  1823. }
  1824. /* Hide this loop device for serialization. */
  1825. ret = mutex_lock_killable(&loop_ctl_mutex);
  1826. if (ret)
  1827. return ret;
  1828. lo = idr_find(&loop_index_idr, idx);
  1829. if (!lo || !lo->idr_visible)
  1830. ret = -ENODEV;
  1831. else
  1832. lo->idr_visible = false;
  1833. mutex_unlock(&loop_ctl_mutex);
  1834. if (ret)
  1835. return ret;
  1836. /* Check whether this loop device can be removed. */
  1837. ret = mutex_lock_killable(&lo->lo_mutex);
  1838. if (ret)
  1839. goto mark_visible;
  1840. if (lo->lo_state != Lo_unbound || disk_openers(lo->lo_disk) > 0) {
  1841. mutex_unlock(&lo->lo_mutex);
  1842. ret = -EBUSY;
  1843. goto mark_visible;
  1844. }
  1845. /* Mark this loop device as no more bound, but not quite unbound yet */
  1846. lo->lo_state = Lo_deleting;
  1847. mutex_unlock(&lo->lo_mutex);
  1848. loop_remove(lo);
  1849. return 0;
  1850. mark_visible:
  1851. /* Show this loop device again. */
  1852. mutex_lock(&loop_ctl_mutex);
  1853. lo->idr_visible = true;
  1854. mutex_unlock(&loop_ctl_mutex);
  1855. return ret;
  1856. }
  1857. static int loop_control_get_free(int idx)
  1858. {
  1859. struct loop_device *lo;
  1860. int id, ret;
  1861. ret = mutex_lock_killable(&loop_ctl_mutex);
  1862. if (ret)
  1863. return ret;
  1864. idr_for_each_entry(&loop_index_idr, lo, id) {
  1865. /* Hitting a race results in creating a new loop device which is harmless. */
  1866. if (lo->idr_visible && data_race(lo->lo_state) == Lo_unbound)
  1867. goto found;
  1868. }
  1869. mutex_unlock(&loop_ctl_mutex);
  1870. return loop_add(-1);
  1871. found:
  1872. mutex_unlock(&loop_ctl_mutex);
  1873. return id;
  1874. }
  1875. static long loop_control_ioctl(struct file *file, unsigned int cmd,
  1876. unsigned long parm)
  1877. {
  1878. switch (cmd) {
  1879. case LOOP_CTL_ADD:
  1880. return loop_add(parm);
  1881. case LOOP_CTL_REMOVE:
  1882. return loop_control_remove(parm);
  1883. case LOOP_CTL_GET_FREE:
  1884. return loop_control_get_free(parm);
  1885. default:
  1886. return -ENOSYS;
  1887. }
  1888. }
  1889. static const struct file_operations loop_ctl_fops = {
  1890. .open = nonseekable_open,
  1891. .unlocked_ioctl = loop_control_ioctl,
  1892. .compat_ioctl = loop_control_ioctl,
  1893. .owner = THIS_MODULE,
  1894. .llseek = noop_llseek,
  1895. };
  1896. static struct miscdevice loop_misc = {
  1897. .minor = LOOP_CTRL_MINOR,
  1898. .name = "loop-control",
  1899. .fops = &loop_ctl_fops,
  1900. };
  1901. MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
  1902. MODULE_ALIAS("devname:loop-control");
  1903. static int __init loop_init(void)
  1904. {
  1905. int i;
  1906. int err;
  1907. part_shift = 0;
  1908. if (max_part > 0) {
  1909. part_shift = fls(max_part);
  1910. /*
  1911. * Adjust max_part according to part_shift as it is exported
  1912. * to user space so that user can decide correct minor number
  1913. * if [s]he want to create more devices.
  1914. *
  1915. * Note that -1 is required because partition 0 is reserved
  1916. * for the whole disk.
  1917. */
  1918. max_part = (1UL << part_shift) - 1;
  1919. }
  1920. if ((1UL << part_shift) > DISK_MAX_PARTS) {
  1921. err = -EINVAL;
  1922. goto err_out;
  1923. }
  1924. if (max_loop > 1UL << (MINORBITS - part_shift)) {
  1925. err = -EINVAL;
  1926. goto err_out;
  1927. }
  1928. err = misc_register(&loop_misc);
  1929. if (err < 0)
  1930. goto err_out;
  1931. if (__register_blkdev(LOOP_MAJOR, "loop", loop_probe)) {
  1932. err = -EIO;
  1933. goto misc_out;
  1934. }
  1935. /* pre-create number of devices given by config or max_loop */
  1936. for (i = 0; i < max_loop; i++)
  1937. loop_add(i);
  1938. printk(KERN_INFO "loop: module loaded\n");
  1939. return 0;
  1940. misc_out:
  1941. misc_deregister(&loop_misc);
  1942. err_out:
  1943. return err;
  1944. }
  1945. static void __exit loop_exit(void)
  1946. {
  1947. struct loop_device *lo;
  1948. int id;
  1949. unregister_blkdev(LOOP_MAJOR, "loop");
  1950. misc_deregister(&loop_misc);
  1951. /*
  1952. * There is no need to use loop_ctl_mutex here, for nobody else can
  1953. * access loop_index_idr when this module is unloading (unless forced
  1954. * module unloading is requested). If this is not a clean unloading,
  1955. * we have no means to avoid kernel crash.
  1956. */
  1957. idr_for_each_entry(&loop_index_idr, lo, id)
  1958. loop_remove(lo);
  1959. idr_destroy(&loop_index_idr);
  1960. }
  1961. module_init(loop_init);
  1962. module_exit(loop_exit);
  1963. #ifndef MODULE
  1964. static int __init max_loop_setup(char *str)
  1965. {
  1966. max_loop = simple_strtol(str, NULL, 0);
  1967. #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
  1968. max_loop_specified = true;
  1969. #endif
  1970. return 1;
  1971. }
  1972. __setup("max_loop=", max_loop_setup);
  1973. #endif