file.c 62 KB

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