file.c 67 KB

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