file.c 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041
  1. /*
  2. * file.c - NTFS kernel file operations. Part of the Linux-NTFS project.
  3. *
  4. * Copyright (c) 2001-2015 Anton Altaparmakov and Tuxera Inc.
  5. *
  6. * This program/include file is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License as published
  8. * by the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program/include file is distributed in the hope that it will be
  12. * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
  13. * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program (in the main directory of the Linux-NTFS
  18. * distribution in the file COPYING); if not, write to the Free Software
  19. * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  20. */
  21. #include <linux/backing-dev.h>
  22. #include <linux/buffer_head.h>
  23. #include <linux/gfp.h>
  24. #include <linux/pagemap.h>
  25. #include <linux/pagevec.h>
  26. #include <linux/sched/signal.h>
  27. #include <linux/swap.h>
  28. #include <linux/uio.h>
  29. #include <linux/writeback.h>
  30. #include <asm/page.h>
  31. #include <linux/uaccess.h>
  32. #include "attrib.h"
  33. #include "bitmap.h"
  34. #include "inode.h"
  35. #include "debug.h"
  36. #include "lcnalloc.h"
  37. #include "malloc.h"
  38. #include "mft.h"
  39. #include "ntfs.h"
  40. /**
  41. * ntfs_file_open - called when an inode is about to be opened
  42. * @vi: inode to be opened
  43. * @filp: file structure describing the inode
  44. *
  45. * Limit file size to the page cache limit on architectures where unsigned long
  46. * is 32-bits. This is the most we can do for now without overflowing the page
  47. * cache page index. Doing it this way means we don't run into problems because
  48. * of existing too large files. It would be better to allow the user to read
  49. * the beginning of the file but I doubt very much anyone is going to hit this
  50. * check on a 32-bit architecture, so there is no point in adding the extra
  51. * complexity required to support this.
  52. *
  53. * On 64-bit architectures, the check is hopefully optimized away by the
  54. * compiler.
  55. *
  56. * After the check passes, just call generic_file_open() to do its work.
  57. */
  58. static int ntfs_file_open(struct inode *vi, struct file *filp)
  59. {
  60. if (sizeof(unsigned long) < 8) {
  61. if (i_size_read(vi) > MAX_LFS_FILESIZE)
  62. return -EOVERFLOW;
  63. }
  64. return generic_file_open(vi, filp);
  65. }
  66. #ifdef NTFS_RW
  67. /**
  68. * ntfs_attr_extend_initialized - extend the initialized size of an attribute
  69. * @ni: ntfs inode of the attribute to extend
  70. * @new_init_size: requested new initialized size in bytes
  71. *
  72. * Extend the initialized size of an attribute described by the ntfs inode @ni
  73. * to @new_init_size bytes. This involves zeroing any non-sparse space between
  74. * the old initialized size and @new_init_size both in the page cache and on
  75. * disk (if relevant complete pages are already uptodate in the page cache then
  76. * these are simply marked dirty).
  77. *
  78. * As a side-effect, the file size (vfs inode->i_size) may be incremented as,
  79. * in the resident attribute case, it is tied to the initialized size and, in
  80. * the non-resident attribute case, it may not fall below the initialized size.
  81. *
  82. * Note that if the attribute is resident, we do not need to touch the page
  83. * cache at all. This is because if the page cache page is not uptodate we
  84. * bring it uptodate later, when doing the write to the mft record since we
  85. * then already have the page mapped. And if the page is uptodate, the
  86. * non-initialized region will already have been zeroed when the page was
  87. * brought uptodate and the region may in fact already have been overwritten
  88. * with new data via mmap() based writes, so we cannot just zero it. And since
  89. * POSIX specifies that the behaviour of resizing a file whilst it is mmap()ped
  90. * is unspecified, we choose not to do zeroing and thus we do not need to touch
  91. * the page at all. For a more detailed explanation see ntfs_truncate() in
  92. * fs/ntfs/inode.c.
  93. *
  94. * Return 0 on success and -errno on error. In the case that an error is
  95. * encountered it is possible that the initialized size will already have been
  96. * incremented some way towards @new_init_size but it is guaranteed that if
  97. * this is the case, the necessary zeroing will also have happened and that all
  98. * metadata is self-consistent.
  99. *
  100. * Locking: i_mutex on the vfs inode corrseponsind to the ntfs inode @ni must be
  101. * held by the caller.
  102. */
  103. static int ntfs_attr_extend_initialized(ntfs_inode *ni, const s64 new_init_size)
  104. {
  105. s64 old_init_size;
  106. loff_t old_i_size;
  107. pgoff_t index, end_index;
  108. unsigned long flags;
  109. struct inode *vi = VFS_I(ni);
  110. ntfs_inode *base_ni;
  111. MFT_RECORD *m = NULL;
  112. ATTR_RECORD *a;
  113. ntfs_attr_search_ctx *ctx = NULL;
  114. struct address_space *mapping;
  115. struct page *page = NULL;
  116. u8 *kattr;
  117. int err;
  118. u32 attr_len;
  119. read_lock_irqsave(&ni->size_lock, flags);
  120. old_init_size = ni->initialized_size;
  121. old_i_size = i_size_read(vi);
  122. BUG_ON(new_init_size > ni->allocated_size);
  123. read_unlock_irqrestore(&ni->size_lock, flags);
  124. ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, "
  125. "old_initialized_size 0x%llx, "
  126. "new_initialized_size 0x%llx, i_size 0x%llx.",
  127. vi->i_ino, (unsigned)le32_to_cpu(ni->type),
  128. (unsigned long long)old_init_size,
  129. (unsigned long long)new_init_size, old_i_size);
  130. if (!NInoAttr(ni))
  131. base_ni = ni;
  132. else
  133. base_ni = ni->ext.base_ntfs_ino;
  134. /* Use goto to reduce indentation and we need the label below anyway. */
  135. if (NInoNonResident(ni))
  136. goto do_non_resident_extend;
  137. BUG_ON(old_init_size != old_i_size);
  138. m = map_mft_record(base_ni);
  139. if (IS_ERR(m)) {
  140. err = PTR_ERR(m);
  141. m = NULL;
  142. goto err_out;
  143. }
  144. ctx = ntfs_attr_get_search_ctx(base_ni, m);
  145. if (unlikely(!ctx)) {
  146. err = -ENOMEM;
  147. goto err_out;
  148. }
  149. err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  150. CASE_SENSITIVE, 0, NULL, 0, ctx);
  151. if (unlikely(err)) {
  152. if (err == -ENOENT)
  153. err = -EIO;
  154. goto err_out;
  155. }
  156. m = ctx->mrec;
  157. a = ctx->attr;
  158. BUG_ON(a->non_resident);
  159. /* The total length of the attribute value. */
  160. attr_len = le32_to_cpu(a->data.resident.value_length);
  161. BUG_ON(old_i_size != (loff_t)attr_len);
  162. /*
  163. * Do the zeroing in the mft record and update the attribute size in
  164. * the mft record.
  165. */
  166. kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
  167. memset(kattr + attr_len, 0, new_init_size - attr_len);
  168. a->data.resident.value_length = cpu_to_le32((u32)new_init_size);
  169. /* Finally, update the sizes in the vfs and ntfs inodes. */
  170. write_lock_irqsave(&ni->size_lock, flags);
  171. i_size_write(vi, new_init_size);
  172. ni->initialized_size = new_init_size;
  173. write_unlock_irqrestore(&ni->size_lock, flags);
  174. goto done;
  175. do_non_resident_extend:
  176. /*
  177. * If the new initialized size @new_init_size exceeds the current file
  178. * size (vfs inode->i_size), we need to extend the file size to the
  179. * new initialized size.
  180. */
  181. if (new_init_size > old_i_size) {
  182. m = map_mft_record(base_ni);
  183. if (IS_ERR(m)) {
  184. err = PTR_ERR(m);
  185. m = NULL;
  186. goto err_out;
  187. }
  188. ctx = ntfs_attr_get_search_ctx(base_ni, m);
  189. if (unlikely(!ctx)) {
  190. err = -ENOMEM;
  191. goto err_out;
  192. }
  193. err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  194. CASE_SENSITIVE, 0, NULL, 0, ctx);
  195. if (unlikely(err)) {
  196. if (err == -ENOENT)
  197. err = -EIO;
  198. goto err_out;
  199. }
  200. m = ctx->mrec;
  201. a = ctx->attr;
  202. BUG_ON(!a->non_resident);
  203. BUG_ON(old_i_size != (loff_t)
  204. sle64_to_cpu(a->data.non_resident.data_size));
  205. a->data.non_resident.data_size = cpu_to_sle64(new_init_size);
  206. flush_dcache_mft_record_page(ctx->ntfs_ino);
  207. mark_mft_record_dirty(ctx->ntfs_ino);
  208. /* Update the file size in the vfs inode. */
  209. i_size_write(vi, new_init_size);
  210. ntfs_attr_put_search_ctx(ctx);
  211. ctx = NULL;
  212. unmap_mft_record(base_ni);
  213. m = NULL;
  214. }
  215. mapping = vi->i_mapping;
  216. index = old_init_size >> PAGE_SHIFT;
  217. end_index = (new_init_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
  218. do {
  219. /*
  220. * Read the page. If the page is not present, this will zero
  221. * the uninitialized regions for us.
  222. */
  223. page = read_mapping_page(mapping, index, NULL);
  224. if (IS_ERR(page)) {
  225. err = PTR_ERR(page);
  226. goto init_err_out;
  227. }
  228. if (unlikely(PageError(page))) {
  229. put_page(page);
  230. err = -EIO;
  231. goto init_err_out;
  232. }
  233. /*
  234. * Update the initialized size in the ntfs inode. This is
  235. * enough to make ntfs_writepage() work.
  236. */
  237. write_lock_irqsave(&ni->size_lock, flags);
  238. ni->initialized_size = (s64)(index + 1) << PAGE_SHIFT;
  239. if (ni->initialized_size > new_init_size)
  240. ni->initialized_size = new_init_size;
  241. write_unlock_irqrestore(&ni->size_lock, flags);
  242. /* Set the page dirty so it gets written out. */
  243. set_page_dirty(page);
  244. put_page(page);
  245. /*
  246. * Play nice with the vm and the rest of the system. This is
  247. * very much needed as we can potentially be modifying the
  248. * initialised size from a very small value to a really huge
  249. * value, e.g.
  250. * f = open(somefile, O_TRUNC);
  251. * truncate(f, 10GiB);
  252. * seek(f, 10GiB);
  253. * write(f, 1);
  254. * And this would mean we would be marking dirty hundreds of
  255. * thousands of pages or as in the above example more than
  256. * two and a half million pages!
  257. *
  258. * TODO: For sparse pages could optimize this workload by using
  259. * the FsMisc / MiscFs page bit as a "PageIsSparse" bit. This
  260. * would be set in readpage for sparse pages and here we would
  261. * not need to mark dirty any pages which have this bit set.
  262. * The only caveat is that we have to clear the bit everywhere
  263. * where we allocate any clusters that lie in the page or that
  264. * contain the page.
  265. *
  266. * TODO: An even greater optimization would be for us to only
  267. * call readpage() on pages which are not in sparse regions as
  268. * determined from the runlist. This would greatly reduce the
  269. * number of pages we read and make dirty in the case of sparse
  270. * files.
  271. */
  272. balance_dirty_pages_ratelimited(mapping);
  273. cond_resched();
  274. } while (++index < end_index);
  275. read_lock_irqsave(&ni->size_lock, flags);
  276. BUG_ON(ni->initialized_size != new_init_size);
  277. read_unlock_irqrestore(&ni->size_lock, flags);
  278. /* Now bring in sync the initialized_size in the mft record. */
  279. m = map_mft_record(base_ni);
  280. if (IS_ERR(m)) {
  281. err = PTR_ERR(m);
  282. m = NULL;
  283. goto init_err_out;
  284. }
  285. ctx = ntfs_attr_get_search_ctx(base_ni, m);
  286. if (unlikely(!ctx)) {
  287. err = -ENOMEM;
  288. goto init_err_out;
  289. }
  290. err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  291. CASE_SENSITIVE, 0, NULL, 0, ctx);
  292. if (unlikely(err)) {
  293. if (err == -ENOENT)
  294. err = -EIO;
  295. goto init_err_out;
  296. }
  297. m = ctx->mrec;
  298. a = ctx->attr;
  299. BUG_ON(!a->non_resident);
  300. a->data.non_resident.initialized_size = cpu_to_sle64(new_init_size);
  301. done:
  302. flush_dcache_mft_record_page(ctx->ntfs_ino);
  303. mark_mft_record_dirty(ctx->ntfs_ino);
  304. if (ctx)
  305. ntfs_attr_put_search_ctx(ctx);
  306. if (m)
  307. unmap_mft_record(base_ni);
  308. ntfs_debug("Done, initialized_size 0x%llx, i_size 0x%llx.",
  309. (unsigned long long)new_init_size, i_size_read(vi));
  310. return 0;
  311. init_err_out:
  312. write_lock_irqsave(&ni->size_lock, flags);
  313. ni->initialized_size = old_init_size;
  314. write_unlock_irqrestore(&ni->size_lock, flags);
  315. err_out:
  316. if (ctx)
  317. ntfs_attr_put_search_ctx(ctx);
  318. if (m)
  319. unmap_mft_record(base_ni);
  320. ntfs_debug("Failed. Returning error code %i.", err);
  321. return err;
  322. }
  323. static ssize_t ntfs_prepare_file_for_write(struct kiocb *iocb,
  324. struct iov_iter *from)
  325. {
  326. loff_t pos;
  327. s64 end, ll;
  328. ssize_t err;
  329. unsigned long flags;
  330. struct file *file = iocb->ki_filp;
  331. struct inode *vi = file_inode(file);
  332. ntfs_inode *base_ni, *ni = NTFS_I(vi);
  333. ntfs_volume *vol = ni->vol;
  334. ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, pos "
  335. "0x%llx, count 0x%zx.", vi->i_ino,
  336. (unsigned)le32_to_cpu(ni->type),
  337. (unsigned long long)iocb->ki_pos,
  338. iov_iter_count(from));
  339. err = generic_write_checks(iocb, from);
  340. if (unlikely(err <= 0))
  341. goto out;
  342. /*
  343. * All checks have passed. Before we start doing any writing we want
  344. * to abort any totally illegal writes.
  345. */
  346. BUG_ON(NInoMstProtected(ni));
  347. BUG_ON(ni->type != AT_DATA);
  348. /* If file is encrypted, deny access, just like NT4. */
  349. if (NInoEncrypted(ni)) {
  350. /* Only $DATA attributes can be encrypted. */
  351. /*
  352. * Reminder for later: Encrypted files are _always_
  353. * non-resident so that the content can always be encrypted.
  354. */
  355. ntfs_debug("Denying write access to encrypted file.");
  356. err = -EACCES;
  357. goto out;
  358. }
  359. if (NInoCompressed(ni)) {
  360. /* Only unnamed $DATA attribute can be compressed. */
  361. BUG_ON(ni->name_len);
  362. /*
  363. * Reminder for later: If resident, the data is not actually
  364. * compressed. Only on the switch to non-resident does
  365. * compression kick in. This is in contrast to encrypted files
  366. * (see above).
  367. */
  368. ntfs_error(vi->i_sb, "Writing to compressed files is not "
  369. "implemented yet. Sorry.");
  370. err = -EOPNOTSUPP;
  371. goto out;
  372. }
  373. base_ni = ni;
  374. if (NInoAttr(ni))
  375. base_ni = ni->ext.base_ntfs_ino;
  376. err = file_remove_privs(file);
  377. if (unlikely(err))
  378. goto out;
  379. /*
  380. * Our ->update_time method always succeeds thus file_update_time()
  381. * cannot fail either so there is no need to check the return code.
  382. */
  383. file_update_time(file);
  384. pos = iocb->ki_pos;
  385. /* The first byte after the last cluster being written to. */
  386. end = (pos + iov_iter_count(from) + vol->cluster_size_mask) &
  387. ~(u64)vol->cluster_size_mask;
  388. /*
  389. * If the write goes beyond the allocated size, extend the allocation
  390. * to cover the whole of the write, rounded up to the nearest cluster.
  391. */
  392. read_lock_irqsave(&ni->size_lock, flags);
  393. ll = ni->allocated_size;
  394. read_unlock_irqrestore(&ni->size_lock, flags);
  395. if (end > ll) {
  396. /*
  397. * Extend the allocation without changing the data size.
  398. *
  399. * Note we ensure the allocation is big enough to at least
  400. * write some data but we do not require the allocation to be
  401. * complete, i.e. it may be partial.
  402. */
  403. ll = ntfs_attr_extend_allocation(ni, end, -1, pos);
  404. if (likely(ll >= 0)) {
  405. BUG_ON(pos >= ll);
  406. /* If the extension was partial truncate the write. */
  407. if (end > ll) {
  408. ntfs_debug("Truncating write to inode 0x%lx, "
  409. "attribute type 0x%x, because "
  410. "the allocation was only "
  411. "partially extended.",
  412. vi->i_ino, (unsigned)
  413. le32_to_cpu(ni->type));
  414. iov_iter_truncate(from, ll - pos);
  415. }
  416. } else {
  417. err = ll;
  418. read_lock_irqsave(&ni->size_lock, flags);
  419. ll = ni->allocated_size;
  420. read_unlock_irqrestore(&ni->size_lock, flags);
  421. /* Perform a partial write if possible or fail. */
  422. if (pos < ll) {
  423. ntfs_debug("Truncating write to inode 0x%lx "
  424. "attribute type 0x%x, because "
  425. "extending the allocation "
  426. "failed (error %d).",
  427. vi->i_ino, (unsigned)
  428. le32_to_cpu(ni->type),
  429. (int)-err);
  430. iov_iter_truncate(from, ll - pos);
  431. } else {
  432. if (err != -ENOSPC)
  433. ntfs_error(vi->i_sb, "Cannot perform "
  434. "write to inode "
  435. "0x%lx, attribute "
  436. "type 0x%x, because "
  437. "extending the "
  438. "allocation failed "
  439. "(error %ld).",
  440. vi->i_ino, (unsigned)
  441. le32_to_cpu(ni->type),
  442. (long)-err);
  443. else
  444. ntfs_debug("Cannot perform write to "
  445. "inode 0x%lx, "
  446. "attribute type 0x%x, "
  447. "because there is not "
  448. "space left.",
  449. vi->i_ino, (unsigned)
  450. le32_to_cpu(ni->type));
  451. goto out;
  452. }
  453. }
  454. }
  455. /*
  456. * If the write starts beyond the initialized size, extend it up to the
  457. * beginning of the write and initialize all non-sparse space between
  458. * the old initialized size and the new one. This automatically also
  459. * increments the vfs inode->i_size to keep it above or equal to the
  460. * initialized_size.
  461. */
  462. read_lock_irqsave(&ni->size_lock, flags);
  463. ll = ni->initialized_size;
  464. read_unlock_irqrestore(&ni->size_lock, flags);
  465. if (pos > ll) {
  466. /*
  467. * Wait for ongoing direct i/o to complete before proceeding.
  468. * New direct i/o cannot start as we hold i_mutex.
  469. */
  470. inode_dio_wait(vi);
  471. err = ntfs_attr_extend_initialized(ni, pos);
  472. if (unlikely(err < 0))
  473. ntfs_error(vi->i_sb, "Cannot perform write to inode "
  474. "0x%lx, attribute type 0x%x, because "
  475. "extending the initialized size "
  476. "failed (error %d).", vi->i_ino,
  477. (unsigned)le32_to_cpu(ni->type),
  478. (int)-err);
  479. }
  480. out:
  481. return err;
  482. }
  483. /**
  484. * __ntfs_grab_cache_pages - obtain a number of locked pages
  485. * @mapping: address space mapping from which to obtain page cache pages
  486. * @index: starting index in @mapping at which to begin obtaining pages
  487. * @nr_pages: number of page cache pages to obtain
  488. * @pages: array of pages in which to return the obtained page cache pages
  489. * @cached_page: allocated but as yet unused page
  490. *
  491. * Obtain @nr_pages locked page cache pages from the mapping @mapping and
  492. * starting at index @index.
  493. *
  494. * If a page is newly created, add it to lru list
  495. *
  496. * Note, the page locks are obtained in ascending page index order.
  497. */
  498. static inline int __ntfs_grab_cache_pages(struct address_space *mapping,
  499. pgoff_t index, const unsigned nr_pages, struct page **pages,
  500. struct page **cached_page)
  501. {
  502. int err, nr;
  503. BUG_ON(!nr_pages);
  504. err = nr = 0;
  505. do {
  506. pages[nr] = find_get_page_flags(mapping, index, FGP_LOCK |
  507. FGP_ACCESSED);
  508. if (!pages[nr]) {
  509. if (!*cached_page) {
  510. *cached_page = page_cache_alloc(mapping);
  511. if (unlikely(!*cached_page)) {
  512. err = -ENOMEM;
  513. goto err_out;
  514. }
  515. }
  516. err = add_to_page_cache_lru(*cached_page, mapping,
  517. index,
  518. mapping_gfp_constraint(mapping, GFP_KERNEL));
  519. if (unlikely(err)) {
  520. if (err == -EEXIST)
  521. continue;
  522. goto err_out;
  523. }
  524. pages[nr] = *cached_page;
  525. *cached_page = NULL;
  526. }
  527. index++;
  528. nr++;
  529. } while (nr < nr_pages);
  530. out:
  531. return err;
  532. err_out:
  533. while (nr > 0) {
  534. unlock_page(pages[--nr]);
  535. put_page(pages[nr]);
  536. }
  537. goto out;
  538. }
  539. static inline int ntfs_submit_bh_for_read(struct buffer_head *bh)
  540. {
  541. lock_buffer(bh);
  542. get_bh(bh);
  543. bh->b_end_io = end_buffer_read_sync;
  544. return submit_bh(REQ_OP_READ, 0, bh);
  545. }
  546. /**
  547. * ntfs_prepare_pages_for_non_resident_write - prepare pages for receiving data
  548. * @pages: array of destination pages
  549. * @nr_pages: number of pages in @pages
  550. * @pos: byte position in file at which the write begins
  551. * @bytes: number of bytes to be written
  552. *
  553. * This is called for non-resident attributes from ntfs_file_buffered_write()
  554. * with i_mutex held on the inode (@pages[0]->mapping->host). There are
  555. * @nr_pages pages in @pages which are locked but not kmap()ped. The source
  556. * data has not yet been copied into the @pages.
  557. *
  558. * Need to fill any holes with actual clusters, allocate buffers if necessary,
  559. * ensure all the buffers are mapped, and bring uptodate any buffers that are
  560. * only partially being written to.
  561. *
  562. * If @nr_pages is greater than one, we are guaranteed that the cluster size is
  563. * greater than PAGE_SIZE, that all pages in @pages are entirely inside
  564. * the same cluster and that they are the entirety of that cluster, and that
  565. * the cluster is sparse, i.e. we need to allocate a cluster to fill the hole.
  566. *
  567. * i_size is not to be modified yet.
  568. *
  569. * Return 0 on success or -errno on error.
  570. */
  571. static int ntfs_prepare_pages_for_non_resident_write(struct page **pages,
  572. unsigned nr_pages, s64 pos, size_t bytes)
  573. {
  574. VCN vcn, highest_vcn = 0, cpos, cend, bh_cpos, bh_cend;
  575. LCN lcn;
  576. s64 bh_pos, vcn_len, end, initialized_size;
  577. sector_t lcn_block;
  578. struct page *page;
  579. struct inode *vi;
  580. ntfs_inode *ni, *base_ni = NULL;
  581. ntfs_volume *vol;
  582. runlist_element *rl, *rl2;
  583. struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
  584. ntfs_attr_search_ctx *ctx = NULL;
  585. MFT_RECORD *m = NULL;
  586. ATTR_RECORD *a = NULL;
  587. unsigned long flags;
  588. u32 attr_rec_len = 0;
  589. unsigned blocksize, u;
  590. int err, mp_size;
  591. bool rl_write_locked, was_hole, is_retry;
  592. unsigned char blocksize_bits;
  593. struct {
  594. u8 runlist_merged:1;
  595. u8 mft_attr_mapped:1;
  596. u8 mp_rebuilt:1;
  597. u8 attr_switched:1;
  598. } status = { 0, 0, 0, 0 };
  599. BUG_ON(!nr_pages);
  600. BUG_ON(!pages);
  601. BUG_ON(!*pages);
  602. vi = pages[0]->mapping->host;
  603. ni = NTFS_I(vi);
  604. vol = ni->vol;
  605. ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, start page "
  606. "index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx.",
  607. vi->i_ino, ni->type, pages[0]->index, nr_pages,
  608. (long long)pos, bytes);
  609. blocksize = vol->sb->s_blocksize;
  610. blocksize_bits = vol->sb->s_blocksize_bits;
  611. u = 0;
  612. do {
  613. page = pages[u];
  614. BUG_ON(!page);
  615. /*
  616. * create_empty_buffers() will create uptodate/dirty buffers if
  617. * the page is uptodate/dirty.
  618. */
  619. if (!page_has_buffers(page)) {
  620. create_empty_buffers(page, blocksize, 0);
  621. if (unlikely(!page_has_buffers(page)))
  622. return -ENOMEM;
  623. }
  624. } while (++u < nr_pages);
  625. rl_write_locked = false;
  626. rl = NULL;
  627. err = 0;
  628. vcn = lcn = -1;
  629. vcn_len = 0;
  630. lcn_block = -1;
  631. was_hole = false;
  632. cpos = pos >> vol->cluster_size_bits;
  633. end = pos + bytes;
  634. cend = (end + vol->cluster_size - 1) >> vol->cluster_size_bits;
  635. /*
  636. * Loop over each page and for each page over each buffer. Use goto to
  637. * reduce indentation.
  638. */
  639. u = 0;
  640. do_next_page:
  641. page = pages[u];
  642. bh_pos = (s64)page->index << PAGE_SHIFT;
  643. bh = head = page_buffers(page);
  644. do {
  645. VCN cdelta;
  646. s64 bh_end;
  647. unsigned bh_cofs;
  648. /* Clear buffer_new on all buffers to reinitialise state. */
  649. if (buffer_new(bh))
  650. clear_buffer_new(bh);
  651. bh_end = bh_pos + blocksize;
  652. bh_cpos = bh_pos >> vol->cluster_size_bits;
  653. bh_cofs = bh_pos & vol->cluster_size_mask;
  654. if (buffer_mapped(bh)) {
  655. /*
  656. * The buffer is already mapped. If it is uptodate,
  657. * ignore it.
  658. */
  659. if (buffer_uptodate(bh))
  660. continue;
  661. /*
  662. * The buffer is not uptodate. If the page is uptodate
  663. * set the buffer uptodate and otherwise ignore it.
  664. */
  665. if (PageUptodate(page)) {
  666. set_buffer_uptodate(bh);
  667. continue;
  668. }
  669. /*
  670. * Neither the page nor the buffer are uptodate. If
  671. * the buffer is only partially being written to, we
  672. * need to read it in before the write, i.e. now.
  673. */
  674. if ((bh_pos < pos && bh_end > pos) ||
  675. (bh_pos < end && bh_end > end)) {
  676. /*
  677. * If the buffer is fully or partially within
  678. * the initialized size, do an actual read.
  679. * Otherwise, simply zero the buffer.
  680. */
  681. read_lock_irqsave(&ni->size_lock, flags);
  682. initialized_size = ni->initialized_size;
  683. read_unlock_irqrestore(&ni->size_lock, flags);
  684. if (bh_pos < initialized_size) {
  685. ntfs_submit_bh_for_read(bh);
  686. *wait_bh++ = bh;
  687. } else {
  688. zero_user(page, bh_offset(bh),
  689. blocksize);
  690. set_buffer_uptodate(bh);
  691. }
  692. }
  693. continue;
  694. }
  695. /* Unmapped buffer. Need to map it. */
  696. bh->b_bdev = vol->sb->s_bdev;
  697. /*
  698. * If the current buffer is in the same clusters as the map
  699. * cache, there is no need to check the runlist again. The
  700. * map cache is made up of @vcn, which is the first cached file
  701. * cluster, @vcn_len which is the number of cached file
  702. * clusters, @lcn is the device cluster corresponding to @vcn,
  703. * and @lcn_block is the block number corresponding to @lcn.
  704. */
  705. cdelta = bh_cpos - vcn;
  706. if (likely(!cdelta || (cdelta > 0 && cdelta < vcn_len))) {
  707. map_buffer_cached:
  708. BUG_ON(lcn < 0);
  709. bh->b_blocknr = lcn_block +
  710. (cdelta << (vol->cluster_size_bits -
  711. blocksize_bits)) +
  712. (bh_cofs >> blocksize_bits);
  713. set_buffer_mapped(bh);
  714. /*
  715. * If the page is uptodate so is the buffer. If the
  716. * buffer is fully outside the write, we ignore it if
  717. * it was already allocated and we mark it dirty so it
  718. * gets written out if we allocated it. On the other
  719. * hand, if we allocated the buffer but we are not
  720. * marking it dirty we set buffer_new so we can do
  721. * error recovery.
  722. */
  723. if (PageUptodate(page)) {
  724. if (!buffer_uptodate(bh))
  725. set_buffer_uptodate(bh);
  726. if (unlikely(was_hole)) {
  727. /* We allocated the buffer. */
  728. clean_bdev_bh_alias(bh);
  729. if (bh_end <= pos || bh_pos >= end)
  730. mark_buffer_dirty(bh);
  731. else
  732. set_buffer_new(bh);
  733. }
  734. continue;
  735. }
  736. /* Page is _not_ uptodate. */
  737. if (likely(!was_hole)) {
  738. /*
  739. * Buffer was already allocated. If it is not
  740. * uptodate and is only partially being written
  741. * to, we need to read it in before the write,
  742. * i.e. now.
  743. */
  744. if (!buffer_uptodate(bh) && bh_pos < end &&
  745. bh_end > pos &&
  746. (bh_pos < pos ||
  747. bh_end > end)) {
  748. /*
  749. * If the buffer is fully or partially
  750. * within the initialized size, do an
  751. * actual read. Otherwise, simply zero
  752. * the buffer.
  753. */
  754. read_lock_irqsave(&ni->size_lock,
  755. flags);
  756. initialized_size = ni->initialized_size;
  757. read_unlock_irqrestore(&ni->size_lock,
  758. flags);
  759. if (bh_pos < initialized_size) {
  760. ntfs_submit_bh_for_read(bh);
  761. *wait_bh++ = bh;
  762. } else {
  763. zero_user(page, bh_offset(bh),
  764. blocksize);
  765. set_buffer_uptodate(bh);
  766. }
  767. }
  768. continue;
  769. }
  770. /* We allocated the buffer. */
  771. clean_bdev_bh_alias(bh);
  772. /*
  773. * If the buffer is fully outside the write, zero it,
  774. * set it uptodate, and mark it dirty so it gets
  775. * written out. If it is partially being written to,
  776. * zero region surrounding the write but leave it to
  777. * commit write to do anything else. Finally, if the
  778. * buffer is fully being overwritten, do nothing.
  779. */
  780. if (bh_end <= pos || bh_pos >= end) {
  781. if (!buffer_uptodate(bh)) {
  782. zero_user(page, bh_offset(bh),
  783. blocksize);
  784. set_buffer_uptodate(bh);
  785. }
  786. mark_buffer_dirty(bh);
  787. continue;
  788. }
  789. set_buffer_new(bh);
  790. if (!buffer_uptodate(bh) &&
  791. (bh_pos < pos || bh_end > end)) {
  792. u8 *kaddr;
  793. unsigned pofs;
  794. kaddr = kmap_atomic(page);
  795. if (bh_pos < pos) {
  796. pofs = bh_pos & ~PAGE_MASK;
  797. memset(kaddr + pofs, 0, pos - bh_pos);
  798. }
  799. if (bh_end > end) {
  800. pofs = end & ~PAGE_MASK;
  801. memset(kaddr + pofs, 0, bh_end - end);
  802. }
  803. kunmap_atomic(kaddr);
  804. flush_dcache_page(page);
  805. }
  806. continue;
  807. }
  808. /*
  809. * Slow path: this is the first buffer in the cluster. If it
  810. * is outside allocated size and is not uptodate, zero it and
  811. * set it uptodate.
  812. */
  813. read_lock_irqsave(&ni->size_lock, flags);
  814. initialized_size = ni->allocated_size;
  815. read_unlock_irqrestore(&ni->size_lock, flags);
  816. if (bh_pos > initialized_size) {
  817. if (PageUptodate(page)) {
  818. if (!buffer_uptodate(bh))
  819. set_buffer_uptodate(bh);
  820. } else if (!buffer_uptodate(bh)) {
  821. zero_user(page, bh_offset(bh), blocksize);
  822. set_buffer_uptodate(bh);
  823. }
  824. continue;
  825. }
  826. is_retry = false;
  827. if (!rl) {
  828. down_read(&ni->runlist.lock);
  829. retry_remap:
  830. rl = ni->runlist.rl;
  831. }
  832. if (likely(rl != NULL)) {
  833. /* Seek to element containing target cluster. */
  834. while (rl->length && rl[1].vcn <= bh_cpos)
  835. rl++;
  836. lcn = ntfs_rl_vcn_to_lcn(rl, bh_cpos);
  837. if (likely(lcn >= 0)) {
  838. /*
  839. * Successful remap, setup the map cache and
  840. * use that to deal with the buffer.
  841. */
  842. was_hole = false;
  843. vcn = bh_cpos;
  844. vcn_len = rl[1].vcn - vcn;
  845. lcn_block = lcn << (vol->cluster_size_bits -
  846. blocksize_bits);
  847. cdelta = 0;
  848. /*
  849. * If the number of remaining clusters touched
  850. * by the write is smaller or equal to the
  851. * number of cached clusters, unlock the
  852. * runlist as the map cache will be used from
  853. * now on.
  854. */
  855. if (likely(vcn + vcn_len >= cend)) {
  856. if (rl_write_locked) {
  857. up_write(&ni->runlist.lock);
  858. rl_write_locked = false;
  859. } else
  860. up_read(&ni->runlist.lock);
  861. rl = NULL;
  862. }
  863. goto map_buffer_cached;
  864. }
  865. } else
  866. lcn = LCN_RL_NOT_MAPPED;
  867. /*
  868. * If it is not a hole and not out of bounds, the runlist is
  869. * probably unmapped so try to map it now.
  870. */
  871. if (unlikely(lcn != LCN_HOLE && lcn != LCN_ENOENT)) {
  872. if (likely(!is_retry && lcn == LCN_RL_NOT_MAPPED)) {
  873. /* Attempt to map runlist. */
  874. if (!rl_write_locked) {
  875. /*
  876. * We need the runlist locked for
  877. * writing, so if it is locked for
  878. * reading relock it now and retry in
  879. * case it changed whilst we dropped
  880. * the lock.
  881. */
  882. up_read(&ni->runlist.lock);
  883. down_write(&ni->runlist.lock);
  884. rl_write_locked = true;
  885. goto retry_remap;
  886. }
  887. err = ntfs_map_runlist_nolock(ni, bh_cpos,
  888. NULL);
  889. if (likely(!err)) {
  890. is_retry = true;
  891. goto retry_remap;
  892. }
  893. /*
  894. * If @vcn is out of bounds, pretend @lcn is
  895. * LCN_ENOENT. As long as the buffer is out
  896. * of bounds this will work fine.
  897. */
  898. if (err == -ENOENT) {
  899. lcn = LCN_ENOENT;
  900. err = 0;
  901. goto rl_not_mapped_enoent;
  902. }
  903. } else
  904. err = -EIO;
  905. /* Failed to map the buffer, even after retrying. */
  906. bh->b_blocknr = -1;
  907. ntfs_error(vol->sb, "Failed to write to inode 0x%lx, "
  908. "attribute type 0x%x, vcn 0x%llx, "
  909. "vcn offset 0x%x, because its "
  910. "location on disk could not be "
  911. "determined%s (error code %i).",
  912. ni->mft_no, ni->type,
  913. (unsigned long long)bh_cpos,
  914. (unsigned)bh_pos &
  915. vol->cluster_size_mask,
  916. is_retry ? " even after retrying" : "",
  917. err);
  918. break;
  919. }
  920. rl_not_mapped_enoent:
  921. /*
  922. * The buffer is in a hole or out of bounds. We need to fill
  923. * the hole, unless the buffer is in a cluster which is not
  924. * touched by the write, in which case we just leave the buffer
  925. * unmapped. This can only happen when the cluster size is
  926. * less than the page cache size.
  927. */
  928. if (unlikely(vol->cluster_size < PAGE_SIZE)) {
  929. bh_cend = (bh_end + vol->cluster_size - 1) >>
  930. vol->cluster_size_bits;
  931. if ((bh_cend <= cpos || bh_cpos >= cend)) {
  932. bh->b_blocknr = -1;
  933. /*
  934. * If the buffer is uptodate we skip it. If it
  935. * is not but the page is uptodate, we can set
  936. * the buffer uptodate. If the page is not
  937. * uptodate, we can clear the buffer and set it
  938. * uptodate. Whether this is worthwhile is
  939. * debatable and this could be removed.
  940. */
  941. if (PageUptodate(page)) {
  942. if (!buffer_uptodate(bh))
  943. set_buffer_uptodate(bh);
  944. } else if (!buffer_uptodate(bh)) {
  945. zero_user(page, bh_offset(bh),
  946. blocksize);
  947. set_buffer_uptodate(bh);
  948. }
  949. continue;
  950. }
  951. }
  952. /*
  953. * Out of bounds buffer is invalid if it was not really out of
  954. * bounds.
  955. */
  956. BUG_ON(lcn != LCN_HOLE);
  957. /*
  958. * We need the runlist locked for writing, so if it is locked
  959. * for reading relock it now and retry in case it changed
  960. * whilst we dropped the lock.
  961. */
  962. BUG_ON(!rl);
  963. if (!rl_write_locked) {
  964. up_read(&ni->runlist.lock);
  965. down_write(&ni->runlist.lock);
  966. rl_write_locked = true;
  967. goto retry_remap;
  968. }
  969. /* Find the previous last allocated cluster. */
  970. BUG_ON(rl->lcn != LCN_HOLE);
  971. lcn = -1;
  972. rl2 = rl;
  973. while (--rl2 >= ni->runlist.rl) {
  974. if (rl2->lcn >= 0) {
  975. lcn = rl2->lcn + rl2->length;
  976. break;
  977. }
  978. }
  979. rl2 = ntfs_cluster_alloc(vol, bh_cpos, 1, lcn, DATA_ZONE,
  980. false);
  981. if (IS_ERR(rl2)) {
  982. err = PTR_ERR(rl2);
  983. ntfs_debug("Failed to allocate cluster, error code %i.",
  984. err);
  985. break;
  986. }
  987. lcn = rl2->lcn;
  988. rl = ntfs_runlists_merge(ni->runlist.rl, rl2);
  989. if (IS_ERR(rl)) {
  990. err = PTR_ERR(rl);
  991. if (err != -ENOMEM)
  992. err = -EIO;
  993. if (ntfs_cluster_free_from_rl(vol, rl2)) {
  994. ntfs_error(vol->sb, "Failed to release "
  995. "allocated cluster in error "
  996. "code path. Run chkdsk to "
  997. "recover the lost cluster.");
  998. NVolSetErrors(vol);
  999. }
  1000. ntfs_free(rl2);
  1001. break;
  1002. }
  1003. ni->runlist.rl = rl;
  1004. status.runlist_merged = 1;
  1005. ntfs_debug("Allocated cluster, lcn 0x%llx.",
  1006. (unsigned long long)lcn);
  1007. /* Map and lock the mft record and get the attribute record. */
  1008. if (!NInoAttr(ni))
  1009. base_ni = ni;
  1010. else
  1011. base_ni = ni->ext.base_ntfs_ino;
  1012. m = map_mft_record(base_ni);
  1013. if (IS_ERR(m)) {
  1014. err = PTR_ERR(m);
  1015. break;
  1016. }
  1017. ctx = ntfs_attr_get_search_ctx(base_ni, m);
  1018. if (unlikely(!ctx)) {
  1019. err = -ENOMEM;
  1020. unmap_mft_record(base_ni);
  1021. break;
  1022. }
  1023. status.mft_attr_mapped = 1;
  1024. err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  1025. CASE_SENSITIVE, bh_cpos, NULL, 0, ctx);
  1026. if (unlikely(err)) {
  1027. if (err == -ENOENT)
  1028. err = -EIO;
  1029. break;
  1030. }
  1031. m = ctx->mrec;
  1032. a = ctx->attr;
  1033. /*
  1034. * Find the runlist element with which the attribute extent
  1035. * starts. Note, we cannot use the _attr_ version because we
  1036. * have mapped the mft record. That is ok because we know the
  1037. * runlist fragment must be mapped already to have ever gotten
  1038. * here, so we can just use the _rl_ version.
  1039. */
  1040. vcn = sle64_to_cpu(a->data.non_resident.lowest_vcn);
  1041. rl2 = ntfs_rl_find_vcn_nolock(rl, vcn);
  1042. BUG_ON(!rl2);
  1043. BUG_ON(!rl2->length);
  1044. BUG_ON(rl2->lcn < LCN_HOLE);
  1045. highest_vcn = sle64_to_cpu(a->data.non_resident.highest_vcn);
  1046. /*
  1047. * If @highest_vcn is zero, calculate the real highest_vcn
  1048. * (which can really be zero).
  1049. */
  1050. if (!highest_vcn)
  1051. highest_vcn = (sle64_to_cpu(
  1052. a->data.non_resident.allocated_size) >>
  1053. vol->cluster_size_bits) - 1;
  1054. /*
  1055. * Determine the size of the mapping pairs array for the new
  1056. * extent, i.e. the old extent with the hole filled.
  1057. */
  1058. mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, vcn,
  1059. highest_vcn);
  1060. if (unlikely(mp_size <= 0)) {
  1061. if (!(err = mp_size))
  1062. err = -EIO;
  1063. ntfs_debug("Failed to get size for mapping pairs "
  1064. "array, error code %i.", err);
  1065. break;
  1066. }
  1067. /*
  1068. * Resize the attribute record to fit the new mapping pairs
  1069. * array.
  1070. */
  1071. attr_rec_len = le32_to_cpu(a->length);
  1072. err = ntfs_attr_record_resize(m, a, mp_size + le16_to_cpu(
  1073. a->data.non_resident.mapping_pairs_offset));
  1074. if (unlikely(err)) {
  1075. BUG_ON(err != -ENOSPC);
  1076. // TODO: Deal with this by using the current attribute
  1077. // and fill it with as much of the mapping pairs
  1078. // array as possible. Then loop over each attribute
  1079. // extent rewriting the mapping pairs arrays as we go
  1080. // along and if when we reach the end we have not
  1081. // enough space, try to resize the last attribute
  1082. // extent and if even that fails, add a new attribute
  1083. // extent.
  1084. // We could also try to resize at each step in the hope
  1085. // that we will not need to rewrite every single extent.
  1086. // Note, we may need to decompress some extents to fill
  1087. // the runlist as we are walking the extents...
  1088. ntfs_error(vol->sb, "Not enough space in the mft "
  1089. "record for the extended attribute "
  1090. "record. This case is not "
  1091. "implemented yet.");
  1092. err = -EOPNOTSUPP;
  1093. break ;
  1094. }
  1095. status.mp_rebuilt = 1;
  1096. /*
  1097. * Generate the mapping pairs array directly into the attribute
  1098. * record.
  1099. */
  1100. err = ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
  1101. a->data.non_resident.mapping_pairs_offset),
  1102. mp_size, rl2, vcn, highest_vcn, NULL);
  1103. if (unlikely(err)) {
  1104. ntfs_error(vol->sb, "Cannot fill hole in inode 0x%lx, "
  1105. "attribute type 0x%x, because building "
  1106. "the mapping pairs failed with error "
  1107. "code %i.", vi->i_ino,
  1108. (unsigned)le32_to_cpu(ni->type), err);
  1109. err = -EIO;
  1110. break;
  1111. }
  1112. /* Update the highest_vcn but only if it was not set. */
  1113. if (unlikely(!a->data.non_resident.highest_vcn))
  1114. a->data.non_resident.highest_vcn =
  1115. cpu_to_sle64(highest_vcn);
  1116. /*
  1117. * If the attribute is sparse/compressed, update the compressed
  1118. * size in the ntfs_inode structure and the attribute record.
  1119. */
  1120. if (likely(NInoSparse(ni) || NInoCompressed(ni))) {
  1121. /*
  1122. * If we are not in the first attribute extent, switch
  1123. * to it, but first ensure the changes will make it to
  1124. * disk later.
  1125. */
  1126. if (a->data.non_resident.lowest_vcn) {
  1127. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1128. mark_mft_record_dirty(ctx->ntfs_ino);
  1129. ntfs_attr_reinit_search_ctx(ctx);
  1130. err = ntfs_attr_lookup(ni->type, ni->name,
  1131. ni->name_len, CASE_SENSITIVE,
  1132. 0, NULL, 0, ctx);
  1133. if (unlikely(err)) {
  1134. status.attr_switched = 1;
  1135. break;
  1136. }
  1137. /* @m is not used any more so do not set it. */
  1138. a = ctx->attr;
  1139. }
  1140. write_lock_irqsave(&ni->size_lock, flags);
  1141. ni->itype.compressed.size += vol->cluster_size;
  1142. a->data.non_resident.compressed_size =
  1143. cpu_to_sle64(ni->itype.compressed.size);
  1144. write_unlock_irqrestore(&ni->size_lock, flags);
  1145. }
  1146. /* Ensure the changes make it to disk. */
  1147. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1148. mark_mft_record_dirty(ctx->ntfs_ino);
  1149. ntfs_attr_put_search_ctx(ctx);
  1150. unmap_mft_record(base_ni);
  1151. /* Successfully filled the hole. */
  1152. status.runlist_merged = 0;
  1153. status.mft_attr_mapped = 0;
  1154. status.mp_rebuilt = 0;
  1155. /* Setup the map cache and use that to deal with the buffer. */
  1156. was_hole = true;
  1157. vcn = bh_cpos;
  1158. vcn_len = 1;
  1159. lcn_block = lcn << (vol->cluster_size_bits - blocksize_bits);
  1160. cdelta = 0;
  1161. /*
  1162. * If the number of remaining clusters in the @pages is smaller
  1163. * or equal to the number of cached clusters, unlock the
  1164. * runlist as the map cache will be used from now on.
  1165. */
  1166. if (likely(vcn + vcn_len >= cend)) {
  1167. up_write(&ni->runlist.lock);
  1168. rl_write_locked = false;
  1169. rl = NULL;
  1170. }
  1171. goto map_buffer_cached;
  1172. } while (bh_pos += blocksize, (bh = bh->b_this_page) != head);
  1173. /* If there are no errors, do the next page. */
  1174. if (likely(!err && ++u < nr_pages))
  1175. goto do_next_page;
  1176. /* If there are no errors, release the runlist lock if we took it. */
  1177. if (likely(!err)) {
  1178. if (unlikely(rl_write_locked)) {
  1179. up_write(&ni->runlist.lock);
  1180. rl_write_locked = false;
  1181. } else if (unlikely(rl))
  1182. up_read(&ni->runlist.lock);
  1183. rl = NULL;
  1184. }
  1185. /* If we issued read requests, let them complete. */
  1186. read_lock_irqsave(&ni->size_lock, flags);
  1187. initialized_size = ni->initialized_size;
  1188. read_unlock_irqrestore(&ni->size_lock, flags);
  1189. while (wait_bh > wait) {
  1190. bh = *--wait_bh;
  1191. wait_on_buffer(bh);
  1192. if (likely(buffer_uptodate(bh))) {
  1193. page = bh->b_page;
  1194. bh_pos = ((s64)page->index << PAGE_SHIFT) +
  1195. bh_offset(bh);
  1196. /*
  1197. * If the buffer overflows the initialized size, need
  1198. * to zero the overflowing region.
  1199. */
  1200. if (unlikely(bh_pos + blocksize > initialized_size)) {
  1201. int ofs = 0;
  1202. if (likely(bh_pos < initialized_size))
  1203. ofs = initialized_size - bh_pos;
  1204. zero_user_segment(page, bh_offset(bh) + ofs,
  1205. blocksize);
  1206. }
  1207. } else /* if (unlikely(!buffer_uptodate(bh))) */
  1208. err = -EIO;
  1209. }
  1210. if (likely(!err)) {
  1211. /* Clear buffer_new on all buffers. */
  1212. u = 0;
  1213. do {
  1214. bh = head = page_buffers(pages[u]);
  1215. do {
  1216. if (buffer_new(bh))
  1217. clear_buffer_new(bh);
  1218. } while ((bh = bh->b_this_page) != head);
  1219. } while (++u < nr_pages);
  1220. ntfs_debug("Done.");
  1221. return err;
  1222. }
  1223. if (status.attr_switched) {
  1224. /* Get back to the attribute extent we modified. */
  1225. ntfs_attr_reinit_search_ctx(ctx);
  1226. if (ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  1227. CASE_SENSITIVE, bh_cpos, NULL, 0, ctx)) {
  1228. ntfs_error(vol->sb, "Failed to find required "
  1229. "attribute extent of attribute in "
  1230. "error code path. Run chkdsk to "
  1231. "recover.");
  1232. write_lock_irqsave(&ni->size_lock, flags);
  1233. ni->itype.compressed.size += vol->cluster_size;
  1234. write_unlock_irqrestore(&ni->size_lock, flags);
  1235. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1236. mark_mft_record_dirty(ctx->ntfs_ino);
  1237. /*
  1238. * The only thing that is now wrong is the compressed
  1239. * size of the base attribute extent which chkdsk
  1240. * should be able to fix.
  1241. */
  1242. NVolSetErrors(vol);
  1243. } else {
  1244. m = ctx->mrec;
  1245. a = ctx->attr;
  1246. status.attr_switched = 0;
  1247. }
  1248. }
  1249. /*
  1250. * If the runlist has been modified, need to restore it by punching a
  1251. * hole into it and we then need to deallocate the on-disk cluster as
  1252. * well. Note, we only modify the runlist if we are able to generate a
  1253. * new mapping pairs array, i.e. only when the mapped attribute extent
  1254. * is not switched.
  1255. */
  1256. if (status.runlist_merged && !status.attr_switched) {
  1257. BUG_ON(!rl_write_locked);
  1258. /* Make the file cluster we allocated sparse in the runlist. */
  1259. if (ntfs_rl_punch_nolock(vol, &ni->runlist, bh_cpos, 1)) {
  1260. ntfs_error(vol->sb, "Failed to punch hole into "
  1261. "attribute runlist in error code "
  1262. "path. Run chkdsk to recover the "
  1263. "lost cluster.");
  1264. NVolSetErrors(vol);
  1265. } else /* if (success) */ {
  1266. status.runlist_merged = 0;
  1267. /*
  1268. * Deallocate the on-disk cluster we allocated but only
  1269. * if we succeeded in punching its vcn out of the
  1270. * runlist.
  1271. */
  1272. down_write(&vol->lcnbmp_lock);
  1273. if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
  1274. ntfs_error(vol->sb, "Failed to release "
  1275. "allocated cluster in error "
  1276. "code path. Run chkdsk to "
  1277. "recover the lost cluster.");
  1278. NVolSetErrors(vol);
  1279. }
  1280. up_write(&vol->lcnbmp_lock);
  1281. }
  1282. }
  1283. /*
  1284. * Resize the attribute record to its old size and rebuild the mapping
  1285. * pairs array. Note, we only can do this if the runlist has been
  1286. * restored to its old state which also implies that the mapped
  1287. * attribute extent is not switched.
  1288. */
  1289. if (status.mp_rebuilt && !status.runlist_merged) {
  1290. if (ntfs_attr_record_resize(m, a, attr_rec_len)) {
  1291. ntfs_error(vol->sb, "Failed to restore attribute "
  1292. "record in error code path. Run "
  1293. "chkdsk to recover.");
  1294. NVolSetErrors(vol);
  1295. } else /* if (success) */ {
  1296. if (ntfs_mapping_pairs_build(vol, (u8*)a +
  1297. le16_to_cpu(a->data.non_resident.
  1298. mapping_pairs_offset), attr_rec_len -
  1299. le16_to_cpu(a->data.non_resident.
  1300. mapping_pairs_offset), ni->runlist.rl,
  1301. vcn, highest_vcn, NULL)) {
  1302. ntfs_error(vol->sb, "Failed to restore "
  1303. "mapping pairs array in error "
  1304. "code path. Run chkdsk to "
  1305. "recover.");
  1306. NVolSetErrors(vol);
  1307. }
  1308. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1309. mark_mft_record_dirty(ctx->ntfs_ino);
  1310. }
  1311. }
  1312. /* Release the mft record and the attribute. */
  1313. if (status.mft_attr_mapped) {
  1314. ntfs_attr_put_search_ctx(ctx);
  1315. unmap_mft_record(base_ni);
  1316. }
  1317. /* Release the runlist lock. */
  1318. if (rl_write_locked)
  1319. up_write(&ni->runlist.lock);
  1320. else if (rl)
  1321. up_read(&ni->runlist.lock);
  1322. /*
  1323. * Zero out any newly allocated blocks to avoid exposing stale data.
  1324. * If BH_New is set, we know that the block was newly allocated above
  1325. * and that it has not been fully zeroed and marked dirty yet.
  1326. */
  1327. nr_pages = u;
  1328. u = 0;
  1329. end = bh_cpos << vol->cluster_size_bits;
  1330. do {
  1331. page = pages[u];
  1332. bh = head = page_buffers(page);
  1333. do {
  1334. if (u == nr_pages &&
  1335. ((s64)page->index << PAGE_SHIFT) +
  1336. bh_offset(bh) >= end)
  1337. break;
  1338. if (!buffer_new(bh))
  1339. continue;
  1340. clear_buffer_new(bh);
  1341. if (!buffer_uptodate(bh)) {
  1342. if (PageUptodate(page))
  1343. set_buffer_uptodate(bh);
  1344. else {
  1345. zero_user(page, bh_offset(bh),
  1346. blocksize);
  1347. set_buffer_uptodate(bh);
  1348. }
  1349. }
  1350. mark_buffer_dirty(bh);
  1351. } while ((bh = bh->b_this_page) != head);
  1352. } while (++u <= nr_pages);
  1353. ntfs_error(vol->sb, "Failed. Returning error code %i.", err);
  1354. return err;
  1355. }
  1356. static inline void ntfs_flush_dcache_pages(struct page **pages,
  1357. unsigned nr_pages)
  1358. {
  1359. BUG_ON(!nr_pages);
  1360. /*
  1361. * Warning: Do not do the decrement at the same time as the call to
  1362. * flush_dcache_page() because it is a NULL macro on i386 and hence the
  1363. * decrement never happens so the loop never terminates.
  1364. */
  1365. do {
  1366. --nr_pages;
  1367. flush_dcache_page(pages[nr_pages]);
  1368. } while (nr_pages > 0);
  1369. }
  1370. /**
  1371. * ntfs_commit_pages_after_non_resident_write - commit the received data
  1372. * @pages: array of destination pages
  1373. * @nr_pages: number of pages in @pages
  1374. * @pos: byte position in file at which the write begins
  1375. * @bytes: number of bytes to be written
  1376. *
  1377. * See description of ntfs_commit_pages_after_write(), below.
  1378. */
  1379. static inline int ntfs_commit_pages_after_non_resident_write(
  1380. struct page **pages, const unsigned nr_pages,
  1381. s64 pos, size_t bytes)
  1382. {
  1383. s64 end, initialized_size;
  1384. struct inode *vi;
  1385. ntfs_inode *ni, *base_ni;
  1386. struct buffer_head *bh, *head;
  1387. ntfs_attr_search_ctx *ctx;
  1388. MFT_RECORD *m;
  1389. ATTR_RECORD *a;
  1390. unsigned long flags;
  1391. unsigned blocksize, u;
  1392. int err;
  1393. vi = pages[0]->mapping->host;
  1394. ni = NTFS_I(vi);
  1395. blocksize = vi->i_sb->s_blocksize;
  1396. end = pos + bytes;
  1397. u = 0;
  1398. do {
  1399. s64 bh_pos;
  1400. struct page *page;
  1401. bool partial;
  1402. page = pages[u];
  1403. bh_pos = (s64)page->index << PAGE_SHIFT;
  1404. bh = head = page_buffers(page);
  1405. partial = false;
  1406. do {
  1407. s64 bh_end;
  1408. bh_end = bh_pos + blocksize;
  1409. if (bh_end <= pos || bh_pos >= end) {
  1410. if (!buffer_uptodate(bh))
  1411. partial = true;
  1412. } else {
  1413. set_buffer_uptodate(bh);
  1414. mark_buffer_dirty(bh);
  1415. }
  1416. } while (bh_pos += blocksize, (bh = bh->b_this_page) != head);
  1417. /*
  1418. * If all buffers are now uptodate but the page is not, set the
  1419. * page uptodate.
  1420. */
  1421. if (!partial && !PageUptodate(page))
  1422. SetPageUptodate(page);
  1423. } while (++u < nr_pages);
  1424. /*
  1425. * Finally, if we do not need to update initialized_size or i_size we
  1426. * are finished.
  1427. */
  1428. read_lock_irqsave(&ni->size_lock, flags);
  1429. initialized_size = ni->initialized_size;
  1430. read_unlock_irqrestore(&ni->size_lock, flags);
  1431. if (end <= initialized_size) {
  1432. ntfs_debug("Done.");
  1433. return 0;
  1434. }
  1435. /*
  1436. * Update initialized_size/i_size as appropriate, both in the inode and
  1437. * the mft record.
  1438. */
  1439. if (!NInoAttr(ni))
  1440. base_ni = ni;
  1441. else
  1442. base_ni = ni->ext.base_ntfs_ino;
  1443. /* Map, pin, and lock the mft record. */
  1444. m = map_mft_record(base_ni);
  1445. if (IS_ERR(m)) {
  1446. err = PTR_ERR(m);
  1447. m = NULL;
  1448. ctx = NULL;
  1449. goto err_out;
  1450. }
  1451. BUG_ON(!NInoNonResident(ni));
  1452. ctx = ntfs_attr_get_search_ctx(base_ni, m);
  1453. if (unlikely(!ctx)) {
  1454. err = -ENOMEM;
  1455. goto err_out;
  1456. }
  1457. err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  1458. CASE_SENSITIVE, 0, NULL, 0, ctx);
  1459. if (unlikely(err)) {
  1460. if (err == -ENOENT)
  1461. err = -EIO;
  1462. goto err_out;
  1463. }
  1464. a = ctx->attr;
  1465. BUG_ON(!a->non_resident);
  1466. write_lock_irqsave(&ni->size_lock, flags);
  1467. BUG_ON(end > ni->allocated_size);
  1468. ni->initialized_size = end;
  1469. a->data.non_resident.initialized_size = cpu_to_sle64(end);
  1470. if (end > i_size_read(vi)) {
  1471. i_size_write(vi, end);
  1472. a->data.non_resident.data_size =
  1473. a->data.non_resident.initialized_size;
  1474. }
  1475. write_unlock_irqrestore(&ni->size_lock, flags);
  1476. /* Mark the mft record dirty, so it gets written back. */
  1477. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1478. mark_mft_record_dirty(ctx->ntfs_ino);
  1479. ntfs_attr_put_search_ctx(ctx);
  1480. unmap_mft_record(base_ni);
  1481. ntfs_debug("Done.");
  1482. return 0;
  1483. err_out:
  1484. if (ctx)
  1485. ntfs_attr_put_search_ctx(ctx);
  1486. if (m)
  1487. unmap_mft_record(base_ni);
  1488. ntfs_error(vi->i_sb, "Failed to update initialized_size/i_size (error "
  1489. "code %i).", err);
  1490. if (err != -ENOMEM)
  1491. NVolSetErrors(ni->vol);
  1492. return err;
  1493. }
  1494. /**
  1495. * ntfs_commit_pages_after_write - commit the received data
  1496. * @pages: array of destination pages
  1497. * @nr_pages: number of pages in @pages
  1498. * @pos: byte position in file at which the write begins
  1499. * @bytes: number of bytes to be written
  1500. *
  1501. * This is called from ntfs_file_buffered_write() with i_mutex held on the inode
  1502. * (@pages[0]->mapping->host). There are @nr_pages pages in @pages which are
  1503. * locked but not kmap()ped. The source data has already been copied into the
  1504. * @page. ntfs_prepare_pages_for_non_resident_write() has been called before
  1505. * the data was copied (for non-resident attributes only) and it returned
  1506. * success.
  1507. *
  1508. * Need to set uptodate and mark dirty all buffers within the boundary of the
  1509. * write. If all buffers in a page are uptodate we set the page uptodate, too.
  1510. *
  1511. * Setting the buffers dirty ensures that they get written out later when
  1512. * ntfs_writepage() is invoked by the VM.
  1513. *
  1514. * Finally, we need to update i_size and initialized_size as appropriate both
  1515. * in the inode and the mft record.
  1516. *
  1517. * This is modelled after fs/buffer.c::generic_commit_write(), which marks
  1518. * buffers uptodate and dirty, sets the page uptodate if all buffers in the
  1519. * page are uptodate, and updates i_size if the end of io is beyond i_size. In
  1520. * that case, it also marks the inode dirty.
  1521. *
  1522. * If things have gone as outlined in
  1523. * ntfs_prepare_pages_for_non_resident_write(), we do not need to do any page
  1524. * content modifications here for non-resident attributes. For resident
  1525. * attributes we need to do the uptodate bringing here which we combine with
  1526. * the copying into the mft record which means we save one atomic kmap.
  1527. *
  1528. * Return 0 on success or -errno on error.
  1529. */
  1530. static int ntfs_commit_pages_after_write(struct page **pages,
  1531. const unsigned nr_pages, s64 pos, size_t bytes)
  1532. {
  1533. s64 end, initialized_size;
  1534. loff_t i_size;
  1535. struct inode *vi;
  1536. ntfs_inode *ni, *base_ni;
  1537. struct page *page;
  1538. ntfs_attr_search_ctx *ctx;
  1539. MFT_RECORD *m;
  1540. ATTR_RECORD *a;
  1541. char *kattr, *kaddr;
  1542. unsigned long flags;
  1543. u32 attr_len;
  1544. int err;
  1545. BUG_ON(!nr_pages);
  1546. BUG_ON(!pages);
  1547. page = pages[0];
  1548. BUG_ON(!page);
  1549. vi = page->mapping->host;
  1550. ni = NTFS_I(vi);
  1551. ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, start page "
  1552. "index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx.",
  1553. vi->i_ino, ni->type, page->index, nr_pages,
  1554. (long long)pos, bytes);
  1555. if (NInoNonResident(ni))
  1556. return ntfs_commit_pages_after_non_resident_write(pages,
  1557. nr_pages, pos, bytes);
  1558. BUG_ON(nr_pages > 1);
  1559. /*
  1560. * Attribute is resident, implying it is not compressed, encrypted, or
  1561. * sparse.
  1562. */
  1563. if (!NInoAttr(ni))
  1564. base_ni = ni;
  1565. else
  1566. base_ni = ni->ext.base_ntfs_ino;
  1567. BUG_ON(NInoNonResident(ni));
  1568. /* Map, pin, and lock the mft record. */
  1569. m = map_mft_record(base_ni);
  1570. if (IS_ERR(m)) {
  1571. err = PTR_ERR(m);
  1572. m = NULL;
  1573. ctx = NULL;
  1574. goto err_out;
  1575. }
  1576. ctx = ntfs_attr_get_search_ctx(base_ni, m);
  1577. if (unlikely(!ctx)) {
  1578. err = -ENOMEM;
  1579. goto err_out;
  1580. }
  1581. err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  1582. CASE_SENSITIVE, 0, NULL, 0, ctx);
  1583. if (unlikely(err)) {
  1584. if (err == -ENOENT)
  1585. err = -EIO;
  1586. goto err_out;
  1587. }
  1588. a = ctx->attr;
  1589. BUG_ON(a->non_resident);
  1590. /* The total length of the attribute value. */
  1591. attr_len = le32_to_cpu(a->data.resident.value_length);
  1592. i_size = i_size_read(vi);
  1593. BUG_ON(attr_len != i_size);
  1594. BUG_ON(pos > attr_len);
  1595. end = pos + bytes;
  1596. BUG_ON(end > le32_to_cpu(a->length) -
  1597. le16_to_cpu(a->data.resident.value_offset));
  1598. kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
  1599. kaddr = kmap_atomic(page);
  1600. /* Copy the received data from the page to the mft record. */
  1601. memcpy(kattr + pos, kaddr + pos, bytes);
  1602. /* Update the attribute length if necessary. */
  1603. if (end > attr_len) {
  1604. attr_len = end;
  1605. a->data.resident.value_length = cpu_to_le32(attr_len);
  1606. }
  1607. /*
  1608. * If the page is not uptodate, bring the out of bounds area(s)
  1609. * uptodate by copying data from the mft record to the page.
  1610. */
  1611. if (!PageUptodate(page)) {
  1612. if (pos > 0)
  1613. memcpy(kaddr, kattr, pos);
  1614. if (end < attr_len)
  1615. memcpy(kaddr + end, kattr + end, attr_len - end);
  1616. /* Zero the region outside the end of the attribute value. */
  1617. memset(kaddr + attr_len, 0, PAGE_SIZE - attr_len);
  1618. flush_dcache_page(page);
  1619. SetPageUptodate(page);
  1620. }
  1621. kunmap_atomic(kaddr);
  1622. /* Update initialized_size/i_size if necessary. */
  1623. read_lock_irqsave(&ni->size_lock, flags);
  1624. initialized_size = ni->initialized_size;
  1625. BUG_ON(end > ni->allocated_size);
  1626. read_unlock_irqrestore(&ni->size_lock, flags);
  1627. BUG_ON(initialized_size != i_size);
  1628. if (end > initialized_size) {
  1629. write_lock_irqsave(&ni->size_lock, flags);
  1630. ni->initialized_size = end;
  1631. i_size_write(vi, end);
  1632. write_unlock_irqrestore(&ni->size_lock, flags);
  1633. }
  1634. /* Mark the mft record dirty, so it gets written back. */
  1635. flush_dcache_mft_record_page(ctx->ntfs_ino);
  1636. mark_mft_record_dirty(ctx->ntfs_ino);
  1637. ntfs_attr_put_search_ctx(ctx);
  1638. unmap_mft_record(base_ni);
  1639. ntfs_debug("Done.");
  1640. return 0;
  1641. err_out:
  1642. if (err == -ENOMEM) {
  1643. ntfs_warning(vi->i_sb, "Error allocating memory required to "
  1644. "commit the write.");
  1645. if (PageUptodate(page)) {
  1646. ntfs_warning(vi->i_sb, "Page is uptodate, setting "
  1647. "dirty so the write will be retried "
  1648. "later on by the VM.");
  1649. /*
  1650. * Put the page on mapping->dirty_pages, but leave its
  1651. * buffers' dirty state as-is.
  1652. */
  1653. __set_page_dirty_nobuffers(page);
  1654. err = 0;
  1655. } else
  1656. ntfs_error(vi->i_sb, "Page is not uptodate. Written "
  1657. "data has been lost.");
  1658. } else {
  1659. ntfs_error(vi->i_sb, "Resident attribute commit write failed "
  1660. "with error %i.", err);
  1661. NVolSetErrors(ni->vol);
  1662. }
  1663. if (ctx)
  1664. ntfs_attr_put_search_ctx(ctx);
  1665. if (m)
  1666. unmap_mft_record(base_ni);
  1667. return err;
  1668. }
  1669. /*
  1670. * Copy as much as we can into the pages and return the number of bytes which
  1671. * were successfully copied. If a fault is encountered then clear the pages
  1672. * out to (ofs + bytes) and return the number of bytes which were copied.
  1673. */
  1674. static size_t ntfs_copy_from_user_iter(struct page **pages, unsigned nr_pages,
  1675. unsigned ofs, struct iov_iter *i, size_t bytes)
  1676. {
  1677. struct page **last_page = pages + nr_pages;
  1678. size_t total = 0;
  1679. struct iov_iter data = *i;
  1680. unsigned len, copied;
  1681. do {
  1682. len = PAGE_SIZE - ofs;
  1683. if (len > bytes)
  1684. len = bytes;
  1685. copied = iov_iter_copy_from_user_atomic(*pages, &data, ofs,
  1686. len);
  1687. total += copied;
  1688. bytes -= copied;
  1689. if (!bytes)
  1690. break;
  1691. iov_iter_advance(&data, copied);
  1692. if (copied < len)
  1693. goto err;
  1694. ofs = 0;
  1695. } while (++pages < last_page);
  1696. out:
  1697. return total;
  1698. err:
  1699. /* Zero the rest of the target like __copy_from_user(). */
  1700. len = PAGE_SIZE - copied;
  1701. do {
  1702. if (len > bytes)
  1703. len = bytes;
  1704. zero_user(*pages, copied, len);
  1705. bytes -= len;
  1706. copied = 0;
  1707. len = PAGE_SIZE;
  1708. } while (++pages < last_page);
  1709. goto out;
  1710. }
  1711. /**
  1712. * ntfs_perform_write - perform buffered write to a file
  1713. * @file: file to write to
  1714. * @i: iov_iter with data to write
  1715. * @pos: byte offset in file at which to begin writing to
  1716. */
  1717. static ssize_t ntfs_perform_write(struct file *file, struct iov_iter *i,
  1718. loff_t pos)
  1719. {
  1720. struct address_space *mapping = file->f_mapping;
  1721. struct inode *vi = mapping->host;
  1722. ntfs_inode *ni = NTFS_I(vi);
  1723. ntfs_volume *vol = ni->vol;
  1724. struct page *pages[NTFS_MAX_PAGES_PER_CLUSTER];
  1725. struct page *cached_page = NULL;
  1726. VCN last_vcn;
  1727. LCN lcn;
  1728. size_t bytes;
  1729. ssize_t status, written = 0;
  1730. unsigned nr_pages;
  1731. ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, pos "
  1732. "0x%llx, count 0x%lx.", vi->i_ino,
  1733. (unsigned)le32_to_cpu(ni->type),
  1734. (unsigned long long)pos,
  1735. (unsigned long)iov_iter_count(i));
  1736. /*
  1737. * If a previous ntfs_truncate() failed, repeat it and abort if it
  1738. * fails again.
  1739. */
  1740. if (unlikely(NInoTruncateFailed(ni))) {
  1741. int err;
  1742. inode_dio_wait(vi);
  1743. err = ntfs_truncate(vi);
  1744. if (err || NInoTruncateFailed(ni)) {
  1745. if (!err)
  1746. err = -EIO;
  1747. ntfs_error(vol->sb, "Cannot perform write to inode "
  1748. "0x%lx, attribute type 0x%x, because "
  1749. "ntfs_truncate() failed (error code "
  1750. "%i).", vi->i_ino,
  1751. (unsigned)le32_to_cpu(ni->type), err);
  1752. return err;
  1753. }
  1754. }
  1755. /*
  1756. * Determine the number of pages per cluster for non-resident
  1757. * attributes.
  1758. */
  1759. nr_pages = 1;
  1760. if (vol->cluster_size > PAGE_SIZE && NInoNonResident(ni))
  1761. nr_pages = vol->cluster_size >> PAGE_SHIFT;
  1762. last_vcn = -1;
  1763. do {
  1764. VCN vcn;
  1765. pgoff_t idx, start_idx;
  1766. unsigned ofs, do_pages, u;
  1767. size_t copied;
  1768. start_idx = idx = pos >> PAGE_SHIFT;
  1769. ofs = pos & ~PAGE_MASK;
  1770. bytes = PAGE_SIZE - ofs;
  1771. do_pages = 1;
  1772. if (nr_pages > 1) {
  1773. vcn = pos >> vol->cluster_size_bits;
  1774. if (vcn != last_vcn) {
  1775. last_vcn = vcn;
  1776. /*
  1777. * Get the lcn of the vcn the write is in. If
  1778. * it is a hole, need to lock down all pages in
  1779. * the cluster.
  1780. */
  1781. down_read(&ni->runlist.lock);
  1782. lcn = ntfs_attr_vcn_to_lcn_nolock(ni, pos >>
  1783. vol->cluster_size_bits, false);
  1784. up_read(&ni->runlist.lock);
  1785. if (unlikely(lcn < LCN_HOLE)) {
  1786. if (lcn == LCN_ENOMEM)
  1787. status = -ENOMEM;
  1788. else {
  1789. status = -EIO;
  1790. ntfs_error(vol->sb, "Cannot "
  1791. "perform write to "
  1792. "inode 0x%lx, "
  1793. "attribute type 0x%x, "
  1794. "because the attribute "
  1795. "is corrupt.",
  1796. vi->i_ino, (unsigned)
  1797. le32_to_cpu(ni->type));
  1798. }
  1799. break;
  1800. }
  1801. if (lcn == LCN_HOLE) {
  1802. start_idx = (pos & ~(s64)
  1803. vol->cluster_size_mask)
  1804. >> PAGE_SHIFT;
  1805. bytes = vol->cluster_size - (pos &
  1806. vol->cluster_size_mask);
  1807. do_pages = nr_pages;
  1808. }
  1809. }
  1810. }
  1811. if (bytes > iov_iter_count(i))
  1812. bytes = iov_iter_count(i);
  1813. again:
  1814. /*
  1815. * Bring in the user page(s) that we will copy from _first_.
  1816. * Otherwise there is a nasty deadlock on copying from the same
  1817. * page(s) as we are writing to, without it/them being marked
  1818. * up-to-date. Note, at present there is nothing to stop the
  1819. * pages being swapped out between us bringing them into memory
  1820. * and doing the actual copying.
  1821. */
  1822. if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
  1823. status = -EFAULT;
  1824. break;
  1825. }
  1826. /* Get and lock @do_pages starting at index @start_idx. */
  1827. status = __ntfs_grab_cache_pages(mapping, start_idx, do_pages,
  1828. pages, &cached_page);
  1829. if (unlikely(status))
  1830. break;
  1831. /*
  1832. * For non-resident attributes, we need to fill any holes with
  1833. * actual clusters and ensure all bufferes are mapped. We also
  1834. * need to bring uptodate any buffers that are only partially
  1835. * being written to.
  1836. */
  1837. if (NInoNonResident(ni)) {
  1838. status = ntfs_prepare_pages_for_non_resident_write(
  1839. pages, do_pages, pos, bytes);
  1840. if (unlikely(status)) {
  1841. do {
  1842. unlock_page(pages[--do_pages]);
  1843. put_page(pages[do_pages]);
  1844. } while (do_pages);
  1845. break;
  1846. }
  1847. }
  1848. u = (pos >> PAGE_SHIFT) - pages[0]->index;
  1849. copied = ntfs_copy_from_user_iter(pages + u, do_pages - u, ofs,
  1850. i, bytes);
  1851. ntfs_flush_dcache_pages(pages + u, do_pages - u);
  1852. status = 0;
  1853. if (likely(copied == bytes)) {
  1854. status = ntfs_commit_pages_after_write(pages, do_pages,
  1855. pos, bytes);
  1856. if (!status)
  1857. status = bytes;
  1858. }
  1859. do {
  1860. unlock_page(pages[--do_pages]);
  1861. put_page(pages[do_pages]);
  1862. } while (do_pages);
  1863. if (unlikely(status < 0))
  1864. break;
  1865. copied = status;
  1866. cond_resched();
  1867. if (unlikely(!copied)) {
  1868. size_t sc;
  1869. /*
  1870. * We failed to copy anything. Fall back to single
  1871. * segment length write.
  1872. *
  1873. * This is needed to avoid possible livelock in the
  1874. * case that all segments in the iov cannot be copied
  1875. * at once without a pagefault.
  1876. */
  1877. sc = iov_iter_single_seg_count(i);
  1878. if (bytes > sc)
  1879. bytes = sc;
  1880. goto again;
  1881. }
  1882. iov_iter_advance(i, copied);
  1883. pos += copied;
  1884. written += copied;
  1885. balance_dirty_pages_ratelimited(mapping);
  1886. if (fatal_signal_pending(current)) {
  1887. status = -EINTR;
  1888. break;
  1889. }
  1890. } while (iov_iter_count(i));
  1891. if (cached_page)
  1892. put_page(cached_page);
  1893. ntfs_debug("Done. Returning %s (written 0x%lx, status %li).",
  1894. written ? "written" : "status", (unsigned long)written,
  1895. (long)status);
  1896. return written ? written : status;
  1897. }
  1898. /**
  1899. * ntfs_file_write_iter - simple wrapper for ntfs_file_write_iter_nolock()
  1900. * @iocb: IO state structure
  1901. * @from: iov_iter with data to write
  1902. *
  1903. * Basically the same as generic_file_write_iter() except that it ends up
  1904. * up calling ntfs_perform_write() instead of generic_perform_write() and that
  1905. * O_DIRECT is not implemented.
  1906. */
  1907. static ssize_t ntfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
  1908. {
  1909. struct file *file = iocb->ki_filp;
  1910. struct inode *vi = file_inode(file);
  1911. ssize_t written = 0;
  1912. ssize_t err;
  1913. inode_lock(vi);
  1914. /* We can write back this queue in page reclaim. */
  1915. current->backing_dev_info = inode_to_bdi(vi);
  1916. err = ntfs_prepare_file_for_write(iocb, from);
  1917. if (iov_iter_count(from) && !err)
  1918. written = ntfs_perform_write(file, from, iocb->ki_pos);
  1919. current->backing_dev_info = NULL;
  1920. inode_unlock(vi);
  1921. iocb->ki_pos += written;
  1922. if (likely(written > 0))
  1923. written = generic_write_sync(iocb, written);
  1924. return written ? written : err;
  1925. }
  1926. /**
  1927. * ntfs_file_fsync - sync a file to disk
  1928. * @filp: file to be synced
  1929. * @datasync: if non-zero only flush user data and not metadata
  1930. *
  1931. * Data integrity sync of a file to disk. Used for fsync, fdatasync, and msync
  1932. * system calls. This function is inspired by fs/buffer.c::file_fsync().
  1933. *
  1934. * If @datasync is false, write the mft record and all associated extent mft
  1935. * records as well as the $DATA attribute and then sync the block device.
  1936. *
  1937. * If @datasync is true and the attribute is non-resident, we skip the writing
  1938. * of the mft record and all associated extent mft records (this might still
  1939. * happen due to the write_inode_now() call).
  1940. *
  1941. * Also, if @datasync is true, we do not wait on the inode to be written out
  1942. * but we always wait on the page cache pages to be written out.
  1943. *
  1944. * Locking: Caller must hold i_mutex on the inode.
  1945. *
  1946. * TODO: We should probably also write all attribute/index inodes associated
  1947. * with this inode but since we have no simple way of getting to them we ignore
  1948. * this problem for now.
  1949. */
  1950. static int ntfs_file_fsync(struct file *filp, loff_t start, loff_t end,
  1951. int datasync)
  1952. {
  1953. struct inode *vi = filp->f_mapping->host;
  1954. int err, ret = 0;
  1955. ntfs_debug("Entering for inode 0x%lx.", vi->i_ino);
  1956. err = file_write_and_wait_range(filp, start, end);
  1957. if (err)
  1958. return err;
  1959. inode_lock(vi);
  1960. BUG_ON(S_ISDIR(vi->i_mode));
  1961. if (!datasync || !NInoNonResident(NTFS_I(vi)))
  1962. ret = __ntfs_write_inode(vi, 1);
  1963. write_inode_now(vi, !datasync);
  1964. /*
  1965. * NOTE: If we were to use mapping->private_list (see ext2 and
  1966. * fs/buffer.c) for dirty blocks then we could optimize the below to be
  1967. * sync_mapping_buffers(vi->i_mapping).
  1968. */
  1969. err = sync_blockdev(vi->i_sb->s_bdev);
  1970. if (unlikely(err && !ret))
  1971. ret = err;
  1972. if (likely(!ret))
  1973. ntfs_debug("Done.");
  1974. else
  1975. ntfs_warning(vi->i_sb, "Failed to f%ssync inode 0x%lx. Error "
  1976. "%u.", datasync ? "data" : "", vi->i_ino, -ret);
  1977. inode_unlock(vi);
  1978. return ret;
  1979. }
  1980. #endif /* NTFS_RW */
  1981. const struct file_operations ntfs_file_ops = {
  1982. .llseek = generic_file_llseek,
  1983. .read_iter = generic_file_read_iter,
  1984. #ifdef NTFS_RW
  1985. .write_iter = ntfs_file_write_iter,
  1986. .fsync = ntfs_file_fsync,
  1987. #endif /* NTFS_RW */
  1988. .mmap = generic_file_mmap,
  1989. .open = ntfs_file_open,
  1990. .splice_read = generic_file_splice_read,
  1991. };
  1992. const struct inode_operations ntfs_file_inode_ops = {
  1993. #ifdef NTFS_RW
  1994. .setattr = ntfs_setattr,
  1995. #endif /* NTFS_RW */
  1996. };
  1997. const struct file_operations ntfs_empty_file_ops = {};
  1998. const struct inode_operations ntfs_empty_inode_ops = {};