nilfs2: replace BUG_ON and BUG calls triggerable from ioctl

Pekka Enberg advised me:
> It would be nice if BUG(), BUG_ON(), and panic() calls would be
> converted to proper error handling using WARN_ON() calls. The BUG()
> call in nilfs_cpfile_delete_checkpoints(), for example, looks to be
> triggerable from user-space via the ioctl() system call.

This will follow the comment and keep them to a minimum.

Acked-by: Pekka Enberg <penberg@cs.helsinki.fi>
Signed-off-by: Ryusuke Konishi <konishi.ryusuke@lab.ntt.co.jp>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
diff --git a/fs/nilfs2/sufile.c b/fs/nilfs2/sufile.c
index cc714c7..4cf47e0 100644
--- a/fs/nilfs2/sufile.c
+++ b/fs/nilfs2/sufile.c
@@ -231,10 +231,11 @@
 	kaddr = kmap_atomic(su_bh->b_page, KM_USER0);
 	su = nilfs_sufile_block_get_segment_usage(
 		sufile, segnum, su_bh, kaddr);
-	if (!nilfs_segment_usage_clean(su)) {
-		printk(KERN_CRIT "%s: segment %llu must be clean\n",
+	if (unlikely(!nilfs_segment_usage_clean(su))) {
+		printk(KERN_WARNING "%s: segment %llu must be clean\n",
 		       __func__, (unsigned long long)segnum);
-		BUG();
+		kunmap_atomic(kaddr, KM_USER0);
+		goto out_su_bh;
 	}
 	nilfs_segment_usage_set_dirty(su);
 	kunmap_atomic(kaddr, KM_USER0);
@@ -249,11 +250,10 @@
 	nilfs_mdt_mark_buffer_dirty(su_bh);
 	nilfs_mdt_mark_dirty(sufile);
 
+ out_su_bh:
 	brelse(su_bh);
-
  out_header:
 	brelse(header_bh);
-
  out_sem:
 	up_write(&NILFS_MDT(sufile)->mi_sem);
 	return ret;
@@ -317,7 +317,7 @@
 		kaddr = kmap_atomic(su_bh[i]->b_page, KM_USER0);
 		su = nilfs_sufile_block_get_segment_usage(
 			sufile, segnum[i], su_bh[i], kaddr);
-		BUG_ON(nilfs_segment_usage_error(su));
+		WARN_ON(nilfs_segment_usage_error(su));
 		nilfs_segment_usage_set_clean(su);
 		kunmap_atomic(kaddr, KM_USER0);
 		nilfs_mdt_mark_buffer_dirty(su_bh[i]);
@@ -385,8 +385,8 @@
 	int ret;
 
 	/* segnum is 0 origin */
-	BUG_ON(segnum >= nilfs_sufile_get_nsegments(sufile));
-
+	if (segnum >= nilfs_sufile_get_nsegments(sufile))
+		return -EINVAL;
 	down_write(&NILFS_MDT(sufile)->mi_sem);
 	ret = nilfs_sufile_get_segment_usage_block(sufile, segnum, 1, &bh);
 	if (ret < 0)
@@ -515,6 +515,8 @@
  * %-EIO - I/O error.
  *
  * %-ENOMEM - Insufficient amount of memory available.
+ *
+ * %-EINVAL - Invalid segment usage number.
  */
 int nilfs_sufile_set_error(struct inode *sufile, __u64 segnum)
 {
@@ -524,8 +526,11 @@
 	void *kaddr;
 	int ret;
 
-	BUG_ON(segnum >= nilfs_sufile_get_nsegments(sufile));
-
+	if (unlikely(segnum >= nilfs_sufile_get_nsegments(sufile))) {
+		printk(KERN_WARNING "%s: invalid segment number: %llu\n",
+		       __func__, (unsigned long long)segnum);
+		return -EINVAL;
+	}
 	down_write(&NILFS_MDT(sufile)->mi_sem);
 
 	ret = nilfs_sufile_get_header_block(sufile, &header_bh);