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