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