xref: /linux/fs/xfs/xfs_dquot.c (revision da483b8a9c2c3e7b23655699680feb57a194000c)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2003 Silicon Graphics, Inc.
4  * All Rights Reserved.
5  */
6 #include "xfs_platform.h"
7 #include "xfs_fs.h"
8 #include "xfs_format.h"
9 #include "xfs_log_format.h"
10 #include "xfs_shared.h"
11 #include "xfs_trans_resv.h"
12 #include "xfs_bit.h"
13 #include "xfs_mount.h"
14 #include "xfs_defer.h"
15 #include "xfs_inode.h"
16 #include "xfs_bmap.h"
17 #include "xfs_quota.h"
18 #include "xfs_trans.h"
19 #include "xfs_buf_item.h"
20 #include "xfs_trans_space.h"
21 #include "xfs_trans_priv.h"
22 #include "xfs_qm.h"
23 #include "xfs_trace.h"
24 #include "xfs_log.h"
25 #include "xfs_bmap_btree.h"
26 #include "xfs_error.h"
27 #include "xfs_health.h"
28 
29 /*
30  * Lock order:
31  *
32  * ip->i_lock
33  *   qi->qi_tree_lock
34  *     dquot->q_qlock
35  *       dquot->q_flush (xfs_dqflock() and friends)
36  *       qi->qi_lru_lock
37  *
38  * If two dquots need to be locked the order is user before group/project,
39  * otherwise by the lowest id first, see xfs_dqlock2.
40  */
41 
42 struct kmem_cache		*xfs_dqtrx_cache;
43 static struct kmem_cache	*xfs_dquot_cache;
44 
45 static struct lock_class_key xfs_dquot_group_class;
46 static struct lock_class_key xfs_dquot_project_class;
47 
48 /* Record observations of quota corruption with the health tracking system. */
49 static void
50 xfs_dquot_mark_sick(
51 	struct xfs_dquot	*dqp)
52 {
53 	struct xfs_mount	*mp = dqp->q_mount;
54 
55 	switch (dqp->q_type) {
56 	case XFS_DQTYPE_USER:
57 		xfs_fs_mark_sick(mp, XFS_SICK_FS_UQUOTA);
58 		break;
59 	case XFS_DQTYPE_GROUP:
60 		xfs_fs_mark_sick(mp, XFS_SICK_FS_GQUOTA);
61 		break;
62 	case XFS_DQTYPE_PROJ:
63 		xfs_fs_mark_sick(mp, XFS_SICK_FS_PQUOTA);
64 		break;
65 	default:
66 		ASSERT(0);
67 		break;
68 	}
69 }
70 
71 /*
72  * Detach the dquot buffer if it's still attached, because we can get called
73  * through dqpurge after a log shutdown.  Caller must hold the dqflock or have
74  * otherwise isolated the dquot.
75  */
76 void
77 xfs_dquot_detach_buf(
78 	struct xfs_dquot	*dqp)
79 {
80 	struct xfs_dq_logitem	*qlip = &dqp->q_logitem;
81 	struct xfs_buf		*bp = NULL;
82 
83 	spin_lock(&qlip->qli_lock);
84 	if (qlip->qli_item.li_buf) {
85 		bp = qlip->qli_item.li_buf;
86 		qlip->qli_item.li_buf = NULL;
87 	}
88 	spin_unlock(&qlip->qli_lock);
89 	if (bp) {
90 		xfs_buf_lock(bp);
91 		list_del_init(&qlip->qli_item.li_bio_list);
92 		xfs_buf_relse(bp);
93 	}
94 }
95 
96 /*
97  * This is called to free all the memory associated with a dquot
98  */
99 void
100 xfs_qm_dqdestroy(
101 	struct xfs_dquot	*dqp)
102 {
103 	ASSERT(list_empty(&dqp->q_lru));
104 	ASSERT(dqp->q_logitem.qli_item.li_buf == NULL);
105 
106 	kvfree(dqp->q_logitem.qli_item.li_lv_shadow);
107 	mutex_destroy(&dqp->q_qlock);
108 
109 	XFS_STATS_DEC(dqp->q_mount, xs_qm_dquot);
110 	kmem_cache_free(xfs_dquot_cache, dqp);
111 }
112 
113 /*
114  * If default limits are in force, push them into the dquot now.
115  * We overwrite the dquot limits only if they are zero and this
116  * is not the root dquot.
117  */
118 static void
119 xfs_qm_adjust_dqlimits(
120 	struct xfs_dquot	*dq)
121 {
122 	struct xfs_mount	*mp = dq->q_mount;
123 	struct xfs_quotainfo	*q = mp->m_quotainfo;
124 	struct xfs_def_quota	*defq = xfs_get_defquota(q, xfs_dquot_type(dq));
125 	int			prealloc = 0;
126 
127 	if (!dq->q_blk.softlimit) {
128 		dq->q_blk.softlimit = defq->blk.soft;
129 		prealloc = 1;
130 	}
131 	if (!dq->q_blk.hardlimit) {
132 		dq->q_blk.hardlimit = defq->blk.hard;
133 		prealloc = 1;
134 	}
135 	if (!dq->q_ino.softlimit)
136 		dq->q_ino.softlimit = defq->ino.soft;
137 	if (!dq->q_ino.hardlimit)
138 		dq->q_ino.hardlimit = defq->ino.hard;
139 	if (!dq->q_rtb.softlimit) {
140 		dq->q_rtb.softlimit = defq->rtb.soft;
141 		prealloc = 1;
142 	}
143 	if (!dq->q_rtb.hardlimit) {
144 		dq->q_rtb.hardlimit = defq->rtb.hard;
145 		prealloc = 1;
146 	}
147 
148 	if (prealloc)
149 		xfs_dquot_set_prealloc_limits(dq);
150 }
151 
152 /* Set the expiration time of a quota's grace period. */
153 time64_t
154 xfs_dquot_set_timeout(
155 	struct xfs_mount	*mp,
156 	time64_t		timeout)
157 {
158 	struct xfs_quotainfo	*qi = mp->m_quotainfo;
159 
160 	return clamp_t(time64_t, timeout, qi->qi_expiry_min,
161 					  qi->qi_expiry_max);
162 }
163 
164 /* Set the length of the default grace period. */
165 time64_t
166 xfs_dquot_set_grace_period(
167 	time64_t		grace)
168 {
169 	return clamp_t(time64_t, grace, XFS_DQ_GRACE_MIN, XFS_DQ_GRACE_MAX);
170 }
171 
172 /*
173  * Determine if this quota counter is over either limit and set the quota
174  * timers as appropriate.
175  */
176 static inline void
177 xfs_qm_adjust_res_timer(
178 	struct xfs_mount	*mp,
179 	struct xfs_dquot_res	*res,
180 	struct xfs_quota_limits	*qlim)
181 {
182 	ASSERT(res->hardlimit == 0 || res->softlimit <= res->hardlimit);
183 
184 	if ((res->softlimit && res->count > res->softlimit) ||
185 	    (res->hardlimit && res->count > res->hardlimit)) {
186 		if (res->timer == 0)
187 			res->timer = xfs_dquot_set_timeout(mp,
188 					ktime_get_real_seconds() + qlim->time);
189 	} else {
190 		res->timer = 0;
191 	}
192 }
193 
194 /*
195  * Check the limits and timers of a dquot and start or reset timers
196  * if necessary.
197  * This gets called even when quota enforcement is OFF, which makes our
198  * life a little less complicated. (We just don't reject any quota
199  * reservations in that case, when enforcement is off).
200  * We also return 0 as the values of the timers in Q_GETQUOTA calls, when
201  * enforcement's off.
202  * In contrast, warnings are a little different in that they don't
203  * 'automatically' get started when limits get exceeded.  They do
204  * get reset to zero, however, when we find the count to be under
205  * the soft limit (they are only ever set non-zero via userspace).
206  */
207 void
208 xfs_qm_adjust_dqtimers(
209 	struct xfs_dquot	*dq)
210 {
211 	struct xfs_mount	*mp = dq->q_mount;
212 	struct xfs_quotainfo	*qi = mp->m_quotainfo;
213 	struct xfs_def_quota	*defq;
214 
215 	ASSERT(dq->q_id);
216 	defq = xfs_get_defquota(qi, xfs_dquot_type(dq));
217 
218 	xfs_qm_adjust_res_timer(dq->q_mount, &dq->q_blk, &defq->blk);
219 	xfs_qm_adjust_res_timer(dq->q_mount, &dq->q_ino, &defq->ino);
220 	xfs_qm_adjust_res_timer(dq->q_mount, &dq->q_rtb, &defq->rtb);
221 }
222 
223 /* Adjust enforcement limits and timers after a change in usage. */
224 void
225 xfs_qm_adjust_dqenforcement(
226 	struct xfs_dquot	*dq)
227 {
228 	if (dq->q_id == 0)
229 		return;
230 
231 	xfs_qm_adjust_dqlimits(dq);
232 	xfs_qm_adjust_dqtimers(dq);
233 	dq->q_flags |= XFS_DQFLAG_DIRTY;
234 }
235 
236 /*
237  * initialize a buffer full of dquots and log the whole thing
238  */
239 void
240 xfs_qm_init_dquot_blk(
241 	struct xfs_trans	*tp,
242 	xfs_dqid_t		id,
243 	xfs_dqtype_t		type,
244 	struct xfs_buf		*bp)
245 {
246 	struct xfs_mount	*mp = tp->t_mountp;
247 	struct xfs_quotainfo	*q = mp->m_quotainfo;
248 	struct xfs_dqblk	*d;
249 	xfs_dqid_t		curid;
250 	unsigned int		qflag;
251 	unsigned int		blftype;
252 	int			i;
253 
254 	ASSERT(tp);
255 	ASSERT(xfs_buf_islocked(bp));
256 
257 	switch (type) {
258 	case XFS_DQTYPE_USER:
259 		qflag = XFS_UQUOTA_CHKD;
260 		blftype = XFS_BLF_UDQUOT_BUF;
261 		break;
262 	case XFS_DQTYPE_PROJ:
263 		qflag = XFS_PQUOTA_CHKD;
264 		blftype = XFS_BLF_PDQUOT_BUF;
265 		break;
266 	case XFS_DQTYPE_GROUP:
267 		qflag = XFS_GQUOTA_CHKD;
268 		blftype = XFS_BLF_GDQUOT_BUF;
269 		break;
270 	default:
271 		ASSERT(0);
272 		return;
273 	}
274 
275 	d = bp->b_addr;
276 
277 	/*
278 	 * ID of the first dquot in the block - id's are zero based.
279 	 */
280 	curid = id - (id % q->qi_dqperchunk);
281 	memset(d, 0, BBTOB(q->qi_dqchunklen));
282 	for (i = 0; i < q->qi_dqperchunk; i++, d++, curid++) {
283 		d->dd_diskdq.d_magic = cpu_to_be16(XFS_DQUOT_MAGIC);
284 		d->dd_diskdq.d_version = XFS_DQUOT_VERSION;
285 		d->dd_diskdq.d_id = cpu_to_be32(curid);
286 		d->dd_diskdq.d_type = type;
287 		if (curid > 0 && xfs_has_bigtime(mp))
288 			d->dd_diskdq.d_type |= XFS_DQTYPE_BIGTIME;
289 		if (xfs_has_crc(mp)) {
290 			uuid_copy(&d->dd_uuid, &mp->m_sb.sb_meta_uuid);
291 			xfs_update_cksum((char *)d, sizeof(struct xfs_dqblk),
292 					 XFS_DQUOT_CRC_OFF);
293 		}
294 	}
295 
296 	xfs_trans_dquot_buf(tp, bp, blftype);
297 
298 	/*
299 	 * quotacheck uses delayed writes to update all the dquots on disk in an
300 	 * efficient manner instead of logging the individual dquot changes as
301 	 * they are made. However if we log the buffer allocated here and crash
302 	 * after quotacheck while the logged initialisation is still in the
303 	 * active region of the log, log recovery can replay the dquot buffer
304 	 * initialisation over the top of the checked dquots and corrupt quota
305 	 * accounting.
306 	 *
307 	 * To avoid this problem, quotacheck cannot log the initialised buffer.
308 	 * We must still dirty the buffer and write it back before the
309 	 * allocation transaction clears the log. Therefore, mark the buffer as
310 	 * ordered instead of logging it directly. This is safe for quotacheck
311 	 * because it detects and repairs allocated but initialized dquot blocks
312 	 * in the quota inodes.
313 	 */
314 	if (!(mp->m_qflags & qflag))
315 		xfs_trans_ordered_buf(tp, bp);
316 	else
317 		xfs_trans_log_buf(tp, bp, 0, BBTOB(q->qi_dqchunklen) - 1);
318 }
319 
320 static void
321 xfs_dquot_set_prealloc(
322 	struct xfs_dquot_pre		*pre,
323 	const struct xfs_dquot_res	*res)
324 {
325 	xfs_qcnt_t			space;
326 
327 	pre->q_prealloc_hi_wmark = res->hardlimit;
328 	pre->q_prealloc_lo_wmark = res->softlimit;
329 
330 	space = div_u64(pre->q_prealloc_hi_wmark, 100);
331 	if (!pre->q_prealloc_lo_wmark)
332 		pre->q_prealloc_lo_wmark = space * 95;
333 
334 	pre->q_low_space[XFS_QLOWSP_1_PCNT] = space;
335 	pre->q_low_space[XFS_QLOWSP_3_PCNT] = space * 3;
336 	pre->q_low_space[XFS_QLOWSP_5_PCNT] = space * 5;
337 }
338 
339 /*
340  * Initialize the dynamic speculative preallocation thresholds. The lo/hi
341  * watermarks correspond to the soft and hard limits by default. If a soft limit
342  * is not specified, we use 95% of the hard limit.
343  */
344 void
345 xfs_dquot_set_prealloc_limits(struct xfs_dquot *dqp)
346 {
347 	xfs_dquot_set_prealloc(&dqp->q_blk_prealloc, &dqp->q_blk);
348 	xfs_dquot_set_prealloc(&dqp->q_rtb_prealloc, &dqp->q_rtb);
349 }
350 
351 /*
352  * Ensure that the given in-core dquot has a buffer on disk backing it, and
353  * return the buffer locked and held. This is called when the bmapi finds a
354  * hole.
355  */
356 STATIC int
357 xfs_dquot_disk_alloc(
358 	struct xfs_dquot	*dqp,
359 	struct xfs_buf		**bpp)
360 {
361 	struct xfs_bmbt_irec	map;
362 	struct xfs_trans	*tp;
363 	struct xfs_mount	*mp = dqp->q_mount;
364 	struct xfs_buf		*bp;
365 	xfs_dqtype_t		qtype = xfs_dquot_type(dqp);
366 	struct xfs_inode	*quotip = xfs_quota_inode(mp, qtype);
367 	int			nmaps = 1;
368 	int			error;
369 
370 	trace_xfs_dqalloc(dqp);
371 
372 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_qm_dqalloc,
373 			XFS_QM_DQALLOC_SPACE_RES(mp), 0, 0, &tp);
374 	if (error)
375 		return error;
376 
377 	xfs_ilock(quotip, XFS_ILOCK_EXCL);
378 	xfs_trans_ijoin(tp, quotip, 0);
379 
380 	if (!xfs_this_quota_on(dqp->q_mount, qtype)) {
381 		/*
382 		 * Return if this type of quotas is turned off while we didn't
383 		 * have an inode lock
384 		 */
385 		error = -ESRCH;
386 		goto err_cancel;
387 	}
388 
389 	error = xfs_iext_count_extend(tp, quotip, XFS_DATA_FORK,
390 			XFS_IEXT_ADD_NOSPLIT_CNT);
391 	if (error)
392 		goto err_cancel;
393 
394 	/* Create the block mapping. */
395 	error = xfs_bmapi_write(tp, quotip, dqp->q_fileoffset,
396 			XFS_DQUOT_CLUSTER_SIZE_FSB, XFS_BMAPI_METADATA, 0, &map,
397 			&nmaps);
398 	if (error)
399 		goto err_cancel;
400 
401 	ASSERT(map.br_blockcount == XFS_DQUOT_CLUSTER_SIZE_FSB);
402 	ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
403 	       (map.br_startblock != HOLESTARTBLOCK));
404 
405 	/*
406 	 * Keep track of the blkno to save a lookup later
407 	 */
408 	dqp->q_blkno = XFS_FSB_TO_DADDR(mp, map.br_startblock);
409 
410 	/* now we can just get the buffer (there's nothing to read yet) */
411 	error = xfs_trans_get_buf(tp, mp->m_ddev_targp, dqp->q_blkno,
412 			mp->m_quotainfo->qi_dqchunklen, 0, &bp);
413 	if (error)
414 		goto err_cancel;
415 	bp->b_ops = &xfs_dquot_buf_ops;
416 
417 	/*
418 	 * Make a chunk of dquots out of this buffer and log
419 	 * the entire thing.
420 	 */
421 	xfs_qm_init_dquot_blk(tp, dqp->q_id, qtype, bp);
422 	xfs_buf_set_ref(bp, XFS_DQUOT_REF);
423 
424 	/*
425 	 * Hold the buffer and join it to the dfops so that we'll still own
426 	 * the buffer when we return to the caller.  The buffer disposal on
427 	 * error must be paid attention to very carefully, as it has been
428 	 * broken since commit efa092f3d4c6 "[XFS] Fixes a bug in the quota
429 	 * code when allocating a new dquot record" in 2005, and the later
430 	 * conversion to xfs_defer_ops in commit 310a75a3c6c747 failed to keep
431 	 * the buffer locked across the _defer_finish call.  We can now do
432 	 * this correctly with xfs_defer_bjoin.
433 	 *
434 	 * Above, we allocated a disk block for the dquot information and used
435 	 * get_buf to initialize the dquot. If the _defer_finish fails, the old
436 	 * transaction is gone but the new buffer is not joined or held to any
437 	 * transaction, so we must _buf_relse it.
438 	 *
439 	 * If everything succeeds, the caller of this function is returned a
440 	 * buffer that is locked and held to the transaction.  The caller
441 	 * is responsible for unlocking any buffer passed back, either
442 	 * manually or by committing the transaction.  On error, the buffer is
443 	 * released and not passed back.
444 	 *
445 	 * Keep the quota inode ILOCKed until after the transaction commit to
446 	 * maintain the atomicity of bmap/rmap updates.
447 	 */
448 	xfs_trans_bhold(tp, bp);
449 	error = xfs_trans_commit(tp);
450 	xfs_iunlock(quotip, XFS_ILOCK_EXCL);
451 	if (error) {
452 		xfs_buf_relse(bp);
453 		return error;
454 	}
455 
456 	*bpp = bp;
457 	return 0;
458 
459 err_cancel:
460 	xfs_trans_cancel(tp);
461 	xfs_iunlock(quotip, XFS_ILOCK_EXCL);
462 	return error;
463 }
464 
465 /*
466  * Read in the in-core dquot's on-disk metadata and return the buffer.
467  * Returns ENOENT to signal a hole.
468  */
469 STATIC int
470 xfs_dquot_disk_read(
471 	struct xfs_mount	*mp,
472 	struct xfs_dquot	*dqp,
473 	struct xfs_buf		**bpp)
474 {
475 	struct xfs_bmbt_irec	map;
476 	struct xfs_buf		*bp;
477 	xfs_dqtype_t		qtype = xfs_dquot_type(dqp);
478 	struct xfs_inode	*quotip = xfs_quota_inode(mp, qtype);
479 	uint			lock_mode;
480 	int			nmaps = 1;
481 	int			error;
482 
483 	lock_mode = xfs_ilock_data_map_shared(quotip);
484 	if (!xfs_this_quota_on(mp, qtype)) {
485 		/*
486 		 * Return if this type of quotas is turned off while we
487 		 * didn't have the quota inode lock.
488 		 */
489 		xfs_iunlock(quotip, lock_mode);
490 		return -ESRCH;
491 	}
492 
493 	/*
494 	 * Find the block map; no allocations yet
495 	 */
496 	error = xfs_bmapi_read(quotip, dqp->q_fileoffset,
497 			XFS_DQUOT_CLUSTER_SIZE_FSB, &map, &nmaps, 0);
498 	xfs_iunlock(quotip, lock_mode);
499 	if (error)
500 		return error;
501 
502 	ASSERT(nmaps == 1);
503 	ASSERT(map.br_blockcount >= 1);
504 	ASSERT(map.br_startblock != DELAYSTARTBLOCK);
505 	if (map.br_startblock == HOLESTARTBLOCK)
506 		return -ENOENT;
507 
508 	trace_xfs_dqtobp_read(dqp);
509 
510 	/*
511 	 * store the blkno etc so that we don't have to do the
512 	 * mapping all the time
513 	 */
514 	dqp->q_blkno = XFS_FSB_TO_DADDR(mp, map.br_startblock);
515 
516 	error = xfs_trans_read_buf(mp, NULL, mp->m_ddev_targp, dqp->q_blkno,
517 			mp->m_quotainfo->qi_dqchunklen, 0, &bp,
518 			&xfs_dquot_buf_ops);
519 	if (xfs_metadata_is_sick(error))
520 		xfs_dquot_mark_sick(dqp);
521 	if (error) {
522 		ASSERT(bp == NULL);
523 		return error;
524 	}
525 
526 	ASSERT(xfs_buf_islocked(bp));
527 	xfs_buf_set_ref(bp, XFS_DQUOT_REF);
528 	*bpp = bp;
529 
530 	return 0;
531 }
532 
533 /* Allocate and initialize everything we need for an incore dquot. */
534 STATIC struct xfs_dquot *
535 xfs_dquot_alloc(
536 	struct xfs_mount	*mp,
537 	xfs_dqid_t		id,
538 	xfs_dqtype_t		type)
539 {
540 	struct xfs_dquot	*dqp;
541 
542 	dqp = kmem_cache_zalloc(xfs_dquot_cache, GFP_KERNEL | __GFP_NOFAIL);
543 
544 	dqp->q_type = type;
545 	dqp->q_id = id;
546 	dqp->q_mount = mp;
547 	INIT_LIST_HEAD(&dqp->q_lru);
548 	mutex_init(&dqp->q_qlock);
549 	init_waitqueue_head(&dqp->q_pinwait);
550 	dqp->q_fileoffset = (xfs_fileoff_t)id / mp->m_quotainfo->qi_dqperchunk;
551 	/*
552 	 * Offset of dquot in the (fixed sized) dquot chunk.
553 	 */
554 	dqp->q_bufoffset = (id % mp->m_quotainfo->qi_dqperchunk) *
555 			sizeof(struct xfs_dqblk);
556 
557 	/*
558 	 * Because we want to use a counting completion, complete
559 	 * the flush completion once to allow a single access to
560 	 * the flush completion without blocking.
561 	 */
562 	init_completion(&dqp->q_flush);
563 	complete(&dqp->q_flush);
564 
565 	/*
566 	 * Make sure group quotas have a different lock class than user
567 	 * quotas.
568 	 */
569 	switch (type) {
570 	case XFS_DQTYPE_USER:
571 		/* uses the default lock class */
572 		break;
573 	case XFS_DQTYPE_GROUP:
574 		lockdep_set_class(&dqp->q_qlock, &xfs_dquot_group_class);
575 		break;
576 	case XFS_DQTYPE_PROJ:
577 		lockdep_set_class(&dqp->q_qlock, &xfs_dquot_project_class);
578 		break;
579 	default:
580 		ASSERT(0);
581 		break;
582 	}
583 
584 	xfs_qm_dquot_logitem_init(dqp);
585 
586 	XFS_STATS_INC(mp, xs_qm_dquot);
587 	return dqp;
588 }
589 
590 /* Check the ondisk dquot's id and type match what the incore dquot expects. */
591 static bool
592 xfs_dquot_check_type(
593 	struct xfs_dquot	*dqp,
594 	struct xfs_disk_dquot	*ddqp)
595 {
596 	uint8_t			ddqp_type;
597 	uint8_t			dqp_type;
598 
599 	ddqp_type = ddqp->d_type & XFS_DQTYPE_REC_MASK;
600 	dqp_type = xfs_dquot_type(dqp);
601 
602 	if (be32_to_cpu(ddqp->d_id) != dqp->q_id)
603 		return false;
604 
605 	/*
606 	 * V5 filesystems always expect an exact type match.  V4 filesystems
607 	 * expect an exact match for user dquots and for non-root group and
608 	 * project dquots.
609 	 */
610 	if (xfs_has_crc(dqp->q_mount) ||
611 	    dqp_type == XFS_DQTYPE_USER || dqp->q_id != 0)
612 		return ddqp_type == dqp_type;
613 
614 	/*
615 	 * V4 filesystems support either group or project quotas, but not both
616 	 * at the same time.  The non-user quota file can be switched between
617 	 * group and project quota uses depending on the mount options, which
618 	 * means that we can encounter the other type when we try to load quota
619 	 * defaults.  Quotacheck will soon reset the entire quota file
620 	 * (including the root dquot) anyway, but don't log scary corruption
621 	 * reports to dmesg.
622 	 */
623 	return ddqp_type == XFS_DQTYPE_GROUP || ddqp_type == XFS_DQTYPE_PROJ;
624 }
625 
626 /* Copy the in-core quota fields in from the on-disk buffer. */
627 STATIC int
628 xfs_dquot_from_disk(
629 	struct xfs_dquot	*dqp,
630 	struct xfs_buf		*bp)
631 {
632 	struct xfs_dqblk	*dqb = xfs_buf_offset(bp, dqp->q_bufoffset);
633 	struct xfs_disk_dquot	*ddqp = &dqb->dd_diskdq;
634 
635 	/*
636 	 * Ensure that we got the type and ID we were looking for.
637 	 * Everything else was checked by the dquot buffer verifier.
638 	 */
639 	if (!xfs_dquot_check_type(dqp, ddqp)) {
640 		xfs_alert_tag(bp->b_mount, XFS_PTAG_VERIFIER_ERROR,
641 			  "Metadata corruption detected at %pS, quota %u",
642 			  __this_address, dqp->q_id);
643 		xfs_alert(bp->b_mount, "Unmount and run xfs_repair");
644 		xfs_dquot_mark_sick(dqp);
645 		return -EFSCORRUPTED;
646 	}
647 
648 	/* copy everything from disk dquot to the incore dquot */
649 	dqp->q_type = ddqp->d_type;
650 	dqp->q_blk.hardlimit = be64_to_cpu(ddqp->d_blk_hardlimit);
651 	dqp->q_blk.softlimit = be64_to_cpu(ddqp->d_blk_softlimit);
652 	dqp->q_ino.hardlimit = be64_to_cpu(ddqp->d_ino_hardlimit);
653 	dqp->q_ino.softlimit = be64_to_cpu(ddqp->d_ino_softlimit);
654 	dqp->q_rtb.hardlimit = be64_to_cpu(ddqp->d_rtb_hardlimit);
655 	dqp->q_rtb.softlimit = be64_to_cpu(ddqp->d_rtb_softlimit);
656 
657 	dqp->q_blk.count = be64_to_cpu(ddqp->d_bcount);
658 	dqp->q_ino.count = be64_to_cpu(ddqp->d_icount);
659 	dqp->q_rtb.count = be64_to_cpu(ddqp->d_rtbcount);
660 
661 	dqp->q_blk.timer = xfs_dquot_from_disk_ts(ddqp, ddqp->d_btimer);
662 	dqp->q_ino.timer = xfs_dquot_from_disk_ts(ddqp, ddqp->d_itimer);
663 	dqp->q_rtb.timer = xfs_dquot_from_disk_ts(ddqp, ddqp->d_rtbtimer);
664 
665 	/*
666 	 * Reservation counters are defined as reservation plus current usage
667 	 * to avoid having to add every time.
668 	 */
669 	dqp->q_blk.reserved = dqp->q_blk.count;
670 	dqp->q_ino.reserved = dqp->q_ino.count;
671 	dqp->q_rtb.reserved = dqp->q_rtb.count;
672 
673 	/* initialize the dquot speculative prealloc thresholds */
674 	xfs_dquot_set_prealloc_limits(dqp);
675 	return 0;
676 }
677 
678 /* Copy the in-core quota fields into the on-disk buffer. */
679 void
680 xfs_dquot_to_disk(
681 	struct xfs_disk_dquot	*ddqp,
682 	struct xfs_dquot	*dqp)
683 {
684 	ddqp->d_magic = cpu_to_be16(XFS_DQUOT_MAGIC);
685 	ddqp->d_version = XFS_DQUOT_VERSION;
686 	ddqp->d_type = dqp->q_type;
687 	ddqp->d_id = cpu_to_be32(dqp->q_id);
688 	ddqp->d_pad0 = 0;
689 	ddqp->d_pad = 0;
690 
691 	ddqp->d_blk_hardlimit = cpu_to_be64(dqp->q_blk.hardlimit);
692 	ddqp->d_blk_softlimit = cpu_to_be64(dqp->q_blk.softlimit);
693 	ddqp->d_ino_hardlimit = cpu_to_be64(dqp->q_ino.hardlimit);
694 	ddqp->d_ino_softlimit = cpu_to_be64(dqp->q_ino.softlimit);
695 	ddqp->d_rtb_hardlimit = cpu_to_be64(dqp->q_rtb.hardlimit);
696 	ddqp->d_rtb_softlimit = cpu_to_be64(dqp->q_rtb.softlimit);
697 
698 	ddqp->d_bcount = cpu_to_be64(dqp->q_blk.count);
699 	ddqp->d_icount = cpu_to_be64(dqp->q_ino.count);
700 	ddqp->d_rtbcount = cpu_to_be64(dqp->q_rtb.count);
701 
702 	ddqp->d_bwarns = 0;
703 	ddqp->d_iwarns = 0;
704 	ddqp->d_rtbwarns = 0;
705 
706 	ddqp->d_btimer = xfs_dquot_to_disk_ts(dqp, dqp->q_blk.timer);
707 	ddqp->d_itimer = xfs_dquot_to_disk_ts(dqp, dqp->q_ino.timer);
708 	ddqp->d_rtbtimer = xfs_dquot_to_disk_ts(dqp, dqp->q_rtb.timer);
709 }
710 
711 /*
712  * Read in the ondisk dquot using dqtobp() then copy it to an incore version,
713  * and release the buffer immediately.  If @can_alloc is true, fill any
714  * holes in the on-disk metadata.
715  */
716 static int
717 xfs_qm_dqread(
718 	struct xfs_mount	*mp,
719 	xfs_dqid_t		id,
720 	xfs_dqtype_t		type,
721 	bool			can_alloc,
722 	struct xfs_dquot	**dqpp)
723 {
724 	struct xfs_dquot	*dqp;
725 	struct xfs_buf		*bp;
726 	int			error;
727 
728 	dqp = xfs_dquot_alloc(mp, id, type);
729 	trace_xfs_dqread(dqp);
730 
731 	/* Try to read the buffer, allocating if necessary. */
732 	error = xfs_dquot_disk_read(mp, dqp, &bp);
733 	if (error == -ENOENT && can_alloc)
734 		error = xfs_dquot_disk_alloc(dqp, &bp);
735 	if (error)
736 		goto err;
737 
738 	/*
739 	 * At this point we should have a clean locked buffer.  Copy the data
740 	 * to the incore dquot and release the buffer since the incore dquot
741 	 * has its own locking protocol so we needn't tie up the buffer any
742 	 * further.
743 	 */
744 	ASSERT(xfs_buf_islocked(bp));
745 	error = xfs_dquot_from_disk(dqp, bp);
746 	xfs_buf_relse(bp);
747 	if (error)
748 		goto err;
749 
750 	*dqpp = dqp;
751 	return error;
752 
753 err:
754 	trace_xfs_dqread_fail(dqp);
755 	xfs_qm_dqdestroy(dqp);
756 	*dqpp = NULL;
757 	return error;
758 }
759 
760 /*
761  * Advance to the next id in the current chunk, or if at the
762  * end of the chunk, skip ahead to first id in next allocated chunk
763  * using the SEEK_DATA interface.
764  */
765 static int
766 xfs_dq_get_next_id(
767 	struct xfs_mount	*mp,
768 	xfs_dqtype_t		type,
769 	xfs_dqid_t		*id)
770 {
771 	struct xfs_inode	*quotip = xfs_quota_inode(mp, type);
772 	xfs_dqid_t		next_id = *id + 1; /* simple advance */
773 	uint			lock_flags;
774 	struct xfs_bmbt_irec	got;
775 	struct xfs_iext_cursor	cur;
776 	xfs_fsblock_t		start;
777 	int			error = 0;
778 
779 	/* If we'd wrap past the max ID, stop */
780 	if (next_id < *id)
781 		return -ENOENT;
782 
783 	/* If new ID is within the current chunk, advancing it sufficed */
784 	if (next_id % mp->m_quotainfo->qi_dqperchunk) {
785 		*id = next_id;
786 		return 0;
787 	}
788 
789 	/* Nope, next_id is now past the current chunk, so find the next one */
790 	start = (xfs_fsblock_t)next_id / mp->m_quotainfo->qi_dqperchunk;
791 
792 	lock_flags = xfs_ilock_data_map_shared(quotip);
793 	error = xfs_iread_extents(NULL, quotip, XFS_DATA_FORK);
794 	if (error)
795 		goto out_unlock;
796 
797 	if (xfs_iext_lookup_extent(quotip, &quotip->i_df, start, &cur, &got)) {
798 		/* contiguous chunk, bump startoff for the id calculation */
799 		if (got.br_startoff < start)
800 			got.br_startoff = start;
801 		*id = got.br_startoff * mp->m_quotainfo->qi_dqperchunk;
802 	} else {
803 		error = -ENOENT;
804 	}
805 
806 out_unlock:
807 	xfs_iunlock(quotip, lock_flags);
808 
809 	return error;
810 }
811 
812 /*
813  * Look up the dquot in the in-core cache.  If found, the dquot is returned
814  * locked and ready to go.
815  */
816 static struct xfs_dquot *
817 xfs_qm_dqget_cache_lookup(
818 	struct xfs_mount	*mp,
819 	xfs_dqid_t		id,
820 	xfs_dqtype_t		type)
821 {
822 	struct xfs_quotainfo	*qi = mp->m_quotainfo;
823 	struct radix_tree_root	*tree = xfs_dquot_tree(qi, type);
824 	struct xfs_dquot	*dqp;
825 
826 restart:
827 	mutex_lock(&qi->qi_tree_lock);
828 	dqp = radix_tree_lookup(tree, id);
829 	if (!dqp) {
830 		mutex_unlock(&qi->qi_tree_lock);
831 		XFS_STATS_INC(mp, xs_qm_dqcachemisses);
832 		return NULL;
833 	}
834 
835 	if (!lockref_get_not_dead(&dqp->q_lockref)) {
836 		mutex_unlock(&qi->qi_tree_lock);
837 		trace_xfs_dqget_freeing(dqp);
838 		delay(1);
839 		goto restart;
840 	}
841 	mutex_unlock(&qi->qi_tree_lock);
842 
843 	trace_xfs_dqget_hit(dqp);
844 	XFS_STATS_INC(mp, xs_qm_dqcachehits);
845 	return dqp;
846 }
847 
848 /*
849  * Try to insert a new dquot into the in-core cache.  If an error occurs the
850  * caller should throw away the dquot and start over.  Otherwise, the dquot
851  * is returned (and held by the cache) as if there had been a cache hit.
852  *
853  * The insert needs to be done under memalloc_nofs context because the radix
854  * tree can do memory allocation during insert. The qi->qi_tree_lock is taken in
855  * memory reclaim when freeing unused dquots, so we cannot have the radix tree
856  * node allocation recursing into filesystem reclaim whilst we hold the
857  * qi_tree_lock.
858  */
859 static int
860 xfs_qm_dqget_cache_insert(
861 	struct xfs_mount	*mp,
862 	xfs_dqid_t		id,
863 	xfs_dqtype_t		type,
864 	struct xfs_dquot	*dqp)
865 {
866 	struct xfs_quotainfo	*qi = mp->m_quotainfo;
867 	struct radix_tree_root	*tree = xfs_dquot_tree(qi, type);
868 	unsigned int		nofs_flags;
869 	int			error;
870 
871 	nofs_flags = memalloc_nofs_save();
872 	mutex_lock(&qi->qi_tree_lock);
873 	error = radix_tree_insert(tree, id, dqp);
874 	if (unlikely(error)) {
875 		trace_xfs_dqget_dup(dqp);
876 		goto out_unlock;
877 	}
878 
879 	lockref_init(&dqp->q_lockref);
880 	qi->qi_dquots++;
881 
882 out_unlock:
883 	mutex_unlock(&qi->qi_tree_lock);
884 	memalloc_nofs_restore(nofs_flags);
885 	return error;
886 }
887 
888 /* Check our input parameters. */
889 static int
890 xfs_qm_dqget_checks(
891 	struct xfs_mount	*mp,
892 	xfs_dqtype_t		type)
893 {
894 	switch (type) {
895 	case XFS_DQTYPE_USER:
896 		if (!XFS_IS_UQUOTA_ON(mp))
897 			return -ESRCH;
898 		return 0;
899 	case XFS_DQTYPE_GROUP:
900 		if (!XFS_IS_GQUOTA_ON(mp))
901 			return -ESRCH;
902 		return 0;
903 	case XFS_DQTYPE_PROJ:
904 		if (!XFS_IS_PQUOTA_ON(mp))
905 			return -ESRCH;
906 		return 0;
907 	default:
908 		WARN_ON_ONCE(0);
909 		return -EINVAL;
910 	}
911 }
912 
913 /*
914  * Given the file system, id, and type (UDQUOT/GDQUOT/PDQUOT), return a
915  * dquot, doing an allocation (if requested) as needed.
916  */
917 int
918 xfs_qm_dqget(
919 	struct xfs_mount	*mp,
920 	xfs_dqid_t		id,
921 	xfs_dqtype_t		type,
922 	bool			can_alloc,
923 	struct xfs_dquot	**O_dqpp)
924 {
925 	struct xfs_dquot	*dqp;
926 	int			error;
927 
928 	error = xfs_qm_dqget_checks(mp, type);
929 	if (error)
930 		return error;
931 
932 restart:
933 	dqp = xfs_qm_dqget_cache_lookup(mp, id, type);
934 	if (dqp)
935 		goto found;
936 
937 	error = xfs_qm_dqread(mp, id, type, can_alloc, &dqp);
938 	if (error)
939 		return error;
940 
941 	error = xfs_qm_dqget_cache_insert(mp, id, type, dqp);
942 	if (error) {
943 		xfs_qm_dqdestroy(dqp);
944 		if (error == -EEXIST) {
945 			/*
946 			 * Duplicate found. Just throw away the new dquot and
947 			 * start over.
948 			 */
949 			XFS_STATS_INC(mp, xs_qm_dquot_dups);
950 			goto restart;
951 		}
952 		return error;
953 	}
954 
955 	trace_xfs_dqget_miss(dqp);
956 found:
957 	*O_dqpp = dqp;
958 	return 0;
959 }
960 
961 /*
962  * Given a dquot id and type, read and initialize a dquot from the on-disk
963  * metadata.  This function is only for use during quota initialization so
964  * it ignores the dquot cache assuming that the dquot shrinker isn't set up.
965  * The caller is responsible for _qm_dqdestroy'ing the returned dquot.
966  */
967 int
968 xfs_qm_dqget_uncached(
969 	struct xfs_mount	*mp,
970 	xfs_dqid_t		id,
971 	xfs_dqtype_t		type,
972 	struct xfs_dquot	**dqpp)
973 {
974 	int			error;
975 
976 	error = xfs_qm_dqget_checks(mp, type);
977 	if (error)
978 		return error;
979 
980 	return xfs_qm_dqread(mp, id, type, 0, dqpp);
981 }
982 
983 /* Return the quota id for a given inode and type. */
984 xfs_dqid_t
985 xfs_qm_id_for_quotatype(
986 	struct xfs_inode	*ip,
987 	xfs_dqtype_t		type)
988 {
989 	switch (type) {
990 	case XFS_DQTYPE_USER:
991 		return i_uid_read(VFS_I(ip));
992 	case XFS_DQTYPE_GROUP:
993 		return i_gid_read(VFS_I(ip));
994 	case XFS_DQTYPE_PROJ:
995 		return ip->i_projid;
996 	}
997 	ASSERT(0);
998 	return 0;
999 }
1000 
1001 /*
1002  * Return the dquot for a given inode and type.  If @can_alloc is true, then
1003  * allocate blocks if needed.  The inode's ILOCK must be held and it must not
1004  * have already had an inode attached.
1005  */
1006 int
1007 xfs_qm_dqget_inode(
1008 	struct xfs_inode	*ip,
1009 	xfs_dqtype_t		type,
1010 	bool			can_alloc,
1011 	struct xfs_dquot	**dqpp)
1012 {
1013 	struct xfs_mount	*mp = ip->i_mount;
1014 	struct xfs_dquot	*dqp;
1015 	xfs_dqid_t		id;
1016 	int			error;
1017 
1018 	ASSERT(!*dqpp);
1019 	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
1020 
1021 	error = xfs_qm_dqget_checks(mp, type);
1022 	if (error)
1023 		return error;
1024 
1025 	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
1026 	ASSERT(xfs_inode_dquot(ip, type) == NULL);
1027 	ASSERT(!xfs_is_metadir_inode(ip));
1028 
1029 	id = xfs_qm_id_for_quotatype(ip, type);
1030 
1031 restart:
1032 	dqp = xfs_qm_dqget_cache_lookup(mp, id, type);
1033 	if (dqp)
1034 		goto found;
1035 
1036 	/*
1037 	 * Dquot cache miss. We don't want to keep the inode lock across
1038 	 * a (potential) disk read. Also we don't want to deal with the lock
1039 	 * ordering between quotainode and this inode. OTOH, dropping the inode
1040 	 * lock here means dealing with a chown that can happen before
1041 	 * we re-acquire the lock.
1042 	 */
1043 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1044 	error = xfs_qm_dqread(mp, id, type, can_alloc, &dqp);
1045 	xfs_ilock(ip, XFS_ILOCK_EXCL);
1046 	if (error)
1047 		return error;
1048 
1049 	/*
1050 	 * A dquot could be attached to this inode by now, since we had
1051 	 * dropped the ilock.
1052 	 */
1053 	if (xfs_this_quota_on(mp, type)) {
1054 		struct xfs_dquot	*dqp1;
1055 
1056 		dqp1 = xfs_inode_dquot(ip, type);
1057 		if (dqp1) {
1058 			xfs_qm_dqdestroy(dqp);
1059 			dqp = dqp1;
1060 			goto dqret;
1061 		}
1062 	} else {
1063 		/* inode stays locked on return */
1064 		xfs_qm_dqdestroy(dqp);
1065 		return -ESRCH;
1066 	}
1067 
1068 	error = xfs_qm_dqget_cache_insert(mp, id, type, dqp);
1069 	if (error) {
1070 		xfs_qm_dqdestroy(dqp);
1071 		if (error == -EEXIST) {
1072 			/*
1073 			 * Duplicate found. Just throw away the new dquot and
1074 			 * start over.
1075 			 */
1076 			XFS_STATS_INC(mp, xs_qm_dquot_dups);
1077 			goto restart;
1078 		}
1079 		return error;
1080 	}
1081 
1082 dqret:
1083 	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
1084 	trace_xfs_dqget_miss(dqp);
1085 found:
1086 	trace_xfs_dqattach_get(dqp);
1087 	*dqpp = dqp;
1088 	return 0;
1089 }
1090 
1091 /*
1092  * Starting at @id and progressing upwards, look for an initialized incore
1093  * dquot, lock it, and return it.
1094  */
1095 int
1096 xfs_qm_dqget_next(
1097 	struct xfs_mount	*mp,
1098 	xfs_dqid_t		id,
1099 	xfs_dqtype_t		type,
1100 	struct xfs_dquot	**dqpp)
1101 {
1102 	struct xfs_dquot	*dqp;
1103 	int			error = 0;
1104 
1105 	*dqpp = NULL;
1106 	for (; !error; error = xfs_dq_get_next_id(mp, type, &id)) {
1107 		error = xfs_qm_dqget(mp, id, type, false, &dqp);
1108 		if (error == -ENOENT)
1109 			continue;
1110 		else if (error != 0)
1111 			break;
1112 
1113 		mutex_lock(&dqp->q_qlock);
1114 		if (!XFS_IS_DQUOT_UNINITIALIZED(dqp)) {
1115 			*dqpp = dqp;
1116 			return 0;
1117 		}
1118 
1119 		mutex_unlock(&dqp->q_qlock);
1120 		xfs_qm_dqrele(dqp);
1121 	}
1122 
1123 	return error;
1124 }
1125 
1126 /*
1127  * Release a reference to the dquot.
1128  */
1129 void
1130 xfs_qm_dqrele(
1131 	struct xfs_dquot	*dqp)
1132 {
1133 	if (!dqp)
1134 		return;
1135 
1136 	trace_xfs_dqrele(dqp);
1137 
1138 	if (lockref_put_or_lock(&dqp->q_lockref))
1139 		return;
1140 	if (!--dqp->q_lockref.count) {
1141 		struct xfs_quotainfo	*qi = dqp->q_mount->m_quotainfo;
1142 
1143 		trace_xfs_dqrele_free(dqp);
1144 		if (list_lru_add_obj(&qi->qi_lru, &dqp->q_lru))
1145 			XFS_STATS_INC(dqp->q_mount, xs_qm_dquot_unused);
1146 	}
1147 	spin_unlock(&dqp->q_lockref.lock);
1148 }
1149 
1150 /*
1151  * This is the dquot flushing I/O completion routine.  It is called
1152  * from interrupt level when the buffer containing the dquot is
1153  * flushed to disk.  It is responsible for removing the dquot logitem
1154  * from the AIL if it has not been re-logged, and unlocking the dquot's
1155  * flush lock. This behavior is very similar to that of inodes..
1156  */
1157 static void
1158 xfs_qm_dqflush_done(
1159 	struct xfs_log_item	*lip)
1160 {
1161 	struct xfs_dq_logitem	*qlip =
1162 			container_of(lip, struct xfs_dq_logitem, qli_item);
1163 	struct xfs_dquot	*dqp = qlip->qli_dquot;
1164 	struct xfs_ail		*ailp = lip->li_ailp;
1165 	struct xfs_buf		*bp = NULL;
1166 	xfs_lsn_t		tail_lsn;
1167 
1168 	/*
1169 	 * We only want to pull the item from the AIL if its
1170 	 * location in the log has not changed since we started the flush.
1171 	 * Thus, we only bother if the dquot's lsn has
1172 	 * not changed. First we check the lsn outside the lock
1173 	 * since it's cheaper, and then we recheck while
1174 	 * holding the lock before removing the dquot from the AIL.
1175 	 */
1176 	if (test_bit(XFS_LI_IN_AIL, &lip->li_flags) &&
1177 	    (lip->li_lsn == qlip->qli_flush_lsn ||
1178 	     test_bit(XFS_LI_FAILED, &lip->li_flags))) {
1179 		spin_lock(&ailp->ail_lock);
1180 		clear_bit(XFS_LI_FAILED, &lip->li_flags);
1181 		if (lip->li_lsn == qlip->qli_flush_lsn) {
1182 			/* xfs_ail_update_finish() drops the AIL lock */
1183 			tail_lsn = xfs_ail_delete_one(ailp, lip);
1184 			xfs_ail_update_finish(ailp, tail_lsn);
1185 		} else {
1186 			spin_unlock(&ailp->ail_lock);
1187 		}
1188 	}
1189 
1190 	/*
1191 	 * If this dquot hasn't been dirtied since initiating the last dqflush,
1192 	 * release the buffer reference.  We already unlinked this dquot item
1193 	 * from the buffer.
1194 	 */
1195 	spin_lock(&qlip->qli_lock);
1196 	if (!qlip->qli_dirty) {
1197 		bp = lip->li_buf;
1198 		lip->li_buf = NULL;
1199 	}
1200 	spin_unlock(&qlip->qli_lock);
1201 	if (bp)
1202 		xfs_buf_rele(bp);
1203 
1204 	/*
1205 	 * Release the dq's flush lock since we're done with it.
1206 	 */
1207 	xfs_dqfunlock(dqp);
1208 }
1209 
1210 void
1211 xfs_buf_dquot_iodone(
1212 	struct xfs_buf		*bp)
1213 {
1214 	struct xfs_log_item	*lip, *n;
1215 
1216 	list_for_each_entry_safe(lip, n, &bp->b_li_list, li_bio_list) {
1217 		list_del_init(&lip->li_bio_list);
1218 		xfs_qm_dqflush_done(lip);
1219 	}
1220 }
1221 
1222 /* Check incore dquot for errors before we flush. */
1223 static xfs_failaddr_t
1224 xfs_qm_dqflush_check(
1225 	struct xfs_dquot	*dqp)
1226 {
1227 	xfs_dqtype_t		type = xfs_dquot_type(dqp);
1228 
1229 	if (type != XFS_DQTYPE_USER &&
1230 	    type != XFS_DQTYPE_GROUP &&
1231 	    type != XFS_DQTYPE_PROJ)
1232 		return __this_address;
1233 
1234 	/* bigtime flag should never be set on root dquots */
1235 	if (dqp->q_type & XFS_DQTYPE_BIGTIME) {
1236 		if (!xfs_has_bigtime(dqp->q_mount))
1237 			return __this_address;
1238 		if (dqp->q_id == 0)
1239 			return __this_address;
1240 	}
1241 
1242 	if (dqp->q_id == 0)
1243 		return NULL;
1244 
1245 	if (dqp->q_blk.softlimit && dqp->q_blk.count > dqp->q_blk.softlimit &&
1246 	    !dqp->q_blk.timer)
1247 		return __this_address;
1248 
1249 	if (dqp->q_ino.softlimit && dqp->q_ino.count > dqp->q_ino.softlimit &&
1250 	    !dqp->q_ino.timer)
1251 		return __this_address;
1252 
1253 	if (dqp->q_rtb.softlimit && dqp->q_rtb.count > dqp->q_rtb.softlimit &&
1254 	    !dqp->q_rtb.timer)
1255 		return __this_address;
1256 
1257 	return NULL;
1258 }
1259 
1260 /*
1261  * Get the buffer containing the on-disk dquot.
1262  *
1263  * Requires dquot flush lock, will clear the dirty flag, delete the quota log
1264  * item from the AIL, and shut down the system if something goes wrong.
1265  */
1266 static int
1267 xfs_dquot_read_buf(
1268 	struct xfs_trans	*tp,
1269 	struct xfs_dquot	*dqp,
1270 	struct xfs_buf		**bpp)
1271 {
1272 	struct xfs_mount	*mp = dqp->q_mount;
1273 	struct xfs_buf		*bp = NULL;
1274 	int			error;
1275 
1276 	error = xfs_trans_read_buf(mp, tp, mp->m_ddev_targp, dqp->q_blkno,
1277 				   mp->m_quotainfo->qi_dqchunklen, 0,
1278 				   &bp, &xfs_dquot_buf_ops);
1279 	if (xfs_metadata_is_sick(error))
1280 		xfs_dquot_mark_sick(dqp);
1281 	if (error)
1282 		goto out_abort;
1283 
1284 	*bpp = bp;
1285 	return 0;
1286 
1287 out_abort:
1288 	dqp->q_flags &= ~XFS_DQFLAG_DIRTY;
1289 	xfs_trans_ail_delete(&dqp->q_logitem.qli_item, 0);
1290 	xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
1291 	return error;
1292 }
1293 
1294 /*
1295  * Attach a dquot buffer to this dquot to avoid allocating a buffer during a
1296  * dqflush, since dqflush can be called from reclaim context.  Caller must hold
1297  * the dqlock.
1298  */
1299 int
1300 xfs_dquot_attach_buf(
1301 	struct xfs_trans	*tp,
1302 	struct xfs_dquot	*dqp)
1303 {
1304 	struct xfs_dq_logitem	*qlip = &dqp->q_logitem;
1305 	struct xfs_log_item	*lip = &qlip->qli_item;
1306 	int			error;
1307 
1308 	spin_lock(&qlip->qli_lock);
1309 	if (!lip->li_buf) {
1310 		struct xfs_buf	*bp = NULL;
1311 
1312 		spin_unlock(&qlip->qli_lock);
1313 		error = xfs_dquot_read_buf(tp, dqp, &bp);
1314 		if (error)
1315 			return error;
1316 
1317 		/*
1318 		 * Hold the dquot buffer so that we retain our ref to it after
1319 		 * detaching it from the transaction, then give that ref to the
1320 		 * dquot log item so that the AIL does not have to read the
1321 		 * dquot buffer to push this item.
1322 		 */
1323 		xfs_buf_hold(bp);
1324 		xfs_trans_brelse(tp, bp);
1325 
1326 		spin_lock(&qlip->qli_lock);
1327 		lip->li_buf = bp;
1328 	}
1329 	qlip->qli_dirty = true;
1330 	spin_unlock(&qlip->qli_lock);
1331 
1332 	return 0;
1333 }
1334 
1335 /*
1336  * Get a new reference the dquot buffer attached to this dquot for a dqflush
1337  * operation.
1338  *
1339  * Returns 0 and a NULL bp if none was attached to the dquot; 0 and a locked
1340  * bp; or -EAGAIN if the buffer could not be locked.
1341  */
1342 int
1343 xfs_dquot_use_attached_buf(
1344 	struct xfs_dquot	*dqp,
1345 	struct xfs_buf		**bpp)
1346 {
1347 	struct xfs_buf		*bp = dqp->q_logitem.qli_item.li_buf;
1348 
1349 	/*
1350 	 * A NULL buffer can happen if the dquot dirty flag was set but the
1351 	 * filesystem shut down before transaction commit happened.  In that
1352 	 * case we're not going to flush anyway.
1353 	 */
1354 	if (!bp) {
1355 		ASSERT(xfs_is_shutdown(dqp->q_mount));
1356 
1357 		*bpp = NULL;
1358 		return 0;
1359 	}
1360 
1361 	if (!xfs_buf_trylock(bp))
1362 		return -EAGAIN;
1363 
1364 	xfs_buf_hold(bp);
1365 	*bpp = bp;
1366 	return 0;
1367 }
1368 
1369 /*
1370  * Write a modified dquot to disk.
1371  * The dquot must be locked and the flush lock too taken by caller.
1372  * The flush lock will not be unlocked until the dquot reaches the disk,
1373  * but the dquot is free to be unlocked and modified by the caller
1374  * in the interim. Dquot is still locked on return. This behavior is
1375  * identical to that of inodes.
1376  */
1377 int
1378 xfs_qm_dqflush(
1379 	struct xfs_dquot	*dqp,
1380 	struct xfs_buf		*bp)
1381 {
1382 	struct xfs_mount	*mp = dqp->q_mount;
1383 	struct xfs_dq_logitem	*qlip = &dqp->q_logitem;
1384 	struct xfs_log_item	*lip = &qlip->qli_item;
1385 	struct xfs_dqblk	*dqblk;
1386 	xfs_failaddr_t		fa;
1387 	int			error;
1388 
1389 	ASSERT(XFS_DQ_IS_LOCKED(dqp));
1390 	ASSERT(!completion_done(&dqp->q_flush));
1391 	ASSERT(atomic_read(&dqp->q_pincount) == 0);
1392 
1393 	trace_xfs_dqflush(dqp);
1394 	fa = xfs_qm_dqflush_check(dqp);
1395 	if (fa) {
1396 		xfs_alert(mp, "corrupt dquot ID 0x%x in memory at %pS",
1397 				dqp->q_id, fa);
1398 		xfs_dquot_mark_sick(dqp);
1399 		error = -EFSCORRUPTED;
1400 		goto out_abort;
1401 	}
1402 
1403 	/* Flush the incore dquot to the ondisk buffer. */
1404 	dqblk = xfs_buf_offset(bp, dqp->q_bufoffset);
1405 	xfs_dquot_to_disk(&dqblk->dd_diskdq, dqp);
1406 
1407 	/*
1408 	 * Clear the dirty field and remember the flush lsn for later use.
1409 	 */
1410 	dqp->q_flags &= ~XFS_DQFLAG_DIRTY;
1411 
1412 	/*
1413 	 * We hold the dquot lock, so nobody can dirty it while we're
1414 	 * scheduling the write out.  Clear the dirty-since-flush flag.
1415 	 */
1416 	spin_lock(&qlip->qli_lock);
1417 	qlip->qli_dirty = false;
1418 	spin_unlock(&qlip->qli_lock);
1419 
1420 	xfs_trans_ail_copy_lsn(mp->m_ail, &qlip->qli_flush_lsn, &lip->li_lsn);
1421 
1422 	/*
1423 	 * copy the lsn into the on-disk dquot now while we have the in memory
1424 	 * dquot here. This can't be done later in the write verifier as we
1425 	 * can't get access to the log item at that point in time.
1426 	 *
1427 	 * We also calculate the CRC here so that the on-disk dquot in the
1428 	 * buffer always has a valid CRC. This ensures there is no possibility
1429 	 * of a dquot without an up-to-date CRC getting to disk.
1430 	 */
1431 	if (xfs_has_crc(mp)) {
1432 		dqblk->dd_lsn = cpu_to_be64(lip->li_lsn);
1433 		xfs_update_cksum((char *)dqblk, sizeof(struct xfs_dqblk),
1434 				 XFS_DQUOT_CRC_OFF);
1435 	}
1436 
1437 	/*
1438 	 * Attach the dquot to the buffer so that we can remove this dquot from
1439 	 * the AIL and release the flush lock once the dquot is synced to disk.
1440 	 */
1441 	bp->b_iodone = xfs_buf_dquot_iodone;
1442 	list_add_tail(&lip->li_bio_list, &bp->b_li_list);
1443 
1444 	/*
1445 	 * If the buffer is pinned then push on the log so we won't
1446 	 * get stuck waiting in the write for too long.
1447 	 */
1448 	if (xfs_buf_ispinned(bp)) {
1449 		trace_xfs_dqflush_force(dqp);
1450 		xfs_log_force(mp, 0);
1451 	}
1452 
1453 	trace_xfs_dqflush_done(dqp);
1454 	return 0;
1455 
1456 out_abort:
1457 	/*
1458 	 * Shut down the log before removing the dquot item from the AIL.
1459 	 * Otherwise, the log tail may advance past this item's LSN while
1460 	 * log writes are still in progress, making these unflushed changes
1461 	 * unrecoverable on the next mount.
1462 	 */
1463 	xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
1464 	dqp->q_flags &= ~XFS_DQFLAG_DIRTY;
1465 	xfs_trans_ail_delete(lip, 0);
1466 	xfs_dqfunlock(dqp);
1467 	return error;
1468 }
1469 
1470 /*
1471  * Lock two xfs_dquot structures.
1472  *
1473  * To avoid deadlocks we always lock the quota structure with
1474  * the lowerd id first.
1475  */
1476 void
1477 xfs_dqlock2(
1478 	struct xfs_dquot	*d1,
1479 	struct xfs_dquot	*d2)
1480 {
1481 	if (d1 && d2) {
1482 		ASSERT(d1 != d2);
1483 		if (d1->q_id > d2->q_id) {
1484 			mutex_lock(&d2->q_qlock);
1485 			mutex_lock_nested(&d1->q_qlock, XFS_QLOCK_NESTED);
1486 		} else {
1487 			mutex_lock(&d1->q_qlock);
1488 			mutex_lock_nested(&d2->q_qlock, XFS_QLOCK_NESTED);
1489 		}
1490 	} else if (d1) {
1491 		mutex_lock(&d1->q_qlock);
1492 	} else if (d2) {
1493 		mutex_lock(&d2->q_qlock);
1494 	}
1495 }
1496 
1497 static int
1498 xfs_dqtrx_cmp(
1499 	const void		*a,
1500 	const void		*b)
1501 {
1502 	const struct xfs_dqtrx	*qa = a;
1503 	const struct xfs_dqtrx	*qb = b;
1504 
1505 	if (qa->qt_dquot->q_id > qb->qt_dquot->q_id)
1506 		return 1;
1507 	if (qa->qt_dquot->q_id < qb->qt_dquot->q_id)
1508 		return -1;
1509 	return 0;
1510 }
1511 
1512 void
1513 xfs_dqlockn(
1514 	struct xfs_dqtrx	*q)
1515 {
1516 	unsigned int		i;
1517 
1518 	BUILD_BUG_ON(XFS_QM_TRANS_MAXDQS > MAX_LOCKDEP_SUBCLASSES);
1519 
1520 	/* Sort in order of dquot id, do not allow duplicates */
1521 	for (i = 0; i < XFS_QM_TRANS_MAXDQS && q[i].qt_dquot != NULL; i++) {
1522 		unsigned int	j;
1523 
1524 		for (j = 0; j < i; j++)
1525 			ASSERT(q[i].qt_dquot != q[j].qt_dquot);
1526 	}
1527 	if (i == 0)
1528 		return;
1529 
1530 	sort(q, i, sizeof(struct xfs_dqtrx), xfs_dqtrx_cmp, NULL);
1531 
1532 	mutex_lock(&q[0].qt_dquot->q_qlock);
1533 	for (i = 1; i < XFS_QM_TRANS_MAXDQS && q[i].qt_dquot != NULL; i++)
1534 		mutex_lock_nested(&q[i].qt_dquot->q_qlock,
1535 				XFS_QLOCK_NESTED + i - 1);
1536 }
1537 
1538 int __init
1539 xfs_qm_init(void)
1540 {
1541 	xfs_dquot_cache = kmem_cache_create("xfs_dquot",
1542 					  sizeof(struct xfs_dquot),
1543 					  0, 0, NULL);
1544 	if (!xfs_dquot_cache)
1545 		goto out;
1546 
1547 	xfs_dqtrx_cache = kmem_cache_create("xfs_dqtrx",
1548 					     sizeof(struct xfs_dquot_acct),
1549 					     0, 0, NULL);
1550 	if (!xfs_dqtrx_cache)
1551 		goto out_free_dquot_cache;
1552 
1553 	return 0;
1554 
1555 out_free_dquot_cache:
1556 	kmem_cache_destroy(xfs_dquot_cache);
1557 out:
1558 	return -ENOMEM;
1559 }
1560 
1561 void
1562 xfs_qm_exit(void)
1563 {
1564 	kmem_cache_destroy(xfs_dqtrx_cache);
1565 	kmem_cache_destroy(xfs_dquot_cache);
1566 }
1567