• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * inode.c
3  *
4  * PURPOSE
5  *  Inode handling routines for the OSTA-UDF(tm) filesystem.
6  *
7  * COPYRIGHT
8  *  This file is distributed under the terms of the GNU General Public
9  *  License (GPL). Copies of the GPL can be obtained from:
10  *    ftp://prep.ai.mit.edu/pub/gnu/GPL
11  *  Each contributing author retains all rights to their own work.
12  *
13  *  (C) 1998 Dave Boynton
14  *  (C) 1998-2004 Ben Fennema
15  *  (C) 1999-2000 Stelias Computing Inc
16  *
17  * HISTORY
18  *
19  *  10/04/98 dgb  Added rudimentary directory functions
20  *  10/07/98      Fully working udf_block_map! It works!
21  *  11/25/98      bmap altered to better support extents
22  *  12/06/98 blf  partition support in udf_iget, udf_block_map
23  *                and udf_read_inode
24  *  12/12/98      rewrote udf_block_map to handle next extents and descs across
25  *                block boundaries (which is not actually allowed)
26  *  12/20/98      added support for strategy 4096
27  *  03/07/99      rewrote udf_block_map (again)
28  *                New funcs, inode_bmap, udf_next_aext
29  *  04/19/99      Support for writing device EA's for major/minor #
30  */
31 
32 #include "udfdecl.h"
33 #include <linux/mm.h>
34 #include <linux/module.h>
35 #include <linux/pagemap.h>
36 #include <linux/writeback.h>
37 #include <linux/slab.h>
38 #include <linux/crc-itu-t.h>
39 #include <linux/mpage.h>
40 #include <linux/uio.h>
41 #include <linux/bio.h>
42 
43 #include "udf_i.h"
44 #include "udf_sb.h"
45 
46 #define EXTENT_MERGE_SIZE 5
47 
48 #define FE_MAPPED_PERMS	(FE_PERM_U_READ | FE_PERM_U_WRITE | FE_PERM_U_EXEC | \
49 			 FE_PERM_G_READ | FE_PERM_G_WRITE | FE_PERM_G_EXEC | \
50 			 FE_PERM_O_READ | FE_PERM_O_WRITE | FE_PERM_O_EXEC)
51 
52 #define FE_DELETE_PERMS	(FE_PERM_U_DELETE | FE_PERM_G_DELETE | \
53 			 FE_PERM_O_DELETE)
54 
55 static umode_t udf_convert_permissions(struct fileEntry *);
56 static int udf_update_inode(struct inode *, int);
57 static int udf_sync_inode(struct inode *inode);
58 static int udf_alloc_i_data(struct inode *inode, size_t size);
59 static sector_t inode_getblk(struct inode *, sector_t, int *, int *);
60 static int udf_insert_aext(struct inode *, struct extent_position,
61 			   struct kernel_lb_addr, uint32_t);
62 static void udf_split_extents(struct inode *, int *, int, udf_pblk_t,
63 			      struct kernel_long_ad *, int *);
64 static void udf_prealloc_extents(struct inode *, int, int,
65 				 struct kernel_long_ad *, int *);
66 static void udf_merge_extents(struct inode *, struct kernel_long_ad *, int *);
67 static int udf_update_extents(struct inode *, struct kernel_long_ad *, int,
68 			      int, struct extent_position *);
69 static int udf_get_block(struct inode *, sector_t, struct buffer_head *, int);
70 
__udf_clear_extent_cache(struct inode * inode)71 static void __udf_clear_extent_cache(struct inode *inode)
72 {
73 	struct udf_inode_info *iinfo = UDF_I(inode);
74 
75 	if (iinfo->cached_extent.lstart != -1) {
76 		brelse(iinfo->cached_extent.epos.bh);
77 		iinfo->cached_extent.lstart = -1;
78 	}
79 }
80 
81 /* Invalidate extent cache */
udf_clear_extent_cache(struct inode * inode)82 static void udf_clear_extent_cache(struct inode *inode)
83 {
84 	struct udf_inode_info *iinfo = UDF_I(inode);
85 
86 	spin_lock(&iinfo->i_extent_cache_lock);
87 	__udf_clear_extent_cache(inode);
88 	spin_unlock(&iinfo->i_extent_cache_lock);
89 }
90 
91 /* Return contents of extent cache */
udf_read_extent_cache(struct inode * inode,loff_t bcount,loff_t * lbcount,struct extent_position * pos)92 static int udf_read_extent_cache(struct inode *inode, loff_t bcount,
93 				 loff_t *lbcount, struct extent_position *pos)
94 {
95 	struct udf_inode_info *iinfo = UDF_I(inode);
96 	int ret = 0;
97 
98 	spin_lock(&iinfo->i_extent_cache_lock);
99 	if ((iinfo->cached_extent.lstart <= bcount) &&
100 	    (iinfo->cached_extent.lstart != -1)) {
101 		/* Cache hit */
102 		*lbcount = iinfo->cached_extent.lstart;
103 		memcpy(pos, &iinfo->cached_extent.epos,
104 		       sizeof(struct extent_position));
105 		if (pos->bh)
106 			get_bh(pos->bh);
107 		ret = 1;
108 	}
109 	spin_unlock(&iinfo->i_extent_cache_lock);
110 	return ret;
111 }
112 
113 /* Add extent to extent cache */
udf_update_extent_cache(struct inode * inode,loff_t estart,struct extent_position * pos)114 static void udf_update_extent_cache(struct inode *inode, loff_t estart,
115 				    struct extent_position *pos)
116 {
117 	struct udf_inode_info *iinfo = UDF_I(inode);
118 
119 	spin_lock(&iinfo->i_extent_cache_lock);
120 	/* Invalidate previously cached extent */
121 	__udf_clear_extent_cache(inode);
122 	if (pos->bh)
123 		get_bh(pos->bh);
124 	memcpy(&iinfo->cached_extent.epos, pos, sizeof(*pos));
125 	iinfo->cached_extent.lstart = estart;
126 	switch (iinfo->i_alloc_type) {
127 	case ICBTAG_FLAG_AD_SHORT:
128 		iinfo->cached_extent.epos.offset -= sizeof(struct short_ad);
129 		break;
130 	case ICBTAG_FLAG_AD_LONG:
131 		iinfo->cached_extent.epos.offset -= sizeof(struct long_ad);
132 		break;
133 	}
134 	spin_unlock(&iinfo->i_extent_cache_lock);
135 }
136 
udf_evict_inode(struct inode * inode)137 void udf_evict_inode(struct inode *inode)
138 {
139 	struct udf_inode_info *iinfo = UDF_I(inode);
140 	int want_delete = 0;
141 
142 	if (!is_bad_inode(inode)) {
143 		if (!inode->i_nlink) {
144 			want_delete = 1;
145 			udf_setsize(inode, 0);
146 			udf_update_inode(inode, IS_SYNC(inode));
147 		}
148 		if (iinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB &&
149 		    inode->i_size != iinfo->i_lenExtents) {
150 			udf_warn(inode->i_sb,
151 				 "Inode %lu (mode %o) has inode size %llu different from extent length %llu. Filesystem need not be standards compliant.\n",
152 				 inode->i_ino, inode->i_mode,
153 				 (unsigned long long)inode->i_size,
154 				 (unsigned long long)iinfo->i_lenExtents);
155 		}
156 	}
157 	truncate_inode_pages_final(&inode->i_data);
158 	invalidate_inode_buffers(inode);
159 	clear_inode(inode);
160 	kfree(iinfo->i_data);
161 	iinfo->i_data = NULL;
162 	udf_clear_extent_cache(inode);
163 	if (want_delete) {
164 		udf_free_inode(inode);
165 	}
166 }
167 
udf_write_failed(struct address_space * mapping,loff_t to)168 static void udf_write_failed(struct address_space *mapping, loff_t to)
169 {
170 	struct inode *inode = mapping->host;
171 	struct udf_inode_info *iinfo = UDF_I(inode);
172 	loff_t isize = inode->i_size;
173 
174 	if (to > isize) {
175 		truncate_pagecache(inode, isize);
176 		if (iinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) {
177 			down_write(&iinfo->i_data_sem);
178 			udf_clear_extent_cache(inode);
179 			udf_truncate_extents(inode);
180 			up_write(&iinfo->i_data_sem);
181 		}
182 	}
183 }
184 
udf_writepage(struct page * page,struct writeback_control * wbc)185 static int udf_writepage(struct page *page, struct writeback_control *wbc)
186 {
187 	return block_write_full_page(page, udf_get_block, wbc);
188 }
189 
udf_writepages(struct address_space * mapping,struct writeback_control * wbc)190 static int udf_writepages(struct address_space *mapping,
191 			struct writeback_control *wbc)
192 {
193 	return mpage_writepages(mapping, wbc, udf_get_block);
194 }
195 
udf_readpage(struct file * file,struct page * page)196 static int udf_readpage(struct file *file, struct page *page)
197 {
198 	return mpage_readpage(page, udf_get_block);
199 }
200 
udf_readahead(struct readahead_control * rac)201 static void udf_readahead(struct readahead_control *rac)
202 {
203 	mpage_readahead(rac, udf_get_block);
204 }
205 
udf_write_begin(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned flags,struct page ** pagep,void ** fsdata)206 static int udf_write_begin(struct file *file, struct address_space *mapping,
207 			loff_t pos, unsigned len, unsigned flags,
208 			struct page **pagep, void **fsdata)
209 {
210 	int ret;
211 
212 	ret = block_write_begin(mapping, pos, len, flags, pagep, udf_get_block);
213 	if (unlikely(ret))
214 		udf_write_failed(mapping, pos + len);
215 	return ret;
216 }
217 
udf_direct_IO(struct kiocb * iocb,struct iov_iter * iter)218 static ssize_t udf_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
219 {
220 	struct file *file = iocb->ki_filp;
221 	struct address_space *mapping = file->f_mapping;
222 	struct inode *inode = mapping->host;
223 	size_t count = iov_iter_count(iter);
224 	ssize_t ret;
225 
226 	ret = blockdev_direct_IO(iocb, inode, iter, udf_get_block);
227 	if (unlikely(ret < 0 && iov_iter_rw(iter) == WRITE))
228 		udf_write_failed(mapping, iocb->ki_pos + count);
229 	return ret;
230 }
231 
udf_bmap(struct address_space * mapping,sector_t block)232 static sector_t udf_bmap(struct address_space *mapping, sector_t block)
233 {
234 	return generic_block_bmap(mapping, block, udf_get_block);
235 }
236 
237 const struct address_space_operations udf_aops = {
238 	.readpage	= udf_readpage,
239 	.readahead	= udf_readahead,
240 	.writepage	= udf_writepage,
241 	.writepages	= udf_writepages,
242 	.write_begin	= udf_write_begin,
243 	.write_end	= generic_write_end,
244 	.direct_IO	= udf_direct_IO,
245 	.bmap		= udf_bmap,
246 };
247 
248 /*
249  * Expand file stored in ICB to a normal one-block-file
250  *
251  * This function requires i_data_sem for writing and releases it.
252  * This function requires i_mutex held
253  */
udf_expand_file_adinicb(struct inode * inode)254 int udf_expand_file_adinicb(struct inode *inode)
255 {
256 	struct page *page;
257 	char *kaddr;
258 	struct udf_inode_info *iinfo = UDF_I(inode);
259 	int err;
260 
261 	WARN_ON_ONCE(!inode_is_locked(inode));
262 	if (!iinfo->i_lenAlloc) {
263 		if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))
264 			iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;
265 		else
266 			iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;
267 		/* from now on we have normal address_space methods */
268 		inode->i_data.a_ops = &udf_aops;
269 		up_write(&iinfo->i_data_sem);
270 		mark_inode_dirty(inode);
271 		return 0;
272 	}
273 	/*
274 	 * Release i_data_sem so that we can lock a page - page lock ranks
275 	 * above i_data_sem. i_mutex still protects us against file changes.
276 	 */
277 	up_write(&iinfo->i_data_sem);
278 
279 	page = find_or_create_page(inode->i_mapping, 0, GFP_NOFS);
280 	if (!page)
281 		return -ENOMEM;
282 
283 	if (!PageUptodate(page)) {
284 		kaddr = kmap_atomic(page);
285 		memset(kaddr + iinfo->i_lenAlloc, 0x00,
286 		       PAGE_SIZE - iinfo->i_lenAlloc);
287 		memcpy(kaddr, iinfo->i_data + iinfo->i_lenEAttr,
288 			iinfo->i_lenAlloc);
289 		flush_dcache_page(page);
290 		SetPageUptodate(page);
291 		kunmap_atomic(kaddr);
292 	}
293 	down_write(&iinfo->i_data_sem);
294 	memset(iinfo->i_data + iinfo->i_lenEAttr, 0x00,
295 	       iinfo->i_lenAlloc);
296 	iinfo->i_lenAlloc = 0;
297 	if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))
298 		iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;
299 	else
300 		iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;
301 	/* from now on we have normal address_space methods */
302 	inode->i_data.a_ops = &udf_aops;
303 	set_page_dirty(page);
304 	unlock_page(page);
305 	up_write(&iinfo->i_data_sem);
306 	err = filemap_fdatawrite(inode->i_mapping);
307 	if (err) {
308 		/* Restore everything back so that we don't lose data... */
309 		lock_page(page);
310 		down_write(&iinfo->i_data_sem);
311 		kaddr = kmap_atomic(page);
312 		memcpy(iinfo->i_data + iinfo->i_lenEAttr, kaddr, inode->i_size);
313 		kunmap_atomic(kaddr);
314 		unlock_page(page);
315 		iinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB;
316 		inode->i_data.a_ops = &udf_adinicb_aops;
317 		iinfo->i_lenAlloc = inode->i_size;
318 		up_write(&iinfo->i_data_sem);
319 	}
320 	put_page(page);
321 	mark_inode_dirty(inode);
322 
323 	return err;
324 }
325 
udf_expand_dir_adinicb(struct inode * inode,udf_pblk_t * block,int * err)326 struct buffer_head *udf_expand_dir_adinicb(struct inode *inode,
327 					    udf_pblk_t *block, int *err)
328 {
329 	udf_pblk_t newblock;
330 	struct buffer_head *dbh = NULL;
331 	struct kernel_lb_addr eloc;
332 	uint8_t alloctype;
333 	struct extent_position epos;
334 
335 	struct udf_fileident_bh sfibh, dfibh;
336 	loff_t f_pos = udf_ext0_offset(inode);
337 	int size = udf_ext0_offset(inode) + inode->i_size;
338 	struct fileIdentDesc cfi, *sfi, *dfi;
339 	struct udf_inode_info *iinfo = UDF_I(inode);
340 
341 	if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))
342 		alloctype = ICBTAG_FLAG_AD_SHORT;
343 	else
344 		alloctype = ICBTAG_FLAG_AD_LONG;
345 
346 	if (!inode->i_size) {
347 		iinfo->i_alloc_type = alloctype;
348 		mark_inode_dirty(inode);
349 		return NULL;
350 	}
351 
352 	/* alloc block, and copy data to it */
353 	*block = udf_new_block(inode->i_sb, inode,
354 			       iinfo->i_location.partitionReferenceNum,
355 			       iinfo->i_location.logicalBlockNum, err);
356 	if (!(*block))
357 		return NULL;
358 	newblock = udf_get_pblock(inode->i_sb, *block,
359 				  iinfo->i_location.partitionReferenceNum,
360 				0);
361 	if (!newblock)
362 		return NULL;
363 	dbh = udf_tgetblk(inode->i_sb, newblock);
364 	if (!dbh)
365 		return NULL;
366 	lock_buffer(dbh);
367 	memset(dbh->b_data, 0x00, inode->i_sb->s_blocksize);
368 	set_buffer_uptodate(dbh);
369 	unlock_buffer(dbh);
370 	mark_buffer_dirty_inode(dbh, inode);
371 
372 	sfibh.soffset = sfibh.eoffset =
373 			f_pos & (inode->i_sb->s_blocksize - 1);
374 	sfibh.sbh = sfibh.ebh = NULL;
375 	dfibh.soffset = dfibh.eoffset = 0;
376 	dfibh.sbh = dfibh.ebh = dbh;
377 	while (f_pos < size) {
378 		iinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB;
379 		sfi = udf_fileident_read(inode, &f_pos, &sfibh, &cfi, NULL,
380 					 NULL, NULL, NULL);
381 		if (!sfi) {
382 			brelse(dbh);
383 			return NULL;
384 		}
385 		iinfo->i_alloc_type = alloctype;
386 		sfi->descTag.tagLocation = cpu_to_le32(*block);
387 		dfibh.soffset = dfibh.eoffset;
388 		dfibh.eoffset += (sfibh.eoffset - sfibh.soffset);
389 		dfi = (struct fileIdentDesc *)(dbh->b_data + dfibh.soffset);
390 		if (udf_write_fi(inode, sfi, dfi, &dfibh, sfi->impUse,
391 				 sfi->fileIdent +
392 					le16_to_cpu(sfi->lengthOfImpUse))) {
393 			iinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB;
394 			brelse(dbh);
395 			return NULL;
396 		}
397 	}
398 	mark_buffer_dirty_inode(dbh, inode);
399 
400 	memset(iinfo->i_data + iinfo->i_lenEAttr, 0, iinfo->i_lenAlloc);
401 	iinfo->i_lenAlloc = 0;
402 	eloc.logicalBlockNum = *block;
403 	eloc.partitionReferenceNum =
404 				iinfo->i_location.partitionReferenceNum;
405 	iinfo->i_lenExtents = inode->i_size;
406 	epos.bh = NULL;
407 	epos.block = iinfo->i_location;
408 	epos.offset = udf_file_entry_alloc_offset(inode);
409 	udf_add_aext(inode, &epos, &eloc, inode->i_size, 0);
410 	/* UniqueID stuff */
411 
412 	brelse(epos.bh);
413 	mark_inode_dirty(inode);
414 	return dbh;
415 }
416 
udf_get_block(struct inode * inode,sector_t block,struct buffer_head * bh_result,int create)417 static int udf_get_block(struct inode *inode, sector_t block,
418 			 struct buffer_head *bh_result, int create)
419 {
420 	int err, new;
421 	sector_t phys = 0;
422 	struct udf_inode_info *iinfo;
423 
424 	if (!create) {
425 		phys = udf_block_map(inode, block);
426 		if (phys)
427 			map_bh(bh_result, inode->i_sb, phys);
428 		return 0;
429 	}
430 
431 	err = -EIO;
432 	new = 0;
433 	iinfo = UDF_I(inode);
434 
435 	down_write(&iinfo->i_data_sem);
436 	if (block == iinfo->i_next_alloc_block + 1) {
437 		iinfo->i_next_alloc_block++;
438 		iinfo->i_next_alloc_goal++;
439 	}
440 
441 	/*
442 	 * Block beyond EOF and prealloc extents? Just discard preallocation
443 	 * as it is not useful and complicates things.
444 	 */
445 	if (((loff_t)block) << inode->i_blkbits >= iinfo->i_lenExtents)
446 		udf_discard_prealloc(inode);
447 	udf_clear_extent_cache(inode);
448 	phys = inode_getblk(inode, block, &err, &new);
449 	if (!phys)
450 		goto abort;
451 
452 	if (new)
453 		set_buffer_new(bh_result);
454 	map_bh(bh_result, inode->i_sb, phys);
455 
456 abort:
457 	up_write(&iinfo->i_data_sem);
458 	return err;
459 }
460 
udf_getblk(struct inode * inode,udf_pblk_t block,int create,int * err)461 static struct buffer_head *udf_getblk(struct inode *inode, udf_pblk_t block,
462 				      int create, int *err)
463 {
464 	struct buffer_head *bh;
465 	struct buffer_head dummy;
466 
467 	dummy.b_state = 0;
468 	dummy.b_blocknr = -1000;
469 	*err = udf_get_block(inode, block, &dummy, create);
470 	if (!*err && buffer_mapped(&dummy)) {
471 		bh = sb_getblk(inode->i_sb, dummy.b_blocknr);
472 		if (buffer_new(&dummy)) {
473 			lock_buffer(bh);
474 			memset(bh->b_data, 0x00, inode->i_sb->s_blocksize);
475 			set_buffer_uptodate(bh);
476 			unlock_buffer(bh);
477 			mark_buffer_dirty_inode(bh, inode);
478 		}
479 		return bh;
480 	}
481 
482 	return NULL;
483 }
484 
485 /* Extend the file with new blocks totaling 'new_block_bytes',
486  * return the number of extents added
487  */
udf_do_extend_file(struct inode * inode,struct extent_position * last_pos,struct kernel_long_ad * last_ext,loff_t new_block_bytes)488 static int udf_do_extend_file(struct inode *inode,
489 			      struct extent_position *last_pos,
490 			      struct kernel_long_ad *last_ext,
491 			      loff_t new_block_bytes)
492 {
493 	uint32_t add;
494 	int count = 0, fake = !(last_ext->extLength & UDF_EXTENT_LENGTH_MASK);
495 	struct super_block *sb = inode->i_sb;
496 	struct udf_inode_info *iinfo;
497 	int err;
498 
499 	/* The previous extent is fake and we should not extend by anything
500 	 * - there's nothing to do... */
501 	if (!new_block_bytes && fake)
502 		return 0;
503 
504 	iinfo = UDF_I(inode);
505 	/* Round the last extent up to a multiple of block size */
506 	if (last_ext->extLength & (sb->s_blocksize - 1)) {
507 		last_ext->extLength =
508 			(last_ext->extLength & UDF_EXTENT_FLAG_MASK) |
509 			(((last_ext->extLength & UDF_EXTENT_LENGTH_MASK) +
510 			  sb->s_blocksize - 1) & ~(sb->s_blocksize - 1));
511 		iinfo->i_lenExtents =
512 			(iinfo->i_lenExtents + sb->s_blocksize - 1) &
513 			~(sb->s_blocksize - 1);
514 	}
515 
516 	/* Can we merge with the previous extent? */
517 	if ((last_ext->extLength & UDF_EXTENT_FLAG_MASK) ==
518 					EXT_NOT_RECORDED_NOT_ALLOCATED) {
519 		add = (1 << 30) - sb->s_blocksize -
520 			(last_ext->extLength & UDF_EXTENT_LENGTH_MASK);
521 		if (add > new_block_bytes)
522 			add = new_block_bytes;
523 		new_block_bytes -= add;
524 		last_ext->extLength += add;
525 	}
526 
527 	if (fake) {
528 		err = udf_add_aext(inode, last_pos, &last_ext->extLocation,
529 				   last_ext->extLength, 1);
530 		if (err < 0)
531 			goto out_err;
532 		count++;
533 	} else {
534 		struct kernel_lb_addr tmploc;
535 		uint32_t tmplen;
536 
537 		udf_write_aext(inode, last_pos, &last_ext->extLocation,
538 				last_ext->extLength, 1);
539 
540 		/*
541 		 * We've rewritten the last extent. If we are going to add
542 		 * more extents, we may need to enter possible following
543 		 * empty indirect extent.
544 		 */
545 		if (new_block_bytes)
546 			udf_next_aext(inode, last_pos, &tmploc, &tmplen, 0);
547 	}
548 
549 	/* Managed to do everything necessary? */
550 	if (!new_block_bytes)
551 		goto out;
552 
553 	/* All further extents will be NOT_RECORDED_NOT_ALLOCATED */
554 	last_ext->extLocation.logicalBlockNum = 0;
555 	last_ext->extLocation.partitionReferenceNum = 0;
556 	add = (1 << 30) - sb->s_blocksize;
557 	last_ext->extLength = EXT_NOT_RECORDED_NOT_ALLOCATED | add;
558 
559 	/* Create enough extents to cover the whole hole */
560 	while (new_block_bytes > add) {
561 		new_block_bytes -= add;
562 		err = udf_add_aext(inode, last_pos, &last_ext->extLocation,
563 				   last_ext->extLength, 1);
564 		if (err)
565 			goto out_err;
566 		count++;
567 	}
568 	if (new_block_bytes) {
569 		last_ext->extLength = EXT_NOT_RECORDED_NOT_ALLOCATED |
570 			new_block_bytes;
571 		err = udf_add_aext(inode, last_pos, &last_ext->extLocation,
572 				   last_ext->extLength, 1);
573 		if (err)
574 			goto out_err;
575 		count++;
576 	}
577 
578 out:
579 	/* last_pos should point to the last written extent... */
580 	if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT)
581 		last_pos->offset -= sizeof(struct short_ad);
582 	else if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG)
583 		last_pos->offset -= sizeof(struct long_ad);
584 	else
585 		return -EIO;
586 
587 	return count;
588 out_err:
589 	/* Remove extents we've created so far */
590 	udf_clear_extent_cache(inode);
591 	udf_truncate_extents(inode);
592 	return err;
593 }
594 
595 /* Extend the final block of the file to final_block_len bytes */
udf_do_extend_final_block(struct inode * inode,struct extent_position * last_pos,struct kernel_long_ad * last_ext,uint32_t new_elen)596 static void udf_do_extend_final_block(struct inode *inode,
597 				      struct extent_position *last_pos,
598 				      struct kernel_long_ad *last_ext,
599 				      uint32_t new_elen)
600 {
601 	uint32_t added_bytes;
602 
603 	/*
604 	 * Extent already large enough? It may be already rounded up to block
605 	 * size...
606 	 */
607 	if (new_elen <= (last_ext->extLength & UDF_EXTENT_LENGTH_MASK))
608 		return;
609 	added_bytes = new_elen - (last_ext->extLength & UDF_EXTENT_LENGTH_MASK);
610 	last_ext->extLength += added_bytes;
611 	UDF_I(inode)->i_lenExtents += added_bytes;
612 
613 	udf_write_aext(inode, last_pos, &last_ext->extLocation,
614 			last_ext->extLength, 1);
615 }
616 
udf_extend_file(struct inode * inode,loff_t newsize)617 static int udf_extend_file(struct inode *inode, loff_t newsize)
618 {
619 
620 	struct extent_position epos;
621 	struct kernel_lb_addr eloc;
622 	uint32_t elen;
623 	int8_t etype;
624 	struct super_block *sb = inode->i_sb;
625 	sector_t first_block = newsize >> sb->s_blocksize_bits, offset;
626 	loff_t new_elen;
627 	int adsize;
628 	struct udf_inode_info *iinfo = UDF_I(inode);
629 	struct kernel_long_ad extent;
630 	int err = 0;
631 	bool within_last_ext;
632 
633 	if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT)
634 		adsize = sizeof(struct short_ad);
635 	else if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG)
636 		adsize = sizeof(struct long_ad);
637 	else
638 		BUG();
639 
640 	/*
641 	 * When creating hole in file, just don't bother with preserving
642 	 * preallocation. It likely won't be very useful anyway.
643 	 */
644 	udf_discard_prealloc(inode);
645 
646 	etype = inode_bmap(inode, first_block, &epos, &eloc, &elen, &offset);
647 	within_last_ext = (etype != -1);
648 	/* We don't expect extents past EOF... */
649 	WARN_ON_ONCE(within_last_ext &&
650 		     elen > ((loff_t)offset + 1) << inode->i_blkbits);
651 
652 	if ((!epos.bh && epos.offset == udf_file_entry_alloc_offset(inode)) ||
653 	    (epos.bh && epos.offset == sizeof(struct allocExtDesc))) {
654 		/* File has no extents at all or has empty last
655 		 * indirect extent! Create a fake extent... */
656 		extent.extLocation.logicalBlockNum = 0;
657 		extent.extLocation.partitionReferenceNum = 0;
658 		extent.extLength = EXT_NOT_RECORDED_NOT_ALLOCATED;
659 	} else {
660 		epos.offset -= adsize;
661 		etype = udf_next_aext(inode, &epos, &extent.extLocation,
662 				      &extent.extLength, 0);
663 		extent.extLength |= etype << 30;
664 	}
665 
666 	new_elen = ((loff_t)offset << inode->i_blkbits) |
667 					(newsize & (sb->s_blocksize - 1));
668 
669 	/* File has extent covering the new size (could happen when extending
670 	 * inside a block)?
671 	 */
672 	if (within_last_ext) {
673 		/* Extending file within the last file block */
674 		udf_do_extend_final_block(inode, &epos, &extent, new_elen);
675 	} else {
676 		err = udf_do_extend_file(inode, &epos, &extent, new_elen);
677 	}
678 
679 	if (err < 0)
680 		goto out;
681 	err = 0;
682 	iinfo->i_lenExtents = newsize;
683 out:
684 	brelse(epos.bh);
685 	return err;
686 }
687 
inode_getblk(struct inode * inode,sector_t block,int * err,int * new)688 static sector_t inode_getblk(struct inode *inode, sector_t block,
689 			     int *err, int *new)
690 {
691 	struct kernel_long_ad laarr[EXTENT_MERGE_SIZE];
692 	struct extent_position prev_epos, cur_epos, next_epos;
693 	int count = 0, startnum = 0, endnum = 0;
694 	uint32_t elen = 0, tmpelen;
695 	struct kernel_lb_addr eloc, tmpeloc;
696 	int c = 1;
697 	loff_t lbcount = 0, b_off = 0;
698 	udf_pblk_t newblocknum, newblock;
699 	sector_t offset = 0;
700 	int8_t etype;
701 	struct udf_inode_info *iinfo = UDF_I(inode);
702 	udf_pblk_t goal = 0, pgoal = iinfo->i_location.logicalBlockNum;
703 	int lastblock = 0;
704 	bool isBeyondEOF;
705 
706 	*err = 0;
707 	*new = 0;
708 	prev_epos.offset = udf_file_entry_alloc_offset(inode);
709 	prev_epos.block = iinfo->i_location;
710 	prev_epos.bh = NULL;
711 	cur_epos = next_epos = prev_epos;
712 	b_off = (loff_t)block << inode->i_sb->s_blocksize_bits;
713 
714 	/* find the extent which contains the block we are looking for.
715 	   alternate between laarr[0] and laarr[1] for locations of the
716 	   current extent, and the previous extent */
717 	do {
718 		if (prev_epos.bh != cur_epos.bh) {
719 			brelse(prev_epos.bh);
720 			get_bh(cur_epos.bh);
721 			prev_epos.bh = cur_epos.bh;
722 		}
723 		if (cur_epos.bh != next_epos.bh) {
724 			brelse(cur_epos.bh);
725 			get_bh(next_epos.bh);
726 			cur_epos.bh = next_epos.bh;
727 		}
728 
729 		lbcount += elen;
730 
731 		prev_epos.block = cur_epos.block;
732 		cur_epos.block = next_epos.block;
733 
734 		prev_epos.offset = cur_epos.offset;
735 		cur_epos.offset = next_epos.offset;
736 
737 		etype = udf_next_aext(inode, &next_epos, &eloc, &elen, 1);
738 		if (etype == -1)
739 			break;
740 
741 		c = !c;
742 
743 		laarr[c].extLength = (etype << 30) | elen;
744 		laarr[c].extLocation = eloc;
745 
746 		if (etype != (EXT_NOT_RECORDED_NOT_ALLOCATED >> 30))
747 			pgoal = eloc.logicalBlockNum +
748 				((elen + inode->i_sb->s_blocksize - 1) >>
749 				 inode->i_sb->s_blocksize_bits);
750 
751 		count++;
752 	} while (lbcount + elen <= b_off);
753 
754 	b_off -= lbcount;
755 	offset = b_off >> inode->i_sb->s_blocksize_bits;
756 	/*
757 	 * Move prev_epos and cur_epos into indirect extent if we are at
758 	 * the pointer to it
759 	 */
760 	udf_next_aext(inode, &prev_epos, &tmpeloc, &tmpelen, 0);
761 	udf_next_aext(inode, &cur_epos, &tmpeloc, &tmpelen, 0);
762 
763 	/* if the extent is allocated and recorded, return the block
764 	   if the extent is not a multiple of the blocksize, round up */
765 
766 	if (etype == (EXT_RECORDED_ALLOCATED >> 30)) {
767 		if (elen & (inode->i_sb->s_blocksize - 1)) {
768 			elen = EXT_RECORDED_ALLOCATED |
769 				((elen + inode->i_sb->s_blocksize - 1) &
770 				 ~(inode->i_sb->s_blocksize - 1));
771 			udf_write_aext(inode, &cur_epos, &eloc, elen, 1);
772 		}
773 		newblock = udf_get_lb_pblock(inode->i_sb, &eloc, offset);
774 		goto out_free;
775 	}
776 
777 	/* Are we beyond EOF and preallocated extent? */
778 	if (etype == -1) {
779 		int ret;
780 		loff_t hole_len;
781 
782 		isBeyondEOF = true;
783 		if (count) {
784 			if (c)
785 				laarr[0] = laarr[1];
786 			startnum = 1;
787 		} else {
788 			/* Create a fake extent when there's not one */
789 			memset(&laarr[0].extLocation, 0x00,
790 				sizeof(struct kernel_lb_addr));
791 			laarr[0].extLength = EXT_NOT_RECORDED_NOT_ALLOCATED;
792 			/* Will udf_do_extend_file() create real extent from
793 			   a fake one? */
794 			startnum = (offset > 0);
795 		}
796 		/* Create extents for the hole between EOF and offset */
797 		hole_len = (loff_t)offset << inode->i_blkbits;
798 		ret = udf_do_extend_file(inode, &prev_epos, laarr, hole_len);
799 		if (ret < 0) {
800 			*err = ret;
801 			newblock = 0;
802 			goto out_free;
803 		}
804 		c = 0;
805 		offset = 0;
806 		count += ret;
807 		/*
808 		 * Is there any real extent? - otherwise we overwrite the fake
809 		 * one...
810 		 */
811 		if (count)
812 			c = !c;
813 		laarr[c].extLength = EXT_NOT_RECORDED_NOT_ALLOCATED |
814 			inode->i_sb->s_blocksize;
815 		memset(&laarr[c].extLocation, 0x00,
816 			sizeof(struct kernel_lb_addr));
817 		count++;
818 		endnum = c + 1;
819 		lastblock = 1;
820 	} else {
821 		isBeyondEOF = false;
822 		endnum = startnum = ((count > 2) ? 2 : count);
823 
824 		/* if the current extent is in position 0,
825 		   swap it with the previous */
826 		if (!c && count != 1) {
827 			laarr[2] = laarr[0];
828 			laarr[0] = laarr[1];
829 			laarr[1] = laarr[2];
830 			c = 1;
831 		}
832 
833 		/* if the current block is located in an extent,
834 		   read the next extent */
835 		etype = udf_next_aext(inode, &next_epos, &eloc, &elen, 0);
836 		if (etype != -1) {
837 			laarr[c + 1].extLength = (etype << 30) | elen;
838 			laarr[c + 1].extLocation = eloc;
839 			count++;
840 			startnum++;
841 			endnum++;
842 		} else
843 			lastblock = 1;
844 	}
845 
846 	/* if the current extent is not recorded but allocated, get the
847 	 * block in the extent corresponding to the requested block */
848 	if ((laarr[c].extLength >> 30) == (EXT_NOT_RECORDED_ALLOCATED >> 30))
849 		newblocknum = laarr[c].extLocation.logicalBlockNum + offset;
850 	else { /* otherwise, allocate a new block */
851 		if (iinfo->i_next_alloc_block == block)
852 			goal = iinfo->i_next_alloc_goal;
853 
854 		if (!goal) {
855 			if (!(goal = pgoal)) /* XXX: what was intended here? */
856 				goal = iinfo->i_location.logicalBlockNum + 1;
857 		}
858 
859 		newblocknum = udf_new_block(inode->i_sb, inode,
860 				iinfo->i_location.partitionReferenceNum,
861 				goal, err);
862 		if (!newblocknum) {
863 			*err = -ENOSPC;
864 			newblock = 0;
865 			goto out_free;
866 		}
867 		if (isBeyondEOF)
868 			iinfo->i_lenExtents += inode->i_sb->s_blocksize;
869 	}
870 
871 	/* if the extent the requsted block is located in contains multiple
872 	 * blocks, split the extent into at most three extents. blocks prior
873 	 * to requested block, requested block, and blocks after requested
874 	 * block */
875 	udf_split_extents(inode, &c, offset, newblocknum, laarr, &endnum);
876 
877 	/* We preallocate blocks only for regular files. It also makes sense
878 	 * for directories but there's a problem when to drop the
879 	 * preallocation. We might use some delayed work for that but I feel
880 	 * it's overengineering for a filesystem like UDF. */
881 	if (S_ISREG(inode->i_mode))
882 		udf_prealloc_extents(inode, c, lastblock, laarr, &endnum);
883 
884 	/* merge any continuous blocks in laarr */
885 	udf_merge_extents(inode, laarr, &endnum);
886 
887 	/* write back the new extents, inserting new extents if the new number
888 	 * of extents is greater than the old number, and deleting extents if
889 	 * the new number of extents is less than the old number */
890 	*err = udf_update_extents(inode, laarr, startnum, endnum, &prev_epos);
891 	if (*err < 0)
892 		goto out_free;
893 
894 	newblock = udf_get_pblock(inode->i_sb, newblocknum,
895 				iinfo->i_location.partitionReferenceNum, 0);
896 	if (!newblock) {
897 		*err = -EIO;
898 		goto out_free;
899 	}
900 	*new = 1;
901 	iinfo->i_next_alloc_block = block;
902 	iinfo->i_next_alloc_goal = newblocknum;
903 	inode->i_ctime = current_time(inode);
904 
905 	if (IS_SYNC(inode))
906 		udf_sync_inode(inode);
907 	else
908 		mark_inode_dirty(inode);
909 out_free:
910 	brelse(prev_epos.bh);
911 	brelse(cur_epos.bh);
912 	brelse(next_epos.bh);
913 	return newblock;
914 }
915 
udf_split_extents(struct inode * inode,int * c,int offset,udf_pblk_t newblocknum,struct kernel_long_ad * laarr,int * endnum)916 static void udf_split_extents(struct inode *inode, int *c, int offset,
917 			       udf_pblk_t newblocknum,
918 			       struct kernel_long_ad *laarr, int *endnum)
919 {
920 	unsigned long blocksize = inode->i_sb->s_blocksize;
921 	unsigned char blocksize_bits = inode->i_sb->s_blocksize_bits;
922 
923 	if ((laarr[*c].extLength >> 30) == (EXT_NOT_RECORDED_ALLOCATED >> 30) ||
924 	    (laarr[*c].extLength >> 30) ==
925 				(EXT_NOT_RECORDED_NOT_ALLOCATED >> 30)) {
926 		int curr = *c;
927 		int blen = ((laarr[curr].extLength & UDF_EXTENT_LENGTH_MASK) +
928 			    blocksize - 1) >> blocksize_bits;
929 		int8_t etype = (laarr[curr].extLength >> 30);
930 
931 		if (blen == 1)
932 			;
933 		else if (!offset || blen == offset + 1) {
934 			laarr[curr + 2] = laarr[curr + 1];
935 			laarr[curr + 1] = laarr[curr];
936 		} else {
937 			laarr[curr + 3] = laarr[curr + 1];
938 			laarr[curr + 2] = laarr[curr + 1] = laarr[curr];
939 		}
940 
941 		if (offset) {
942 			if (etype == (EXT_NOT_RECORDED_ALLOCATED >> 30)) {
943 				udf_free_blocks(inode->i_sb, inode,
944 						&laarr[curr].extLocation,
945 						0, offset);
946 				laarr[curr].extLength =
947 					EXT_NOT_RECORDED_NOT_ALLOCATED |
948 					(offset << blocksize_bits);
949 				laarr[curr].extLocation.logicalBlockNum = 0;
950 				laarr[curr].extLocation.
951 						partitionReferenceNum = 0;
952 			} else
953 				laarr[curr].extLength = (etype << 30) |
954 					(offset << blocksize_bits);
955 			curr++;
956 			(*c)++;
957 			(*endnum)++;
958 		}
959 
960 		laarr[curr].extLocation.logicalBlockNum = newblocknum;
961 		if (etype == (EXT_NOT_RECORDED_NOT_ALLOCATED >> 30))
962 			laarr[curr].extLocation.partitionReferenceNum =
963 				UDF_I(inode)->i_location.partitionReferenceNum;
964 		laarr[curr].extLength = EXT_RECORDED_ALLOCATED |
965 			blocksize;
966 		curr++;
967 
968 		if (blen != offset + 1) {
969 			if (etype == (EXT_NOT_RECORDED_ALLOCATED >> 30))
970 				laarr[curr].extLocation.logicalBlockNum +=
971 								offset + 1;
972 			laarr[curr].extLength = (etype << 30) |
973 				((blen - (offset + 1)) << blocksize_bits);
974 			curr++;
975 			(*endnum)++;
976 		}
977 	}
978 }
979 
udf_prealloc_extents(struct inode * inode,int c,int lastblock,struct kernel_long_ad * laarr,int * endnum)980 static void udf_prealloc_extents(struct inode *inode, int c, int lastblock,
981 				 struct kernel_long_ad *laarr,
982 				 int *endnum)
983 {
984 	int start, length = 0, currlength = 0, i;
985 
986 	if (*endnum >= (c + 1)) {
987 		if (!lastblock)
988 			return;
989 		else
990 			start = c;
991 	} else {
992 		if ((laarr[c + 1].extLength >> 30) ==
993 					(EXT_NOT_RECORDED_ALLOCATED >> 30)) {
994 			start = c + 1;
995 			length = currlength =
996 				(((laarr[c + 1].extLength &
997 					UDF_EXTENT_LENGTH_MASK) +
998 				inode->i_sb->s_blocksize - 1) >>
999 				inode->i_sb->s_blocksize_bits);
1000 		} else
1001 			start = c;
1002 	}
1003 
1004 	for (i = start + 1; i <= *endnum; i++) {
1005 		if (i == *endnum) {
1006 			if (lastblock)
1007 				length += UDF_DEFAULT_PREALLOC_BLOCKS;
1008 		} else if ((laarr[i].extLength >> 30) ==
1009 				(EXT_NOT_RECORDED_NOT_ALLOCATED >> 30)) {
1010 			length += (((laarr[i].extLength &
1011 						UDF_EXTENT_LENGTH_MASK) +
1012 				    inode->i_sb->s_blocksize - 1) >>
1013 				    inode->i_sb->s_blocksize_bits);
1014 		} else
1015 			break;
1016 	}
1017 
1018 	if (length) {
1019 		int next = laarr[start].extLocation.logicalBlockNum +
1020 			(((laarr[start].extLength & UDF_EXTENT_LENGTH_MASK) +
1021 			  inode->i_sb->s_blocksize - 1) >>
1022 			  inode->i_sb->s_blocksize_bits);
1023 		int numalloc = udf_prealloc_blocks(inode->i_sb, inode,
1024 				laarr[start].extLocation.partitionReferenceNum,
1025 				next, (UDF_DEFAULT_PREALLOC_BLOCKS > length ?
1026 				length : UDF_DEFAULT_PREALLOC_BLOCKS) -
1027 				currlength);
1028 		if (numalloc) 	{
1029 			if (start == (c + 1))
1030 				laarr[start].extLength +=
1031 					(numalloc <<
1032 					 inode->i_sb->s_blocksize_bits);
1033 			else {
1034 				memmove(&laarr[c + 2], &laarr[c + 1],
1035 					sizeof(struct long_ad) * (*endnum - (c + 1)));
1036 				(*endnum)++;
1037 				laarr[c + 1].extLocation.logicalBlockNum = next;
1038 				laarr[c + 1].extLocation.partitionReferenceNum =
1039 					laarr[c].extLocation.
1040 							partitionReferenceNum;
1041 				laarr[c + 1].extLength =
1042 					EXT_NOT_RECORDED_ALLOCATED |
1043 					(numalloc <<
1044 					 inode->i_sb->s_blocksize_bits);
1045 				start = c + 1;
1046 			}
1047 
1048 			for (i = start + 1; numalloc && i < *endnum; i++) {
1049 				int elen = ((laarr[i].extLength &
1050 						UDF_EXTENT_LENGTH_MASK) +
1051 					    inode->i_sb->s_blocksize - 1) >>
1052 					    inode->i_sb->s_blocksize_bits;
1053 
1054 				if (elen > numalloc) {
1055 					laarr[i].extLength -=
1056 						(numalloc <<
1057 						 inode->i_sb->s_blocksize_bits);
1058 					numalloc = 0;
1059 				} else {
1060 					numalloc -= elen;
1061 					if (*endnum > (i + 1))
1062 						memmove(&laarr[i],
1063 							&laarr[i + 1],
1064 							sizeof(struct long_ad) *
1065 							(*endnum - (i + 1)));
1066 					i--;
1067 					(*endnum)--;
1068 				}
1069 			}
1070 			UDF_I(inode)->i_lenExtents +=
1071 				numalloc << inode->i_sb->s_blocksize_bits;
1072 		}
1073 	}
1074 }
1075 
udf_merge_extents(struct inode * inode,struct kernel_long_ad * laarr,int * endnum)1076 static void udf_merge_extents(struct inode *inode, struct kernel_long_ad *laarr,
1077 			      int *endnum)
1078 {
1079 	int i;
1080 	unsigned long blocksize = inode->i_sb->s_blocksize;
1081 	unsigned char blocksize_bits = inode->i_sb->s_blocksize_bits;
1082 
1083 	for (i = 0; i < (*endnum - 1); i++) {
1084 		struct kernel_long_ad *li /*l[i]*/ = &laarr[i];
1085 		struct kernel_long_ad *lip1 /*l[i plus 1]*/ = &laarr[i + 1];
1086 
1087 		if (((li->extLength >> 30) == (lip1->extLength >> 30)) &&
1088 			(((li->extLength >> 30) ==
1089 				(EXT_NOT_RECORDED_NOT_ALLOCATED >> 30)) ||
1090 			((lip1->extLocation.logicalBlockNum -
1091 			  li->extLocation.logicalBlockNum) ==
1092 			(((li->extLength & UDF_EXTENT_LENGTH_MASK) +
1093 			blocksize - 1) >> blocksize_bits)))) {
1094 
1095 			if (((li->extLength & UDF_EXTENT_LENGTH_MASK) +
1096 			     (lip1->extLength & UDF_EXTENT_LENGTH_MASK) +
1097 			     blocksize - 1) <= UDF_EXTENT_LENGTH_MASK) {
1098 				li->extLength = lip1->extLength +
1099 					(((li->extLength &
1100 						UDF_EXTENT_LENGTH_MASK) +
1101 					 blocksize - 1) & ~(blocksize - 1));
1102 				if (*endnum > (i + 2))
1103 					memmove(&laarr[i + 1], &laarr[i + 2],
1104 						sizeof(struct long_ad) *
1105 						(*endnum - (i + 2)));
1106 				i--;
1107 				(*endnum)--;
1108 			}
1109 		} else if (((li->extLength >> 30) ==
1110 				(EXT_NOT_RECORDED_ALLOCATED >> 30)) &&
1111 			   ((lip1->extLength >> 30) ==
1112 				(EXT_NOT_RECORDED_NOT_ALLOCATED >> 30))) {
1113 			udf_free_blocks(inode->i_sb, inode, &li->extLocation, 0,
1114 					((li->extLength &
1115 					  UDF_EXTENT_LENGTH_MASK) +
1116 					 blocksize - 1) >> blocksize_bits);
1117 			li->extLocation.logicalBlockNum = 0;
1118 			li->extLocation.partitionReferenceNum = 0;
1119 
1120 			if (((li->extLength & UDF_EXTENT_LENGTH_MASK) +
1121 			     (lip1->extLength & UDF_EXTENT_LENGTH_MASK) +
1122 			     blocksize - 1) & ~UDF_EXTENT_LENGTH_MASK) {
1123 				lip1->extLength = (lip1->extLength -
1124 						   (li->extLength &
1125 						   UDF_EXTENT_LENGTH_MASK) +
1126 						   UDF_EXTENT_LENGTH_MASK) &
1127 						   ~(blocksize - 1);
1128 				li->extLength = (li->extLength &
1129 						 UDF_EXTENT_FLAG_MASK) +
1130 						(UDF_EXTENT_LENGTH_MASK + 1) -
1131 						blocksize;
1132 			} else {
1133 				li->extLength = lip1->extLength +
1134 					(((li->extLength &
1135 						UDF_EXTENT_LENGTH_MASK) +
1136 					  blocksize - 1) & ~(blocksize - 1));
1137 				if (*endnum > (i + 2))
1138 					memmove(&laarr[i + 1], &laarr[i + 2],
1139 						sizeof(struct long_ad) *
1140 						(*endnum - (i + 2)));
1141 				i--;
1142 				(*endnum)--;
1143 			}
1144 		} else if ((li->extLength >> 30) ==
1145 					(EXT_NOT_RECORDED_ALLOCATED >> 30)) {
1146 			udf_free_blocks(inode->i_sb, inode,
1147 					&li->extLocation, 0,
1148 					((li->extLength &
1149 						UDF_EXTENT_LENGTH_MASK) +
1150 					 blocksize - 1) >> blocksize_bits);
1151 			li->extLocation.logicalBlockNum = 0;
1152 			li->extLocation.partitionReferenceNum = 0;
1153 			li->extLength = (li->extLength &
1154 						UDF_EXTENT_LENGTH_MASK) |
1155 						EXT_NOT_RECORDED_NOT_ALLOCATED;
1156 		}
1157 	}
1158 }
1159 
udf_update_extents(struct inode * inode,struct kernel_long_ad * laarr,int startnum,int endnum,struct extent_position * epos)1160 static int udf_update_extents(struct inode *inode, struct kernel_long_ad *laarr,
1161 			      int startnum, int endnum,
1162 			      struct extent_position *epos)
1163 {
1164 	int start = 0, i;
1165 	struct kernel_lb_addr tmploc;
1166 	uint32_t tmplen;
1167 	int err;
1168 
1169 	if (startnum > endnum) {
1170 		for (i = 0; i < (startnum - endnum); i++)
1171 			udf_delete_aext(inode, *epos);
1172 	} else if (startnum < endnum) {
1173 		for (i = 0; i < (endnum - startnum); i++) {
1174 			err = udf_insert_aext(inode, *epos,
1175 					      laarr[i].extLocation,
1176 					      laarr[i].extLength);
1177 			/*
1178 			 * If we fail here, we are likely corrupting the extent
1179 			 * list and leaking blocks. At least stop early to
1180 			 * limit the damage.
1181 			 */
1182 			if (err < 0)
1183 				return err;
1184 			udf_next_aext(inode, epos, &laarr[i].extLocation,
1185 				      &laarr[i].extLength, 1);
1186 			start++;
1187 		}
1188 	}
1189 
1190 	for (i = start; i < endnum; i++) {
1191 		udf_next_aext(inode, epos, &tmploc, &tmplen, 0);
1192 		udf_write_aext(inode, epos, &laarr[i].extLocation,
1193 			       laarr[i].extLength, 1);
1194 	}
1195 	return 0;
1196 }
1197 
udf_bread(struct inode * inode,udf_pblk_t block,int create,int * err)1198 struct buffer_head *udf_bread(struct inode *inode, udf_pblk_t block,
1199 			      int create, int *err)
1200 {
1201 	struct buffer_head *bh = NULL;
1202 
1203 	bh = udf_getblk(inode, block, create, err);
1204 	if (!bh)
1205 		return NULL;
1206 
1207 	if (buffer_uptodate(bh))
1208 		return bh;
1209 
1210 	ll_rw_block(REQ_OP_READ, 0, 1, &bh);
1211 
1212 	wait_on_buffer(bh);
1213 	if (buffer_uptodate(bh))
1214 		return bh;
1215 
1216 	brelse(bh);
1217 	*err = -EIO;
1218 	return NULL;
1219 }
1220 
udf_setsize(struct inode * inode,loff_t newsize)1221 int udf_setsize(struct inode *inode, loff_t newsize)
1222 {
1223 	int err;
1224 	struct udf_inode_info *iinfo;
1225 	unsigned int bsize = i_blocksize(inode);
1226 
1227 	if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
1228 	      S_ISLNK(inode->i_mode)))
1229 		return -EINVAL;
1230 	if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
1231 		return -EPERM;
1232 
1233 	iinfo = UDF_I(inode);
1234 	if (newsize > inode->i_size) {
1235 		down_write(&iinfo->i_data_sem);
1236 		if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) {
1237 			if (bsize <
1238 			    (udf_file_entry_alloc_offset(inode) + newsize)) {
1239 				err = udf_expand_file_adinicb(inode);
1240 				if (err)
1241 					return err;
1242 				down_write(&iinfo->i_data_sem);
1243 			} else {
1244 				iinfo->i_lenAlloc = newsize;
1245 				goto set_size;
1246 			}
1247 		}
1248 		err = udf_extend_file(inode, newsize);
1249 		if (err) {
1250 			up_write(&iinfo->i_data_sem);
1251 			return err;
1252 		}
1253 set_size:
1254 		up_write(&iinfo->i_data_sem);
1255 		truncate_setsize(inode, newsize);
1256 	} else {
1257 		if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) {
1258 			down_write(&iinfo->i_data_sem);
1259 			udf_clear_extent_cache(inode);
1260 			memset(iinfo->i_data + iinfo->i_lenEAttr + newsize,
1261 			       0x00, bsize - newsize -
1262 			       udf_file_entry_alloc_offset(inode));
1263 			iinfo->i_lenAlloc = newsize;
1264 			truncate_setsize(inode, newsize);
1265 			up_write(&iinfo->i_data_sem);
1266 			goto update_time;
1267 		}
1268 		err = block_truncate_page(inode->i_mapping, newsize,
1269 					  udf_get_block);
1270 		if (err)
1271 			return err;
1272 		truncate_setsize(inode, newsize);
1273 		down_write(&iinfo->i_data_sem);
1274 		udf_clear_extent_cache(inode);
1275 		err = udf_truncate_extents(inode);
1276 		up_write(&iinfo->i_data_sem);
1277 		if (err)
1278 			return err;
1279 	}
1280 update_time:
1281 	inode->i_mtime = inode->i_ctime = current_time(inode);
1282 	if (IS_SYNC(inode))
1283 		udf_sync_inode(inode);
1284 	else
1285 		mark_inode_dirty(inode);
1286 	return 0;
1287 }
1288 
1289 /*
1290  * Maximum length of linked list formed by ICB hierarchy. The chosen number is
1291  * arbitrary - just that we hopefully don't limit any real use of rewritten
1292  * inode on write-once media but avoid looping for too long on corrupted media.
1293  */
1294 #define UDF_MAX_ICB_NESTING 1024
1295 
udf_read_inode(struct inode * inode,bool hidden_inode)1296 static int udf_read_inode(struct inode *inode, bool hidden_inode)
1297 {
1298 	struct buffer_head *bh = NULL;
1299 	struct fileEntry *fe;
1300 	struct extendedFileEntry *efe;
1301 	uint16_t ident;
1302 	struct udf_inode_info *iinfo = UDF_I(inode);
1303 	struct udf_sb_info *sbi = UDF_SB(inode->i_sb);
1304 	struct kernel_lb_addr *iloc = &iinfo->i_location;
1305 	unsigned int link_count;
1306 	unsigned int indirections = 0;
1307 	int bs = inode->i_sb->s_blocksize;
1308 	int ret = -EIO;
1309 	uint32_t uid, gid;
1310 
1311 reread:
1312 	if (iloc->partitionReferenceNum >= sbi->s_partitions) {
1313 		udf_debug("partition reference: %u > logical volume partitions: %u\n",
1314 			  iloc->partitionReferenceNum, sbi->s_partitions);
1315 		return -EIO;
1316 	}
1317 
1318 	if (iloc->logicalBlockNum >=
1319 	    sbi->s_partmaps[iloc->partitionReferenceNum].s_partition_len) {
1320 		udf_debug("block=%u, partition=%u out of range\n",
1321 			  iloc->logicalBlockNum, iloc->partitionReferenceNum);
1322 		return -EIO;
1323 	}
1324 
1325 	/*
1326 	 * Set defaults, but the inode is still incomplete!
1327 	 * Note: get_new_inode() sets the following on a new inode:
1328 	 *      i_sb = sb
1329 	 *      i_no = ino
1330 	 *      i_flags = sb->s_flags
1331 	 *      i_state = 0
1332 	 * clean_inode(): zero fills and sets
1333 	 *      i_count = 1
1334 	 *      i_nlink = 1
1335 	 *      i_op = NULL;
1336 	 */
1337 	bh = udf_read_ptagged(inode->i_sb, iloc, 0, &ident);
1338 	if (!bh) {
1339 		udf_err(inode->i_sb, "(ino %lu) failed !bh\n", inode->i_ino);
1340 		return -EIO;
1341 	}
1342 
1343 	if (ident != TAG_IDENT_FE && ident != TAG_IDENT_EFE &&
1344 	    ident != TAG_IDENT_USE) {
1345 		udf_err(inode->i_sb, "(ino %lu) failed ident=%u\n",
1346 			inode->i_ino, ident);
1347 		goto out;
1348 	}
1349 
1350 	fe = (struct fileEntry *)bh->b_data;
1351 	efe = (struct extendedFileEntry *)bh->b_data;
1352 
1353 	if (fe->icbTag.strategyType == cpu_to_le16(4096)) {
1354 		struct buffer_head *ibh;
1355 
1356 		ibh = udf_read_ptagged(inode->i_sb, iloc, 1, &ident);
1357 		if (ident == TAG_IDENT_IE && ibh) {
1358 			struct kernel_lb_addr loc;
1359 			struct indirectEntry *ie;
1360 
1361 			ie = (struct indirectEntry *)ibh->b_data;
1362 			loc = lelb_to_cpu(ie->indirectICB.extLocation);
1363 
1364 			if (ie->indirectICB.extLength) {
1365 				brelse(ibh);
1366 				memcpy(&iinfo->i_location, &loc,
1367 				       sizeof(struct kernel_lb_addr));
1368 				if (++indirections > UDF_MAX_ICB_NESTING) {
1369 					udf_err(inode->i_sb,
1370 						"too many ICBs in ICB hierarchy"
1371 						" (max %d supported)\n",
1372 						UDF_MAX_ICB_NESTING);
1373 					goto out;
1374 				}
1375 				brelse(bh);
1376 				goto reread;
1377 			}
1378 		}
1379 		brelse(ibh);
1380 	} else if (fe->icbTag.strategyType != cpu_to_le16(4)) {
1381 		udf_err(inode->i_sb, "unsupported strategy type: %u\n",
1382 			le16_to_cpu(fe->icbTag.strategyType));
1383 		goto out;
1384 	}
1385 	if (fe->icbTag.strategyType == cpu_to_le16(4))
1386 		iinfo->i_strat4096 = 0;
1387 	else /* if (fe->icbTag.strategyType == cpu_to_le16(4096)) */
1388 		iinfo->i_strat4096 = 1;
1389 
1390 	iinfo->i_alloc_type = le16_to_cpu(fe->icbTag.flags) &
1391 							ICBTAG_FLAG_AD_MASK;
1392 	if (iinfo->i_alloc_type != ICBTAG_FLAG_AD_SHORT &&
1393 	    iinfo->i_alloc_type != ICBTAG_FLAG_AD_LONG &&
1394 	    iinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) {
1395 		ret = -EIO;
1396 		goto out;
1397 	}
1398 	iinfo->i_hidden = hidden_inode;
1399 	iinfo->i_unique = 0;
1400 	iinfo->i_lenEAttr = 0;
1401 	iinfo->i_lenExtents = 0;
1402 	iinfo->i_lenAlloc = 0;
1403 	iinfo->i_next_alloc_block = 0;
1404 	iinfo->i_next_alloc_goal = 0;
1405 	if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_EFE)) {
1406 		iinfo->i_efe = 1;
1407 		iinfo->i_use = 0;
1408 		ret = udf_alloc_i_data(inode, bs -
1409 					sizeof(struct extendedFileEntry));
1410 		if (ret)
1411 			goto out;
1412 		memcpy(iinfo->i_data,
1413 		       bh->b_data + sizeof(struct extendedFileEntry),
1414 		       bs - sizeof(struct extendedFileEntry));
1415 	} else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_FE)) {
1416 		iinfo->i_efe = 0;
1417 		iinfo->i_use = 0;
1418 		ret = udf_alloc_i_data(inode, bs - sizeof(struct fileEntry));
1419 		if (ret)
1420 			goto out;
1421 		memcpy(iinfo->i_data,
1422 		       bh->b_data + sizeof(struct fileEntry),
1423 		       bs - sizeof(struct fileEntry));
1424 	} else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_USE)) {
1425 		iinfo->i_efe = 0;
1426 		iinfo->i_use = 1;
1427 		iinfo->i_lenAlloc = le32_to_cpu(
1428 				((struct unallocSpaceEntry *)bh->b_data)->
1429 				 lengthAllocDescs);
1430 		ret = udf_alloc_i_data(inode, bs -
1431 					sizeof(struct unallocSpaceEntry));
1432 		if (ret)
1433 			goto out;
1434 		memcpy(iinfo->i_data,
1435 		       bh->b_data + sizeof(struct unallocSpaceEntry),
1436 		       bs - sizeof(struct unallocSpaceEntry));
1437 		return 0;
1438 	}
1439 
1440 	ret = -EIO;
1441 	read_lock(&sbi->s_cred_lock);
1442 	uid = le32_to_cpu(fe->uid);
1443 	if (uid == UDF_INVALID_ID ||
1444 	    UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_SET))
1445 		inode->i_uid = sbi->s_uid;
1446 	else
1447 		i_uid_write(inode, uid);
1448 
1449 	gid = le32_to_cpu(fe->gid);
1450 	if (gid == UDF_INVALID_ID ||
1451 	    UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_SET))
1452 		inode->i_gid = sbi->s_gid;
1453 	else
1454 		i_gid_write(inode, gid);
1455 
1456 	if (fe->icbTag.fileType != ICBTAG_FILE_TYPE_DIRECTORY &&
1457 			sbi->s_fmode != UDF_INVALID_MODE)
1458 		inode->i_mode = sbi->s_fmode;
1459 	else if (fe->icbTag.fileType == ICBTAG_FILE_TYPE_DIRECTORY &&
1460 			sbi->s_dmode != UDF_INVALID_MODE)
1461 		inode->i_mode = sbi->s_dmode;
1462 	else
1463 		inode->i_mode = udf_convert_permissions(fe);
1464 	inode->i_mode &= ~sbi->s_umask;
1465 	iinfo->i_extraPerms = le32_to_cpu(fe->permissions) & ~FE_MAPPED_PERMS;
1466 
1467 	read_unlock(&sbi->s_cred_lock);
1468 
1469 	link_count = le16_to_cpu(fe->fileLinkCount);
1470 	if (!link_count) {
1471 		if (!hidden_inode) {
1472 			ret = -ESTALE;
1473 			goto out;
1474 		}
1475 		link_count = 1;
1476 	}
1477 	set_nlink(inode, link_count);
1478 
1479 	inode->i_size = le64_to_cpu(fe->informationLength);
1480 	iinfo->i_lenExtents = inode->i_size;
1481 
1482 	if (iinfo->i_efe == 0) {
1483 		inode->i_blocks = le64_to_cpu(fe->logicalBlocksRecorded) <<
1484 			(inode->i_sb->s_blocksize_bits - 9);
1485 
1486 		udf_disk_stamp_to_time(&inode->i_atime, fe->accessTime);
1487 		udf_disk_stamp_to_time(&inode->i_mtime, fe->modificationTime);
1488 		udf_disk_stamp_to_time(&inode->i_ctime, fe->attrTime);
1489 
1490 		iinfo->i_unique = le64_to_cpu(fe->uniqueID);
1491 		iinfo->i_lenEAttr = le32_to_cpu(fe->lengthExtendedAttr);
1492 		iinfo->i_lenAlloc = le32_to_cpu(fe->lengthAllocDescs);
1493 		iinfo->i_checkpoint = le32_to_cpu(fe->checkpoint);
1494 		iinfo->i_streamdir = 0;
1495 		iinfo->i_lenStreams = 0;
1496 	} else {
1497 		inode->i_blocks = le64_to_cpu(efe->logicalBlocksRecorded) <<
1498 		    (inode->i_sb->s_blocksize_bits - 9);
1499 
1500 		udf_disk_stamp_to_time(&inode->i_atime, efe->accessTime);
1501 		udf_disk_stamp_to_time(&inode->i_mtime, efe->modificationTime);
1502 		udf_disk_stamp_to_time(&iinfo->i_crtime, efe->createTime);
1503 		udf_disk_stamp_to_time(&inode->i_ctime, efe->attrTime);
1504 
1505 		iinfo->i_unique = le64_to_cpu(efe->uniqueID);
1506 		iinfo->i_lenEAttr = le32_to_cpu(efe->lengthExtendedAttr);
1507 		iinfo->i_lenAlloc = le32_to_cpu(efe->lengthAllocDescs);
1508 		iinfo->i_checkpoint = le32_to_cpu(efe->checkpoint);
1509 
1510 		/* Named streams */
1511 		iinfo->i_streamdir = (efe->streamDirectoryICB.extLength != 0);
1512 		iinfo->i_locStreamdir =
1513 			lelb_to_cpu(efe->streamDirectoryICB.extLocation);
1514 		iinfo->i_lenStreams = le64_to_cpu(efe->objectSize);
1515 		if (iinfo->i_lenStreams >= inode->i_size)
1516 			iinfo->i_lenStreams -= inode->i_size;
1517 		else
1518 			iinfo->i_lenStreams = 0;
1519 	}
1520 	inode->i_generation = iinfo->i_unique;
1521 
1522 	/*
1523 	 * Sanity check length of allocation descriptors and extended attrs to
1524 	 * avoid integer overflows
1525 	 */
1526 	if (iinfo->i_lenEAttr > bs || iinfo->i_lenAlloc > bs)
1527 		goto out;
1528 	/* Now do exact checks */
1529 	if (udf_file_entry_alloc_offset(inode) + iinfo->i_lenAlloc > bs)
1530 		goto out;
1531 	/* Sanity checks for files in ICB so that we don't get confused later */
1532 	if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) {
1533 		/*
1534 		 * For file in ICB data is stored in allocation descriptor
1535 		 * so sizes should match
1536 		 */
1537 		if (iinfo->i_lenAlloc != inode->i_size)
1538 			goto out;
1539 		/* File in ICB has to fit in there... */
1540 		if (inode->i_size > bs - udf_file_entry_alloc_offset(inode))
1541 			goto out;
1542 	}
1543 
1544 	switch (fe->icbTag.fileType) {
1545 	case ICBTAG_FILE_TYPE_DIRECTORY:
1546 		inode->i_op = &udf_dir_inode_operations;
1547 		inode->i_fop = &udf_dir_operations;
1548 		inode->i_mode |= S_IFDIR;
1549 		inc_nlink(inode);
1550 		break;
1551 	case ICBTAG_FILE_TYPE_REALTIME:
1552 	case ICBTAG_FILE_TYPE_REGULAR:
1553 	case ICBTAG_FILE_TYPE_UNDEF:
1554 	case ICBTAG_FILE_TYPE_VAT20:
1555 		if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB)
1556 			inode->i_data.a_ops = &udf_adinicb_aops;
1557 		else
1558 			inode->i_data.a_ops = &udf_aops;
1559 		inode->i_op = &udf_file_inode_operations;
1560 		inode->i_fop = &udf_file_operations;
1561 		inode->i_mode |= S_IFREG;
1562 		break;
1563 	case ICBTAG_FILE_TYPE_BLOCK:
1564 		inode->i_mode |= S_IFBLK;
1565 		break;
1566 	case ICBTAG_FILE_TYPE_CHAR:
1567 		inode->i_mode |= S_IFCHR;
1568 		break;
1569 	case ICBTAG_FILE_TYPE_FIFO:
1570 		init_special_inode(inode, inode->i_mode | S_IFIFO, 0);
1571 		break;
1572 	case ICBTAG_FILE_TYPE_SOCKET:
1573 		init_special_inode(inode, inode->i_mode | S_IFSOCK, 0);
1574 		break;
1575 	case ICBTAG_FILE_TYPE_SYMLINK:
1576 		inode->i_data.a_ops = &udf_symlink_aops;
1577 		inode->i_op = &udf_symlink_inode_operations;
1578 		inode_nohighmem(inode);
1579 		inode->i_mode = S_IFLNK | 0777;
1580 		break;
1581 	case ICBTAG_FILE_TYPE_MAIN:
1582 		udf_debug("METADATA FILE-----\n");
1583 		break;
1584 	case ICBTAG_FILE_TYPE_MIRROR:
1585 		udf_debug("METADATA MIRROR FILE-----\n");
1586 		break;
1587 	case ICBTAG_FILE_TYPE_BITMAP:
1588 		udf_debug("METADATA BITMAP FILE-----\n");
1589 		break;
1590 	default:
1591 		udf_err(inode->i_sb, "(ino %lu) failed unknown file type=%u\n",
1592 			inode->i_ino, fe->icbTag.fileType);
1593 		goto out;
1594 	}
1595 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
1596 		struct deviceSpec *dsea =
1597 			(struct deviceSpec *)udf_get_extendedattr(inode, 12, 1);
1598 		if (dsea) {
1599 			init_special_inode(inode, inode->i_mode,
1600 				MKDEV(le32_to_cpu(dsea->majorDeviceIdent),
1601 				      le32_to_cpu(dsea->minorDeviceIdent)));
1602 			/* Developer ID ??? */
1603 		} else
1604 			goto out;
1605 	}
1606 	ret = 0;
1607 out:
1608 	brelse(bh);
1609 	return ret;
1610 }
1611 
udf_alloc_i_data(struct inode * inode,size_t size)1612 static int udf_alloc_i_data(struct inode *inode, size_t size)
1613 {
1614 	struct udf_inode_info *iinfo = UDF_I(inode);
1615 	iinfo->i_data = kmalloc(size, GFP_KERNEL);
1616 	if (!iinfo->i_data)
1617 		return -ENOMEM;
1618 	return 0;
1619 }
1620 
udf_convert_permissions(struct fileEntry * fe)1621 static umode_t udf_convert_permissions(struct fileEntry *fe)
1622 {
1623 	umode_t mode;
1624 	uint32_t permissions;
1625 	uint32_t flags;
1626 
1627 	permissions = le32_to_cpu(fe->permissions);
1628 	flags = le16_to_cpu(fe->icbTag.flags);
1629 
1630 	mode =	((permissions) & 0007) |
1631 		((permissions >> 2) & 0070) |
1632 		((permissions >> 4) & 0700) |
1633 		((flags & ICBTAG_FLAG_SETUID) ? S_ISUID : 0) |
1634 		((flags & ICBTAG_FLAG_SETGID) ? S_ISGID : 0) |
1635 		((flags & ICBTAG_FLAG_STICKY) ? S_ISVTX : 0);
1636 
1637 	return mode;
1638 }
1639 
udf_update_extra_perms(struct inode * inode,umode_t mode)1640 void udf_update_extra_perms(struct inode *inode, umode_t mode)
1641 {
1642 	struct udf_inode_info *iinfo = UDF_I(inode);
1643 
1644 	/*
1645 	 * UDF 2.01 sec. 3.3.3.3 Note 2:
1646 	 * In Unix, delete permission tracks write
1647 	 */
1648 	iinfo->i_extraPerms &= ~FE_DELETE_PERMS;
1649 	if (mode & 0200)
1650 		iinfo->i_extraPerms |= FE_PERM_U_DELETE;
1651 	if (mode & 0020)
1652 		iinfo->i_extraPerms |= FE_PERM_G_DELETE;
1653 	if (mode & 0002)
1654 		iinfo->i_extraPerms |= FE_PERM_O_DELETE;
1655 }
1656 
udf_write_inode(struct inode * inode,struct writeback_control * wbc)1657 int udf_write_inode(struct inode *inode, struct writeback_control *wbc)
1658 {
1659 	return udf_update_inode(inode, wbc->sync_mode == WB_SYNC_ALL);
1660 }
1661 
udf_sync_inode(struct inode * inode)1662 static int udf_sync_inode(struct inode *inode)
1663 {
1664 	return udf_update_inode(inode, 1);
1665 }
1666 
udf_adjust_time(struct udf_inode_info * iinfo,struct timespec64 time)1667 static void udf_adjust_time(struct udf_inode_info *iinfo, struct timespec64 time)
1668 {
1669 	if (iinfo->i_crtime.tv_sec > time.tv_sec ||
1670 	    (iinfo->i_crtime.tv_sec == time.tv_sec &&
1671 	     iinfo->i_crtime.tv_nsec > time.tv_nsec))
1672 		iinfo->i_crtime = time;
1673 }
1674 
udf_update_inode(struct inode * inode,int do_sync)1675 static int udf_update_inode(struct inode *inode, int do_sync)
1676 {
1677 	struct buffer_head *bh = NULL;
1678 	struct fileEntry *fe;
1679 	struct extendedFileEntry *efe;
1680 	uint64_t lb_recorded;
1681 	uint32_t udfperms;
1682 	uint16_t icbflags;
1683 	uint16_t crclen;
1684 	int err = 0;
1685 	struct udf_sb_info *sbi = UDF_SB(inode->i_sb);
1686 	unsigned char blocksize_bits = inode->i_sb->s_blocksize_bits;
1687 	struct udf_inode_info *iinfo = UDF_I(inode);
1688 
1689 	bh = udf_tgetblk(inode->i_sb,
1690 			udf_get_lb_pblock(inode->i_sb, &iinfo->i_location, 0));
1691 	if (!bh) {
1692 		udf_debug("getblk failure\n");
1693 		return -EIO;
1694 	}
1695 
1696 	lock_buffer(bh);
1697 	memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1698 	fe = (struct fileEntry *)bh->b_data;
1699 	efe = (struct extendedFileEntry *)bh->b_data;
1700 
1701 	if (iinfo->i_use) {
1702 		struct unallocSpaceEntry *use =
1703 			(struct unallocSpaceEntry *)bh->b_data;
1704 
1705 		use->lengthAllocDescs = cpu_to_le32(iinfo->i_lenAlloc);
1706 		memcpy(bh->b_data + sizeof(struct unallocSpaceEntry),
1707 		       iinfo->i_data, inode->i_sb->s_blocksize -
1708 					sizeof(struct unallocSpaceEntry));
1709 		use->descTag.tagIdent = cpu_to_le16(TAG_IDENT_USE);
1710 		crclen = sizeof(struct unallocSpaceEntry);
1711 
1712 		goto finish;
1713 	}
1714 
1715 	if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_FORGET))
1716 		fe->uid = cpu_to_le32(UDF_INVALID_ID);
1717 	else
1718 		fe->uid = cpu_to_le32(i_uid_read(inode));
1719 
1720 	if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_FORGET))
1721 		fe->gid = cpu_to_le32(UDF_INVALID_ID);
1722 	else
1723 		fe->gid = cpu_to_le32(i_gid_read(inode));
1724 
1725 	udfperms = ((inode->i_mode & 0007)) |
1726 		   ((inode->i_mode & 0070) << 2) |
1727 		   ((inode->i_mode & 0700) << 4);
1728 
1729 	udfperms |= iinfo->i_extraPerms;
1730 	fe->permissions = cpu_to_le32(udfperms);
1731 
1732 	if (S_ISDIR(inode->i_mode) && inode->i_nlink > 0)
1733 		fe->fileLinkCount = cpu_to_le16(inode->i_nlink - 1);
1734 	else {
1735 		if (iinfo->i_hidden)
1736 			fe->fileLinkCount = cpu_to_le16(0);
1737 		else
1738 			fe->fileLinkCount = cpu_to_le16(inode->i_nlink);
1739 	}
1740 
1741 	fe->informationLength = cpu_to_le64(inode->i_size);
1742 
1743 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
1744 		struct regid *eid;
1745 		struct deviceSpec *dsea =
1746 			(struct deviceSpec *)udf_get_extendedattr(inode, 12, 1);
1747 		if (!dsea) {
1748 			dsea = (struct deviceSpec *)
1749 				udf_add_extendedattr(inode,
1750 						     sizeof(struct deviceSpec) +
1751 						     sizeof(struct regid), 12, 0x3);
1752 			dsea->attrType = cpu_to_le32(12);
1753 			dsea->attrSubtype = 1;
1754 			dsea->attrLength = cpu_to_le32(
1755 						sizeof(struct deviceSpec) +
1756 						sizeof(struct regid));
1757 			dsea->impUseLength = cpu_to_le32(sizeof(struct regid));
1758 		}
1759 		eid = (struct regid *)dsea->impUse;
1760 		memset(eid, 0, sizeof(*eid));
1761 		strcpy(eid->ident, UDF_ID_DEVELOPER);
1762 		eid->identSuffix[0] = UDF_OS_CLASS_UNIX;
1763 		eid->identSuffix[1] = UDF_OS_ID_LINUX;
1764 		dsea->majorDeviceIdent = cpu_to_le32(imajor(inode));
1765 		dsea->minorDeviceIdent = cpu_to_le32(iminor(inode));
1766 	}
1767 
1768 	if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB)
1769 		lb_recorded = 0; /* No extents => no blocks! */
1770 	else
1771 		lb_recorded =
1772 			(inode->i_blocks + (1 << (blocksize_bits - 9)) - 1) >>
1773 			(blocksize_bits - 9);
1774 
1775 	if (iinfo->i_efe == 0) {
1776 		memcpy(bh->b_data + sizeof(struct fileEntry),
1777 		       iinfo->i_data,
1778 		       inode->i_sb->s_blocksize - sizeof(struct fileEntry));
1779 		fe->logicalBlocksRecorded = cpu_to_le64(lb_recorded);
1780 
1781 		udf_time_to_disk_stamp(&fe->accessTime, inode->i_atime);
1782 		udf_time_to_disk_stamp(&fe->modificationTime, inode->i_mtime);
1783 		udf_time_to_disk_stamp(&fe->attrTime, inode->i_ctime);
1784 		memset(&(fe->impIdent), 0, sizeof(struct regid));
1785 		strcpy(fe->impIdent.ident, UDF_ID_DEVELOPER);
1786 		fe->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
1787 		fe->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
1788 		fe->uniqueID = cpu_to_le64(iinfo->i_unique);
1789 		fe->lengthExtendedAttr = cpu_to_le32(iinfo->i_lenEAttr);
1790 		fe->lengthAllocDescs = cpu_to_le32(iinfo->i_lenAlloc);
1791 		fe->checkpoint = cpu_to_le32(iinfo->i_checkpoint);
1792 		fe->descTag.tagIdent = cpu_to_le16(TAG_IDENT_FE);
1793 		crclen = sizeof(struct fileEntry);
1794 	} else {
1795 		memcpy(bh->b_data + sizeof(struct extendedFileEntry),
1796 		       iinfo->i_data,
1797 		       inode->i_sb->s_blocksize -
1798 					sizeof(struct extendedFileEntry));
1799 		efe->objectSize =
1800 			cpu_to_le64(inode->i_size + iinfo->i_lenStreams);
1801 		efe->logicalBlocksRecorded = cpu_to_le64(lb_recorded);
1802 
1803 		if (iinfo->i_streamdir) {
1804 			struct long_ad *icb_lad = &efe->streamDirectoryICB;
1805 
1806 			icb_lad->extLocation =
1807 				cpu_to_lelb(iinfo->i_locStreamdir);
1808 			icb_lad->extLength =
1809 				cpu_to_le32(inode->i_sb->s_blocksize);
1810 		}
1811 
1812 		udf_adjust_time(iinfo, inode->i_atime);
1813 		udf_adjust_time(iinfo, inode->i_mtime);
1814 		udf_adjust_time(iinfo, inode->i_ctime);
1815 
1816 		udf_time_to_disk_stamp(&efe->accessTime, inode->i_atime);
1817 		udf_time_to_disk_stamp(&efe->modificationTime, inode->i_mtime);
1818 		udf_time_to_disk_stamp(&efe->createTime, iinfo->i_crtime);
1819 		udf_time_to_disk_stamp(&efe->attrTime, inode->i_ctime);
1820 
1821 		memset(&(efe->impIdent), 0, sizeof(efe->impIdent));
1822 		strcpy(efe->impIdent.ident, UDF_ID_DEVELOPER);
1823 		efe->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
1824 		efe->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
1825 		efe->uniqueID = cpu_to_le64(iinfo->i_unique);
1826 		efe->lengthExtendedAttr = cpu_to_le32(iinfo->i_lenEAttr);
1827 		efe->lengthAllocDescs = cpu_to_le32(iinfo->i_lenAlloc);
1828 		efe->checkpoint = cpu_to_le32(iinfo->i_checkpoint);
1829 		efe->descTag.tagIdent = cpu_to_le16(TAG_IDENT_EFE);
1830 		crclen = sizeof(struct extendedFileEntry);
1831 	}
1832 
1833 finish:
1834 	if (iinfo->i_strat4096) {
1835 		fe->icbTag.strategyType = cpu_to_le16(4096);
1836 		fe->icbTag.strategyParameter = cpu_to_le16(1);
1837 		fe->icbTag.numEntries = cpu_to_le16(2);
1838 	} else {
1839 		fe->icbTag.strategyType = cpu_to_le16(4);
1840 		fe->icbTag.numEntries = cpu_to_le16(1);
1841 	}
1842 
1843 	if (iinfo->i_use)
1844 		fe->icbTag.fileType = ICBTAG_FILE_TYPE_USE;
1845 	else if (S_ISDIR(inode->i_mode))
1846 		fe->icbTag.fileType = ICBTAG_FILE_TYPE_DIRECTORY;
1847 	else if (S_ISREG(inode->i_mode))
1848 		fe->icbTag.fileType = ICBTAG_FILE_TYPE_REGULAR;
1849 	else if (S_ISLNK(inode->i_mode))
1850 		fe->icbTag.fileType = ICBTAG_FILE_TYPE_SYMLINK;
1851 	else if (S_ISBLK(inode->i_mode))
1852 		fe->icbTag.fileType = ICBTAG_FILE_TYPE_BLOCK;
1853 	else if (S_ISCHR(inode->i_mode))
1854 		fe->icbTag.fileType = ICBTAG_FILE_TYPE_CHAR;
1855 	else if (S_ISFIFO(inode->i_mode))
1856 		fe->icbTag.fileType = ICBTAG_FILE_TYPE_FIFO;
1857 	else if (S_ISSOCK(inode->i_mode))
1858 		fe->icbTag.fileType = ICBTAG_FILE_TYPE_SOCKET;
1859 
1860 	icbflags =	iinfo->i_alloc_type |
1861 			((inode->i_mode & S_ISUID) ? ICBTAG_FLAG_SETUID : 0) |
1862 			((inode->i_mode & S_ISGID) ? ICBTAG_FLAG_SETGID : 0) |
1863 			((inode->i_mode & S_ISVTX) ? ICBTAG_FLAG_STICKY : 0) |
1864 			(le16_to_cpu(fe->icbTag.flags) &
1865 				~(ICBTAG_FLAG_AD_MASK | ICBTAG_FLAG_SETUID |
1866 				ICBTAG_FLAG_SETGID | ICBTAG_FLAG_STICKY));
1867 
1868 	fe->icbTag.flags = cpu_to_le16(icbflags);
1869 	if (sbi->s_udfrev >= 0x0200)
1870 		fe->descTag.descVersion = cpu_to_le16(3);
1871 	else
1872 		fe->descTag.descVersion = cpu_to_le16(2);
1873 	fe->descTag.tagSerialNum = cpu_to_le16(sbi->s_serial_number);
1874 	fe->descTag.tagLocation = cpu_to_le32(
1875 					iinfo->i_location.logicalBlockNum);
1876 	crclen += iinfo->i_lenEAttr + iinfo->i_lenAlloc - sizeof(struct tag);
1877 	fe->descTag.descCRCLength = cpu_to_le16(crclen);
1878 	fe->descTag.descCRC = cpu_to_le16(crc_itu_t(0, (char *)fe + sizeof(struct tag),
1879 						  crclen));
1880 	fe->descTag.tagChecksum = udf_tag_checksum(&fe->descTag);
1881 
1882 	set_buffer_uptodate(bh);
1883 	unlock_buffer(bh);
1884 
1885 	/* write the data blocks */
1886 	mark_buffer_dirty(bh);
1887 	if (do_sync) {
1888 		sync_dirty_buffer(bh);
1889 		if (buffer_write_io_error(bh)) {
1890 			udf_warn(inode->i_sb, "IO error syncing udf inode [%08lx]\n",
1891 				 inode->i_ino);
1892 			err = -EIO;
1893 		}
1894 	}
1895 	brelse(bh);
1896 
1897 	return err;
1898 }
1899 
__udf_iget(struct super_block * sb,struct kernel_lb_addr * ino,bool hidden_inode)1900 struct inode *__udf_iget(struct super_block *sb, struct kernel_lb_addr *ino,
1901 			 bool hidden_inode)
1902 {
1903 	unsigned long block = udf_get_lb_pblock(sb, ino, 0);
1904 	struct inode *inode = iget_locked(sb, block);
1905 	int err;
1906 
1907 	if (!inode)
1908 		return ERR_PTR(-ENOMEM);
1909 
1910 	if (!(inode->i_state & I_NEW)) {
1911 		if (UDF_I(inode)->i_hidden != hidden_inode) {
1912 			iput(inode);
1913 			return ERR_PTR(-EFSCORRUPTED);
1914 		}
1915 		return inode;
1916 	}
1917 
1918 	memcpy(&UDF_I(inode)->i_location, ino, sizeof(struct kernel_lb_addr));
1919 	err = udf_read_inode(inode, hidden_inode);
1920 	if (err < 0) {
1921 		iget_failed(inode);
1922 		return ERR_PTR(err);
1923 	}
1924 	unlock_new_inode(inode);
1925 
1926 	return inode;
1927 }
1928 
udf_setup_indirect_aext(struct inode * inode,udf_pblk_t block,struct extent_position * epos)1929 int udf_setup_indirect_aext(struct inode *inode, udf_pblk_t block,
1930 			    struct extent_position *epos)
1931 {
1932 	struct super_block *sb = inode->i_sb;
1933 	struct buffer_head *bh;
1934 	struct allocExtDesc *aed;
1935 	struct extent_position nepos;
1936 	struct kernel_lb_addr neloc;
1937 	int ver, adsize;
1938 
1939 	if (UDF_I(inode)->i_alloc_type == ICBTAG_FLAG_AD_SHORT)
1940 		adsize = sizeof(struct short_ad);
1941 	else if (UDF_I(inode)->i_alloc_type == ICBTAG_FLAG_AD_LONG)
1942 		adsize = sizeof(struct long_ad);
1943 	else
1944 		return -EIO;
1945 
1946 	neloc.logicalBlockNum = block;
1947 	neloc.partitionReferenceNum = epos->block.partitionReferenceNum;
1948 
1949 	bh = udf_tgetblk(sb, udf_get_lb_pblock(sb, &neloc, 0));
1950 	if (!bh)
1951 		return -EIO;
1952 	lock_buffer(bh);
1953 	memset(bh->b_data, 0x00, sb->s_blocksize);
1954 	set_buffer_uptodate(bh);
1955 	unlock_buffer(bh);
1956 	mark_buffer_dirty_inode(bh, inode);
1957 
1958 	aed = (struct allocExtDesc *)(bh->b_data);
1959 	if (!UDF_QUERY_FLAG(sb, UDF_FLAG_STRICT)) {
1960 		aed->previousAllocExtLocation =
1961 				cpu_to_le32(epos->block.logicalBlockNum);
1962 	}
1963 	aed->lengthAllocDescs = cpu_to_le32(0);
1964 	if (UDF_SB(sb)->s_udfrev >= 0x0200)
1965 		ver = 3;
1966 	else
1967 		ver = 2;
1968 	udf_new_tag(bh->b_data, TAG_IDENT_AED, ver, 1, block,
1969 		    sizeof(struct tag));
1970 
1971 	nepos.block = neloc;
1972 	nepos.offset = sizeof(struct allocExtDesc);
1973 	nepos.bh = bh;
1974 
1975 	/*
1976 	 * Do we have to copy current last extent to make space for indirect
1977 	 * one?
1978 	 */
1979 	if (epos->offset + adsize > sb->s_blocksize) {
1980 		struct kernel_lb_addr cp_loc;
1981 		uint32_t cp_len;
1982 		int cp_type;
1983 
1984 		epos->offset -= adsize;
1985 		cp_type = udf_current_aext(inode, epos, &cp_loc, &cp_len, 0);
1986 		cp_len |= ((uint32_t)cp_type) << 30;
1987 
1988 		__udf_add_aext(inode, &nepos, &cp_loc, cp_len, 1);
1989 		udf_write_aext(inode, epos, &nepos.block,
1990 			       sb->s_blocksize | EXT_NEXT_EXTENT_ALLOCDESCS, 0);
1991 	} else {
1992 		__udf_add_aext(inode, epos, &nepos.block,
1993 			       sb->s_blocksize | EXT_NEXT_EXTENT_ALLOCDESCS, 0);
1994 	}
1995 
1996 	brelse(epos->bh);
1997 	*epos = nepos;
1998 
1999 	return 0;
2000 }
2001 
2002 /*
2003  * Append extent at the given position - should be the first free one in inode
2004  * / indirect extent. This function assumes there is enough space in the inode
2005  * or indirect extent. Use udf_add_aext() if you didn't check for this before.
2006  */
__udf_add_aext(struct inode * inode,struct extent_position * epos,struct kernel_lb_addr * eloc,uint32_t elen,int inc)2007 int __udf_add_aext(struct inode *inode, struct extent_position *epos,
2008 		   struct kernel_lb_addr *eloc, uint32_t elen, int inc)
2009 {
2010 	struct udf_inode_info *iinfo = UDF_I(inode);
2011 	struct allocExtDesc *aed;
2012 	int adsize;
2013 
2014 	if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT)
2015 		adsize = sizeof(struct short_ad);
2016 	else if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG)
2017 		adsize = sizeof(struct long_ad);
2018 	else
2019 		return -EIO;
2020 
2021 	if (!epos->bh) {
2022 		WARN_ON(iinfo->i_lenAlloc !=
2023 			epos->offset - udf_file_entry_alloc_offset(inode));
2024 	} else {
2025 		aed = (struct allocExtDesc *)epos->bh->b_data;
2026 		WARN_ON(le32_to_cpu(aed->lengthAllocDescs) !=
2027 			epos->offset - sizeof(struct allocExtDesc));
2028 		WARN_ON(epos->offset + adsize > inode->i_sb->s_blocksize);
2029 	}
2030 
2031 	udf_write_aext(inode, epos, eloc, elen, inc);
2032 
2033 	if (!epos->bh) {
2034 		iinfo->i_lenAlloc += adsize;
2035 		mark_inode_dirty(inode);
2036 	} else {
2037 		aed = (struct allocExtDesc *)epos->bh->b_data;
2038 		le32_add_cpu(&aed->lengthAllocDescs, adsize);
2039 		if (!UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_STRICT) ||
2040 				UDF_SB(inode->i_sb)->s_udfrev >= 0x0201)
2041 			udf_update_tag(epos->bh->b_data,
2042 					epos->offset + (inc ? 0 : adsize));
2043 		else
2044 			udf_update_tag(epos->bh->b_data,
2045 					sizeof(struct allocExtDesc));
2046 		mark_buffer_dirty_inode(epos->bh, inode);
2047 	}
2048 
2049 	return 0;
2050 }
2051 
2052 /*
2053  * Append extent at given position - should be the first free one in inode
2054  * / indirect extent. Takes care of allocating and linking indirect blocks.
2055  */
udf_add_aext(struct inode * inode,struct extent_position * epos,struct kernel_lb_addr * eloc,uint32_t elen,int inc)2056 int udf_add_aext(struct inode *inode, struct extent_position *epos,
2057 		 struct kernel_lb_addr *eloc, uint32_t elen, int inc)
2058 {
2059 	int adsize;
2060 	struct super_block *sb = inode->i_sb;
2061 
2062 	if (UDF_I(inode)->i_alloc_type == ICBTAG_FLAG_AD_SHORT)
2063 		adsize = sizeof(struct short_ad);
2064 	else if (UDF_I(inode)->i_alloc_type == ICBTAG_FLAG_AD_LONG)
2065 		adsize = sizeof(struct long_ad);
2066 	else
2067 		return -EIO;
2068 
2069 	if (epos->offset + (2 * adsize) > sb->s_blocksize) {
2070 		int err;
2071 		udf_pblk_t new_block;
2072 
2073 		new_block = udf_new_block(sb, NULL,
2074 					  epos->block.partitionReferenceNum,
2075 					  epos->block.logicalBlockNum, &err);
2076 		if (!new_block)
2077 			return -ENOSPC;
2078 
2079 		err = udf_setup_indirect_aext(inode, new_block, epos);
2080 		if (err)
2081 			return err;
2082 	}
2083 
2084 	return __udf_add_aext(inode, epos, eloc, elen, inc);
2085 }
2086 
udf_write_aext(struct inode * inode,struct extent_position * epos,struct kernel_lb_addr * eloc,uint32_t elen,int inc)2087 void udf_write_aext(struct inode *inode, struct extent_position *epos,
2088 		    struct kernel_lb_addr *eloc, uint32_t elen, int inc)
2089 {
2090 	int adsize;
2091 	uint8_t *ptr;
2092 	struct short_ad *sad;
2093 	struct long_ad *lad;
2094 	struct udf_inode_info *iinfo = UDF_I(inode);
2095 
2096 	if (!epos->bh)
2097 		ptr = iinfo->i_data + epos->offset -
2098 			udf_file_entry_alloc_offset(inode) +
2099 			iinfo->i_lenEAttr;
2100 	else
2101 		ptr = epos->bh->b_data + epos->offset;
2102 
2103 	switch (iinfo->i_alloc_type) {
2104 	case ICBTAG_FLAG_AD_SHORT:
2105 		sad = (struct short_ad *)ptr;
2106 		sad->extLength = cpu_to_le32(elen);
2107 		sad->extPosition = cpu_to_le32(eloc->logicalBlockNum);
2108 		adsize = sizeof(struct short_ad);
2109 		break;
2110 	case ICBTAG_FLAG_AD_LONG:
2111 		lad = (struct long_ad *)ptr;
2112 		lad->extLength = cpu_to_le32(elen);
2113 		lad->extLocation = cpu_to_lelb(*eloc);
2114 		memset(lad->impUse, 0x00, sizeof(lad->impUse));
2115 		adsize = sizeof(struct long_ad);
2116 		break;
2117 	default:
2118 		return;
2119 	}
2120 
2121 	if (epos->bh) {
2122 		if (!UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_STRICT) ||
2123 		    UDF_SB(inode->i_sb)->s_udfrev >= 0x0201) {
2124 			struct allocExtDesc *aed =
2125 				(struct allocExtDesc *)epos->bh->b_data;
2126 			udf_update_tag(epos->bh->b_data,
2127 				       le32_to_cpu(aed->lengthAllocDescs) +
2128 				       sizeof(struct allocExtDesc));
2129 		}
2130 		mark_buffer_dirty_inode(epos->bh, inode);
2131 	} else {
2132 		mark_inode_dirty(inode);
2133 	}
2134 
2135 	if (inc)
2136 		epos->offset += adsize;
2137 }
2138 
2139 /*
2140  * Only 1 indirect extent in a row really makes sense but allow upto 16 in case
2141  * someone does some weird stuff.
2142  */
2143 #define UDF_MAX_INDIR_EXTS 16
2144 
udf_next_aext(struct inode * inode,struct extent_position * epos,struct kernel_lb_addr * eloc,uint32_t * elen,int inc)2145 int8_t udf_next_aext(struct inode *inode, struct extent_position *epos,
2146 		     struct kernel_lb_addr *eloc, uint32_t *elen, int inc)
2147 {
2148 	int8_t etype;
2149 	unsigned int indirections = 0;
2150 
2151 	while ((etype = udf_current_aext(inode, epos, eloc, elen, inc)) ==
2152 	       (EXT_NEXT_EXTENT_ALLOCDESCS >> 30)) {
2153 		udf_pblk_t block;
2154 
2155 		if (++indirections > UDF_MAX_INDIR_EXTS) {
2156 			udf_err(inode->i_sb,
2157 				"too many indirect extents in inode %lu\n",
2158 				inode->i_ino);
2159 			return -1;
2160 		}
2161 
2162 		epos->block = *eloc;
2163 		epos->offset = sizeof(struct allocExtDesc);
2164 		brelse(epos->bh);
2165 		block = udf_get_lb_pblock(inode->i_sb, &epos->block, 0);
2166 		epos->bh = udf_tread(inode->i_sb, block);
2167 		if (!epos->bh) {
2168 			udf_debug("reading block %u failed!\n", block);
2169 			return -1;
2170 		}
2171 	}
2172 
2173 	return etype;
2174 }
2175 
udf_current_aext(struct inode * inode,struct extent_position * epos,struct kernel_lb_addr * eloc,uint32_t * elen,int inc)2176 int8_t udf_current_aext(struct inode *inode, struct extent_position *epos,
2177 			struct kernel_lb_addr *eloc, uint32_t *elen, int inc)
2178 {
2179 	int alen;
2180 	int8_t etype;
2181 	uint8_t *ptr;
2182 	struct short_ad *sad;
2183 	struct long_ad *lad;
2184 	struct udf_inode_info *iinfo = UDF_I(inode);
2185 
2186 	if (!epos->bh) {
2187 		if (!epos->offset)
2188 			epos->offset = udf_file_entry_alloc_offset(inode);
2189 		ptr = iinfo->i_data + epos->offset -
2190 			udf_file_entry_alloc_offset(inode) +
2191 			iinfo->i_lenEAttr;
2192 		alen = udf_file_entry_alloc_offset(inode) +
2193 							iinfo->i_lenAlloc;
2194 	} else {
2195 		if (!epos->offset)
2196 			epos->offset = sizeof(struct allocExtDesc);
2197 		ptr = epos->bh->b_data + epos->offset;
2198 		alen = sizeof(struct allocExtDesc) +
2199 			le32_to_cpu(((struct allocExtDesc *)epos->bh->b_data)->
2200 							lengthAllocDescs);
2201 	}
2202 
2203 	switch (iinfo->i_alloc_type) {
2204 	case ICBTAG_FLAG_AD_SHORT:
2205 		sad = udf_get_fileshortad(ptr, alen, &epos->offset, inc);
2206 		if (!sad)
2207 			return -1;
2208 		etype = le32_to_cpu(sad->extLength) >> 30;
2209 		eloc->logicalBlockNum = le32_to_cpu(sad->extPosition);
2210 		eloc->partitionReferenceNum =
2211 				iinfo->i_location.partitionReferenceNum;
2212 		*elen = le32_to_cpu(sad->extLength) & UDF_EXTENT_LENGTH_MASK;
2213 		break;
2214 	case ICBTAG_FLAG_AD_LONG:
2215 		lad = udf_get_filelongad(ptr, alen, &epos->offset, inc);
2216 		if (!lad)
2217 			return -1;
2218 		etype = le32_to_cpu(lad->extLength) >> 30;
2219 		*eloc = lelb_to_cpu(lad->extLocation);
2220 		*elen = le32_to_cpu(lad->extLength) & UDF_EXTENT_LENGTH_MASK;
2221 		break;
2222 	default:
2223 		udf_debug("alloc_type = %u unsupported\n", iinfo->i_alloc_type);
2224 		return -1;
2225 	}
2226 
2227 	return etype;
2228 }
2229 
udf_insert_aext(struct inode * inode,struct extent_position epos,struct kernel_lb_addr neloc,uint32_t nelen)2230 static int udf_insert_aext(struct inode *inode, struct extent_position epos,
2231 			   struct kernel_lb_addr neloc, uint32_t nelen)
2232 {
2233 	struct kernel_lb_addr oeloc;
2234 	uint32_t oelen;
2235 	int8_t etype;
2236 	int err;
2237 
2238 	if (epos.bh)
2239 		get_bh(epos.bh);
2240 
2241 	while ((etype = udf_next_aext(inode, &epos, &oeloc, &oelen, 0)) != -1) {
2242 		udf_write_aext(inode, &epos, &neloc, nelen, 1);
2243 		neloc = oeloc;
2244 		nelen = (etype << 30) | oelen;
2245 	}
2246 	err = udf_add_aext(inode, &epos, &neloc, nelen, 1);
2247 	brelse(epos.bh);
2248 
2249 	return err;
2250 }
2251 
udf_delete_aext(struct inode * inode,struct extent_position epos)2252 int8_t udf_delete_aext(struct inode *inode, struct extent_position epos)
2253 {
2254 	struct extent_position oepos;
2255 	int adsize;
2256 	int8_t etype;
2257 	struct allocExtDesc *aed;
2258 	struct udf_inode_info *iinfo;
2259 	struct kernel_lb_addr eloc;
2260 	uint32_t elen;
2261 
2262 	if (epos.bh) {
2263 		get_bh(epos.bh);
2264 		get_bh(epos.bh);
2265 	}
2266 
2267 	iinfo = UDF_I(inode);
2268 	if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT)
2269 		adsize = sizeof(struct short_ad);
2270 	else if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG)
2271 		adsize = sizeof(struct long_ad);
2272 	else
2273 		adsize = 0;
2274 
2275 	oepos = epos;
2276 	if (udf_next_aext(inode, &epos, &eloc, &elen, 1) == -1)
2277 		return -1;
2278 
2279 	while ((etype = udf_next_aext(inode, &epos, &eloc, &elen, 1)) != -1) {
2280 		udf_write_aext(inode, &oepos, &eloc, (etype << 30) | elen, 1);
2281 		if (oepos.bh != epos.bh) {
2282 			oepos.block = epos.block;
2283 			brelse(oepos.bh);
2284 			get_bh(epos.bh);
2285 			oepos.bh = epos.bh;
2286 			oepos.offset = epos.offset - adsize;
2287 		}
2288 	}
2289 	memset(&eloc, 0x00, sizeof(struct kernel_lb_addr));
2290 	elen = 0;
2291 
2292 	if (epos.bh != oepos.bh) {
2293 		udf_free_blocks(inode->i_sb, inode, &epos.block, 0, 1);
2294 		udf_write_aext(inode, &oepos, &eloc, elen, 1);
2295 		udf_write_aext(inode, &oepos, &eloc, elen, 1);
2296 		if (!oepos.bh) {
2297 			iinfo->i_lenAlloc -= (adsize * 2);
2298 			mark_inode_dirty(inode);
2299 		} else {
2300 			aed = (struct allocExtDesc *)oepos.bh->b_data;
2301 			le32_add_cpu(&aed->lengthAllocDescs, -(2 * adsize));
2302 			if (!UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_STRICT) ||
2303 			    UDF_SB(inode->i_sb)->s_udfrev >= 0x0201)
2304 				udf_update_tag(oepos.bh->b_data,
2305 						oepos.offset - (2 * adsize));
2306 			else
2307 				udf_update_tag(oepos.bh->b_data,
2308 						sizeof(struct allocExtDesc));
2309 			mark_buffer_dirty_inode(oepos.bh, inode);
2310 		}
2311 	} else {
2312 		udf_write_aext(inode, &oepos, &eloc, elen, 1);
2313 		if (!oepos.bh) {
2314 			iinfo->i_lenAlloc -= adsize;
2315 			mark_inode_dirty(inode);
2316 		} else {
2317 			aed = (struct allocExtDesc *)oepos.bh->b_data;
2318 			le32_add_cpu(&aed->lengthAllocDescs, -adsize);
2319 			if (!UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_STRICT) ||
2320 			    UDF_SB(inode->i_sb)->s_udfrev >= 0x0201)
2321 				udf_update_tag(oepos.bh->b_data,
2322 						epos.offset - adsize);
2323 			else
2324 				udf_update_tag(oepos.bh->b_data,
2325 						sizeof(struct allocExtDesc));
2326 			mark_buffer_dirty_inode(oepos.bh, inode);
2327 		}
2328 	}
2329 
2330 	brelse(epos.bh);
2331 	brelse(oepos.bh);
2332 
2333 	return (elen >> 30);
2334 }
2335 
inode_bmap(struct inode * inode,sector_t block,struct extent_position * pos,struct kernel_lb_addr * eloc,uint32_t * elen,sector_t * offset)2336 int8_t inode_bmap(struct inode *inode, sector_t block,
2337 		  struct extent_position *pos, struct kernel_lb_addr *eloc,
2338 		  uint32_t *elen, sector_t *offset)
2339 {
2340 	unsigned char blocksize_bits = inode->i_sb->s_blocksize_bits;
2341 	loff_t lbcount = 0, bcount = (loff_t) block << blocksize_bits;
2342 	int8_t etype;
2343 	struct udf_inode_info *iinfo;
2344 
2345 	iinfo = UDF_I(inode);
2346 	if (!udf_read_extent_cache(inode, bcount, &lbcount, pos)) {
2347 		pos->offset = 0;
2348 		pos->block = iinfo->i_location;
2349 		pos->bh = NULL;
2350 	}
2351 	*elen = 0;
2352 	do {
2353 		etype = udf_next_aext(inode, pos, eloc, elen, 1);
2354 		if (etype == -1) {
2355 			*offset = (bcount - lbcount) >> blocksize_bits;
2356 			iinfo->i_lenExtents = lbcount;
2357 			return -1;
2358 		}
2359 		lbcount += *elen;
2360 	} while (lbcount <= bcount);
2361 	/* update extent cache */
2362 	udf_update_extent_cache(inode, lbcount - *elen, pos);
2363 	*offset = (bcount + *elen - lbcount) >> blocksize_bits;
2364 
2365 	return etype;
2366 }
2367 
udf_block_map(struct inode * inode,sector_t block)2368 udf_pblk_t udf_block_map(struct inode *inode, sector_t block)
2369 {
2370 	struct kernel_lb_addr eloc;
2371 	uint32_t elen;
2372 	sector_t offset;
2373 	struct extent_position epos = {};
2374 	udf_pblk_t ret;
2375 
2376 	down_read(&UDF_I(inode)->i_data_sem);
2377 
2378 	if (inode_bmap(inode, block, &epos, &eloc, &elen, &offset) ==
2379 						(EXT_RECORDED_ALLOCATED >> 30))
2380 		ret = udf_get_lb_pblock(inode->i_sb, &eloc, offset);
2381 	else
2382 		ret = 0;
2383 
2384 	up_read(&UDF_I(inode)->i_data_sem);
2385 	brelse(epos.bh);
2386 
2387 	if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_VARCONV))
2388 		return udf_fixed_to_variable(ret);
2389 	else
2390 		return ret;
2391 }
2392