file.c 66 KB

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