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