loop.c 57 KB

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