loop.c 57 KB

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