xref: /haiku/src/add-ons/kernel/file_systems/btrfs/Volume.cpp (revision bd2dab1c73271f939d8907ea77d2e5937ace802e)
1 /*
2  * Copyright 2011, Jérôme Duval, korli@users.berlios.de.
3  * Copyright 2008-2010, Axel Dörfler, axeld@pinc-software.de.
4  * This file may be used under the terms of the MIT License.
5  */
6 
7 
8 //! Superblock, mounting, etc.
9 
10 
11 #include "Volume.h"
12 #include "BTree.h"
13 #include "CachedBlock.h"
14 #include "Chunk.h"
15 #include "Inode.h"
16 
17 
18 //#define TRACE_BTRFS
19 #ifdef TRACE_BTRFS
20 #	define TRACE(x...) dprintf("\33[34mbtrfs:\33[0m " x)
21 #else
22 #	define TRACE(x...) ;
23 #endif
24 #	define ERROR(x...) dprintf("\33[34mbtrfs:\33[0m " x)
25 
26 
27 class DeviceOpener {
28 public:
29 								DeviceOpener(int fd, int mode);
30 								DeviceOpener(const char* device, int mode);
31 								~DeviceOpener();
32 
33 			int					Open(const char* device, int mode);
34 			int					Open(int fd, int mode);
35 			void*				InitCache(off_t numBlocks, uint32 blockSize);
36 			void				RemoveCache(bool allowWrites);
37 
38 			void				Keep();
39 
40 			int					Device() const { return fDevice; }
41 			int					Mode() const { return fMode; }
42 			bool				IsReadOnly() const
43 									{ return _IsReadOnly(fMode); }
44 
45 			status_t			GetSize(off_t* _size, uint32* _blockSize = NULL);
46 
47 private:
48 	static	bool				_IsReadOnly(int mode)
49 									{ return (mode & O_RWMASK) == O_RDONLY;}
50 	static	bool				_IsReadWrite(int mode)
51 									{ return (mode & O_RWMASK) == O_RDWR;}
52 
53 			int					fDevice;
54 			int					fMode;
55 			void*				fBlockCache;
56 };
57 
58 
59 DeviceOpener::DeviceOpener(const char* device, int mode)
60 	:
61 	fBlockCache(NULL)
62 {
63 	Open(device, mode);
64 }
65 
66 
67 DeviceOpener::DeviceOpener(int fd, int mode)
68 	:
69 	fBlockCache(NULL)
70 {
71 	Open(fd, mode);
72 }
73 
74 
75 DeviceOpener::~DeviceOpener()
76 {
77 	if (fDevice >= 0) {
78 		RemoveCache(false);
79 		close(fDevice);
80 	}
81 }
82 
83 
84 int
85 DeviceOpener::Open(const char* device, int mode)
86 {
87 	fDevice = open(device, mode | O_NOCACHE);
88 	if (fDevice < 0)
89 		fDevice = errno;
90 
91 	if (fDevice < 0 && _IsReadWrite(mode)) {
92 		// try again to open read-only (don't rely on a specific error code)
93 		return Open(device, O_RDONLY | O_NOCACHE);
94 	}
95 
96 	if (fDevice >= 0) {
97 		// opening succeeded
98 		fMode = mode;
99 		if (_IsReadWrite(mode)) {
100 			// check out if the device really allows for read/write access
101 			device_geometry geometry;
102 			if (!ioctl(fDevice, B_GET_GEOMETRY, &geometry)) {
103 				if (geometry.read_only) {
104 					// reopen device read-only
105 					close(fDevice);
106 					return Open(device, O_RDONLY | O_NOCACHE);
107 				}
108 			}
109 		}
110 	}
111 
112 	return fDevice;
113 }
114 
115 
116 int
117 DeviceOpener::Open(int fd, int mode)
118 {
119 	fDevice = dup(fd);
120 	if (fDevice < 0)
121 		return errno;
122 
123 	fMode = mode;
124 
125 	return fDevice;
126 }
127 
128 
129 void*
130 DeviceOpener::InitCache(off_t numBlocks, uint32 blockSize)
131 {
132 	return fBlockCache = block_cache_create(fDevice, numBlocks, blockSize,
133 		IsReadOnly());
134 }
135 
136 
137 void
138 DeviceOpener::RemoveCache(bool allowWrites)
139 {
140 	if (fBlockCache == NULL)
141 		return;
142 
143 	block_cache_delete(fBlockCache, allowWrites);
144 	fBlockCache = NULL;
145 }
146 
147 
148 void
149 DeviceOpener::Keep()
150 {
151 	fDevice = -1;
152 }
153 
154 
155 /*!	Returns the size of the device in bytes. It uses B_GET_GEOMETRY
156 	to compute the size, or fstat() if that failed.
157 */
158 status_t
159 DeviceOpener::GetSize(off_t* _size, uint32* _blockSize)
160 {
161 	device_geometry geometry;
162 	if (ioctl(fDevice, B_GET_GEOMETRY, &geometry) < 0) {
163 		// maybe it's just a file
164 		struct stat stat;
165 		if (fstat(fDevice, &stat) < 0)
166 			return B_ERROR;
167 
168 		if (_size)
169 			*_size = stat.st_size;
170 		if (_blockSize)	// that shouldn't cause us any problems
171 			*_blockSize = 512;
172 
173 		return B_OK;
174 	}
175 
176 	if (_size) {
177 		*_size = 1ULL * geometry.head_count * geometry.cylinder_count
178 			* geometry.sectors_per_track * geometry.bytes_per_sector;
179 	}
180 	if (_blockSize)
181 		*_blockSize = geometry.bytes_per_sector;
182 
183 	return B_OK;
184 }
185 
186 
187 //	#pragma mark -
188 
189 
190 bool
191 btrfs_super_block::IsValid()
192 {
193 	// TODO: check some more values!
194 	if (strncmp(magic, BTRFS_SUPER_BLOCK_MAGIC, sizeof(magic)) != 0)
195 		return false;
196 
197 	return true;
198 }
199 
200 
201 //	#pragma mark -
202 
203 
204 Volume::Volume(fs_volume* volume)
205 	:
206 	fFSVolume(volume),
207 	fFlags(0),
208 	fChunk(NULL),
209 	fChunkTree(NULL)
210 {
211 	mutex_init(&fLock, "btrfs volume");
212 }
213 
214 
215 Volume::~Volume()
216 {
217 	TRACE("Volume destructor.\n");
218 }
219 
220 
221 bool
222 Volume::IsValidSuperBlock()
223 {
224 	return fSuperBlock.IsValid();
225 }
226 
227 
228 const char*
229 Volume::Name() const
230 {
231 	if (fSuperBlock.label[0])
232 		return fSuperBlock.label;
233 
234 	return fName;
235 }
236 
237 
238 status_t
239 Volume::Mount(const char* deviceName, uint32 flags)
240 {
241 	flags |= B_MOUNT_READ_ONLY;
242 		// we only support read-only for now
243 
244 	if ((flags & B_MOUNT_READ_ONLY) != 0) {
245 		TRACE("Volume::Mount(): Read only\n");
246 	} else {
247 		TRACE("Volume::Mount(): Read write\n");
248 	}
249 
250 	DeviceOpener opener(deviceName, (flags & B_MOUNT_READ_ONLY) != 0
251 		? O_RDONLY : O_RDWR);
252 	fDevice = opener.Device();
253 	if (fDevice < B_OK) {
254 		ERROR("Volume::Mount(): couldn't open device\n");
255 		return fDevice;
256 	}
257 
258 	if (opener.IsReadOnly())
259 		fFlags |= VOLUME_READ_ONLY;
260 
261 	// read the superblock
262 	status_t status = Identify(fDevice, &fSuperBlock);
263 	if (status != B_OK) {
264 		ERROR("Volume::Mount(): Identify() failed\n");
265 		return status;
266 	}
267 
268 	fBlockSize = fSuperBlock.BlockSize();
269 	fSectorSize = fSuperBlock.SectorSize();
270 	TRACE("block size %" B_PRIu32 "\n", fBlockSize);
271 	TRACE("sector size %" B_PRIu32 "\n", fSectorSize);
272 
273 	uint8* start = (uint8*)&fSuperBlock.system_chunk_array[0];
274 	uint8* end = (uint8*)&fSuperBlock.system_chunk_array[2048];
275 	while (start < end) {
276 		btrfs_key* key = (btrfs_key*)start;
277 		TRACE("system_chunk_array object_id 0x%" B_PRIx64 " offset 0x%"
278 			B_PRIx64 " type 0x%x\n", key->ObjectID(), key->Offset(),
279 			key->Type());
280 		if (key->Type() != BTRFS_KEY_TYPE_CHUNK_ITEM) {
281 			break;
282 		}
283 
284 		btrfs_chunk* chunk = (btrfs_chunk*)(key + 1);
285 		fChunk = new(std::nothrow) Chunk(chunk, key->Offset());
286 		if (fChunk == NULL)
287 			return B_ERROR;
288 		start += sizeof(btrfs_key) + fChunk->Size();
289 	}
290 
291 	TRACE("Volume::Mount() generation: %" B_PRIu64 "\n",
292 		fSuperBlock.Generation());
293 	fsblock_t physical = 0;
294 	FindBlock(fSuperBlock.Root(), physical);
295 	TRACE("Volume::Mount() root: %" B_PRIu64 " (physical %" B_PRIu64 ")\n",
296 		fSuperBlock.Root(), physical);
297 	FindBlock(fSuperBlock.ChunkRoot(), physical);
298 	TRACE("Volume::Mount() chunk_root: %" B_PRIu64 " (physical %" B_PRIu64
299 		")\n", fSuperBlock.ChunkRoot(), physical);
300 	FindBlock(fSuperBlock.LogRoot(), physical);
301 	TRACE("Volume::Mount() log_root: %" B_PRIu64 " (physical %" B_PRIu64 ")\n",
302 		fSuperBlock.LogRoot(), physical);
303 
304 	// check if the device size is large enough to hold the file system
305 	off_t diskSize;
306 	status = opener.GetSize(&diskSize);
307 	if (status != B_OK)
308 		return status;
309 	if (diskSize < (off_t)fSuperBlock.TotalSize())
310 		return B_BAD_VALUE;
311 
312 	fBlockCache = opener.InitCache(fSuperBlock.TotalSize() / fBlockSize,
313 		fBlockSize);
314 	if (fBlockCache == NULL)
315 		return B_ERROR;
316 
317 	TRACE("Volume::Mount(): Initialized block cache: %p\n", fBlockCache);
318 
319 	fChunkTree = new(std::nothrow) BTree(this, fSuperBlock.ChunkRoot());
320 	if (fChunkTree == NULL)
321 		return B_NO_MEMORY;
322 
323 	FindBlock(fSuperBlock.Root(), physical);
324 	TRACE("Volume::Mount() root: %" B_PRIu64 " (physical %" B_PRIu64 ")\n",
325 		fSuperBlock.Root(), physical);
326 	FindBlock(fSuperBlock.ChunkRoot(), physical);
327 	TRACE("Volume::Mount() chunk_root: %" B_PRIu64 " (physical %" B_PRIu64
328 		")\n", fSuperBlock.ChunkRoot(), physical);
329 	FindBlock(fSuperBlock.LogRoot(), physical);
330 	TRACE("Volume::Mount() log_root: %" B_PRIu64 " (physical %" B_PRIu64 ")\n",
331 		fSuperBlock.LogRoot(), physical);
332 
333 	fRootTree = new(std::nothrow) BTree(this, fSuperBlock.Root());
334 	if (fRootTree == NULL)
335 		return B_NO_MEMORY;
336 	TRACE("Volume::Mount(): Searching extent root\n");
337 	btrfs_key search_key;
338 	search_key.SetOffset(0);
339 	search_key.SetType(BTRFS_KEY_TYPE_ROOT_ITEM);
340 	search_key.SetObjectID(BTRFS_OBJECT_ID_EXTENT_TREE);
341 	btrfs_root* root;
342 	if (fRootTree->FindNext(search_key, (void**)&root) != B_OK) {
343 		ERROR("Volume::Mount(): Couldn't find extent root\n");
344 		return B_ERROR;
345 	}
346 	TRACE("Volume::Mount(): Found extent root: %" B_PRIu64 "\n",
347 		root->BlockNum());
348 	fExtentTree = new(std::nothrow) BTree(this, root->BlockNum());
349 	free(root);
350 	if (fExtentTree == NULL)
351 		return B_NO_MEMORY;
352 
353 	search_key.SetOffset(0);
354 	search_key.SetObjectID(BTRFS_OBJECT_ID_FS_TREE);
355 	if (fRootTree->FindNext(search_key, (void**)&root) != B_OK) {
356 		ERROR("Volume::Mount(): Couldn't find fs root\n");
357 		return B_ERROR;
358 	}
359 	TRACE("Volume::Mount(): Found fs root: %" B_PRIu64 "\n", root->BlockNum());
360 	fFSTree = new(std::nothrow) BTree(this, root->BlockNum());
361 	free(root);
362 	if (fFSTree == NULL)
363 		return B_NO_MEMORY;
364 
365 	search_key.SetOffset(0);
366 	search_key.SetObjectID(BTRFS_OBJECT_ID_DEV_TREE);
367 	if (fRootTree->FindNext(search_key, (void**)&root) != B_OK) {
368 		ERROR("Volume::Mount(): Couldn't find dev root\n");
369 		return B_ERROR;
370 	}
371 	TRACE("Volume::Mount(): Found dev root: %" B_PRIu64 "\n",
372 		root->BlockNum());
373 	fDevTree = new(std::nothrow) BTree(this, root->BlockNum());
374 	free(root);
375 	if (fDevTree == NULL)
376 		return B_NO_MEMORY;
377 
378 	search_key.SetOffset(0);
379 	search_key.SetObjectID(BTRFS_OBJECT_ID_CHECKSUM_TREE);
380 	if (fRootTree->FindNext(search_key, (void**)&root) != B_OK) {
381 		ERROR("Volume::Mount(): Couldn't find checksum root\n");
382 		return B_ERROR;
383 	}
384 	TRACE("Volume::Mount(): Found checksum root: %" B_PRIu64 "\n",
385 		root->BlockNum());
386 	fChecksumTree = new(std::nothrow) BTree(this, root->BlockNum());
387 	free(root);
388 	if (fChecksumTree == NULL)
389 		return B_NO_MEMORY;
390 
391 	// ready
392 	status = get_vnode(fFSVolume, BTRFS_FIRST_SUBVOLUME,
393 		(void**)&fRootNode);
394 	if (status != B_OK) {
395 		ERROR("could not create root node: get_vnode() failed!\n");
396 		return status;
397 	}
398 
399 	TRACE("Volume::Mount(): Found root node: %" B_PRIu64 " (%s)\n",
400 		fRootNode->ID(), strerror(fRootNode->InitCheck()));
401 
402 	// all went fine
403 	opener.Keep();
404 
405 	if (!fSuperBlock.label[0]) {
406 		// generate a more or less descriptive volume name
407 		off_t divisor = 1ULL << 40;
408 		char unit = 'T';
409 		if (diskSize < divisor) {
410 			divisor = 1UL << 30;
411 			unit = 'G';
412 			if (diskSize < divisor) {
413 				divisor = 1UL << 20;
414 				unit = 'M';
415 			}
416 		}
417 
418 		double size = double((10 * diskSize + divisor - 1) / divisor);
419 			// %g in the kernel does not support precision...
420 
421 		snprintf(fName, sizeof(fName), "%g %cB Btrfs Volume",
422 			size / 10, unit);
423 	}
424 
425 	return B_OK;
426 }
427 
428 
429 status_t
430 Volume::Unmount()
431 {
432 	TRACE("Volume::Unmount()\n");
433 	delete fExtentTree;
434 	delete fChecksumTree;
435 	delete fFSTree;
436 	delete fDevTree;
437 	fExtentTree = NULL;
438 	fChecksumTree = NULL;
439 	fFSTree = NULL;
440 	fDevTree = NULL;
441 
442 	TRACE("Volume::Unmount(): Putting root node\n");
443 	put_vnode(fFSVolume, RootNode()->ID());
444 	TRACE("Volume::Unmount(): Deleting the block cache\n");
445 	block_cache_delete(fBlockCache, !IsReadOnly());
446 	TRACE("Volume::Unmount(): Closing device\n");
447 	close(fDevice);
448 
449 	TRACE("Volume::Unmount(): Done\n");
450 	return B_OK;
451 }
452 
453 
454 status_t
455 Volume::LoadSuperBlock()
456 {
457 	CachedBlock cached(this);
458 	const uint8* block = cached.SetTo(BTRFS_SUPER_BLOCK_OFFSET / fBlockSize);
459 
460 	if (block == NULL)
461 		return B_IO_ERROR;
462 
463 	memcpy(&fSuperBlock, block + BTRFS_SUPER_BLOCK_OFFSET % fBlockSize,
464 		sizeof(fSuperBlock));
465 
466 	return B_OK;
467 }
468 
469 
470 status_t
471 Volume::FindBlock(off_t logical, fsblock_t& physicalBlock)
472 {
473 	off_t physical;
474 	status_t status = FindBlock(logical, physical);
475 	if (status != B_OK)
476 		return status;
477 	physicalBlock = physical / fBlockSize;
478 	return B_OK;
479 }
480 
481 
482 status_t
483 Volume::FindBlock(off_t logical, off_t& physical)
484 {
485 	if (fChunkTree == NULL
486 		|| (logical >= (off_t)fChunk->Offset()
487 			&& logical < (off_t)fChunk->End())) {
488 		// try with fChunk
489 		return fChunk->FindBlock(logical, physical);
490 	}
491 
492 	btrfs_key search_key;
493 	search_key.SetOffset(logical);
494 	search_key.SetType(BTRFS_KEY_TYPE_CHUNK_ITEM);
495  	search_key.SetObjectID(BTRFS_OBJECT_ID_FIRST_CHUNK_TREE);
496 	btrfs_chunk* chunk;
497 	size_t chunk_length;
498 	status_t status = fChunkTree->FindPrevious(search_key, (void**)&chunk,
499 		&chunk_length);
500 	if (status != B_OK)
501 		return status;
502 
503 	Chunk _chunk(chunk, search_key.Offset());
504 	free(chunk);
505 	status = _chunk.FindBlock(logical, physical);
506 	if (status != B_OK)
507 			return status;
508 	TRACE("Volume::FindBlock(): logical: %" B_PRIdOFF ", physical: %" B_PRIdOFF
509 		"\n", logical, physical);
510 	return B_OK;
511 }
512 
513 
514 //	#pragma mark - Disk scanning and initialization
515 
516 
517 /*static*/ status_t
518 Volume::Identify(int fd, btrfs_super_block* superBlock)
519 {
520 	if (read_pos(fd, BTRFS_SUPER_BLOCK_OFFSET, superBlock,
521 			sizeof(btrfs_super_block)) != sizeof(btrfs_super_block))
522 		return B_IO_ERROR;
523 
524 	if (!superBlock->IsValid()) {
525 		ERROR("invalid superblock!\n");
526 		return B_BAD_VALUE;
527 	}
528 
529 	return B_OK;
530 }
531 
532