loop.c 58 KB

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