1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Module for pnfs flexfile layout driver.
4  *
5  * Copyright (c) 2014, Primary Data, Inc. All rights reserved.
6  *
7  * Tao Peng <bergwolf@primarydata.com>
8  */
9 
10 #include <linux/nfs_fs.h>
11 #include <linux/nfs_page.h>
12 #include <linux/module.h>
13 #include <linux/sched/mm.h>
14 
15 #include <linux/sunrpc/metrics.h>
16 
17 #include "flexfilelayout.h"
18 #include "../nfs4session.h"
19 #include "../nfs4idmap.h"
20 #include "../internal.h"
21 #include "../delegation.h"
22 #include "../nfs4trace.h"
23 #include "../iostat.h"
24 #include "../nfs.h"
25 #include "../nfs42.h"
26 
27 #define NFSDBG_FACILITY         NFSDBG_PNFS_LD
28 
29 #define FF_LAYOUT_POLL_RETRY_MAX     (15*HZ)
30 #define FF_LAYOUTRETURN_MAXERR 20
31 
32 static unsigned short io_maxretrans;
33 
34 static void ff_layout_read_record_layoutstats_done(struct rpc_task *task,
35 		struct nfs_pgio_header *hdr);
36 static int ff_layout_mirror_prepare_stats(struct pnfs_layout_hdr *lo,
37 			       struct nfs42_layoutstat_devinfo *devinfo,
38 			       int dev_limit);
39 static void ff_layout_encode_ff_layoutupdate(struct xdr_stream *xdr,
40 			      const struct nfs42_layoutstat_devinfo *devinfo,
41 			      struct nfs4_ff_layout_mirror *mirror);
42 
43 static struct pnfs_layout_hdr *
44 ff_layout_alloc_layout_hdr(struct inode *inode, gfp_t gfp_flags)
45 {
46 	struct nfs4_flexfile_layout *ffl;
47 
48 	ffl = kzalloc(sizeof(*ffl), gfp_flags);
49 	if (ffl) {
50 		INIT_LIST_HEAD(&ffl->error_list);
51 		INIT_LIST_HEAD(&ffl->mirrors);
52 		ffl->last_report_time = ktime_get();
53 		return &ffl->generic_hdr;
54 	} else
55 		return NULL;
56 }
57 
58 static void
59 ff_layout_free_layout_hdr(struct pnfs_layout_hdr *lo)
60 {
61 	struct nfs4_ff_layout_ds_err *err, *n;
62 
63 	list_for_each_entry_safe(err, n, &FF_LAYOUT_FROM_HDR(lo)->error_list,
64 				 list) {
65 		list_del(&err->list);
66 		kfree(err);
67 	}
68 	kfree(FF_LAYOUT_FROM_HDR(lo));
69 }
70 
71 static int decode_pnfs_stateid(struct xdr_stream *xdr, nfs4_stateid *stateid)
72 {
73 	__be32 *p;
74 
75 	p = xdr_inline_decode(xdr, NFS4_STATEID_SIZE);
76 	if (unlikely(p == NULL))
77 		return -ENOBUFS;
78 	stateid->type = NFS4_PNFS_DS_STATEID_TYPE;
79 	memcpy(stateid->data, p, NFS4_STATEID_SIZE);
80 	dprintk("%s: stateid id= [%x%x%x%x]\n", __func__,
81 		p[0], p[1], p[2], p[3]);
82 	return 0;
83 }
84 
85 static int decode_deviceid(struct xdr_stream *xdr, struct nfs4_deviceid *devid)
86 {
87 	__be32 *p;
88 
89 	p = xdr_inline_decode(xdr, NFS4_DEVICEID4_SIZE);
90 	if (unlikely(!p))
91 		return -ENOBUFS;
92 	memcpy(devid, p, NFS4_DEVICEID4_SIZE);
93 	nfs4_print_deviceid(devid);
94 	return 0;
95 }
96 
97 static int decode_nfs_fh(struct xdr_stream *xdr, struct nfs_fh *fh)
98 {
99 	__be32 *p;
100 
101 	p = xdr_inline_decode(xdr, 4);
102 	if (unlikely(!p))
103 		return -ENOBUFS;
104 	fh->size = be32_to_cpup(p++);
105 	if (fh->size > sizeof(struct nfs_fh)) {
106 		printk(KERN_ERR "NFS flexfiles: Too big fh received %d\n",
107 		       fh->size);
108 		return -EOVERFLOW;
109 	}
110 	/* fh.data */
111 	p = xdr_inline_decode(xdr, fh->size);
112 	if (unlikely(!p))
113 		return -ENOBUFS;
114 	memcpy(&fh->data, p, fh->size);
115 	dprintk("%s: fh len %d\n", __func__, fh->size);
116 
117 	return 0;
118 }
119 
120 /*
121  * Currently only stringified uids and gids are accepted.
122  * I.e., kerberos is not supported to the DSes, so no pricipals.
123  *
124  * That means that one common function will suffice, but when
125  * principals are added, this should be split to accomodate
126  * calls to both nfs_map_name_to_uid() and nfs_map_group_to_gid().
127  */
128 static int
129 decode_name(struct xdr_stream *xdr, u32 *id)
130 {
131 	__be32 *p;
132 	int len;
133 
134 	/* opaque_length(4)*/
135 	p = xdr_inline_decode(xdr, 4);
136 	if (unlikely(!p))
137 		return -ENOBUFS;
138 	len = be32_to_cpup(p++);
139 	if (len < 0)
140 		return -EINVAL;
141 
142 	dprintk("%s: len %u\n", __func__, len);
143 
144 	/* opaque body */
145 	p = xdr_inline_decode(xdr, len);
146 	if (unlikely(!p))
147 		return -ENOBUFS;
148 
149 	if (!nfs_map_string_to_numeric((char *)p, len, id))
150 		return -EINVAL;
151 
152 	return 0;
153 }
154 
155 static bool ff_mirror_match_fh(const struct nfs4_ff_layout_mirror *m1,
156 		const struct nfs4_ff_layout_mirror *m2)
157 {
158 	int i, j;
159 
160 	if (m1->fh_versions_cnt != m2->fh_versions_cnt)
161 		return false;
162 	for (i = 0; i < m1->fh_versions_cnt; i++) {
163 		bool found_fh = false;
164 		for (j = 0; j < m2->fh_versions_cnt; j++) {
165 			if (nfs_compare_fh(&m1->fh_versions[i],
166 					&m2->fh_versions[j]) == 0) {
167 				found_fh = true;
168 				break;
169 			}
170 		}
171 		if (!found_fh)
172 			return false;
173 	}
174 	return true;
175 }
176 
177 static struct nfs4_ff_layout_mirror *
178 ff_layout_add_mirror(struct pnfs_layout_hdr *lo,
179 		struct nfs4_ff_layout_mirror *mirror)
180 {
181 	struct nfs4_flexfile_layout *ff_layout = FF_LAYOUT_FROM_HDR(lo);
182 	struct nfs4_ff_layout_mirror *pos;
183 	struct inode *inode = lo->plh_inode;
184 
185 	spin_lock(&inode->i_lock);
186 	list_for_each_entry(pos, &ff_layout->mirrors, mirrors) {
187 		if (memcmp(&mirror->devid, &pos->devid, sizeof(pos->devid)) != 0)
188 			continue;
189 		if (!ff_mirror_match_fh(mirror, pos))
190 			continue;
191 		if (refcount_inc_not_zero(&pos->ref)) {
192 			spin_unlock(&inode->i_lock);
193 			return pos;
194 		}
195 	}
196 	list_add(&mirror->mirrors, &ff_layout->mirrors);
197 	mirror->layout = lo;
198 	spin_unlock(&inode->i_lock);
199 	return mirror;
200 }
201 
202 static void
203 ff_layout_remove_mirror(struct nfs4_ff_layout_mirror *mirror)
204 {
205 	struct inode *inode;
206 	if (mirror->layout == NULL)
207 		return;
208 	inode = mirror->layout->plh_inode;
209 	spin_lock(&inode->i_lock);
210 	list_del(&mirror->mirrors);
211 	spin_unlock(&inode->i_lock);
212 	mirror->layout = NULL;
213 }
214 
215 static struct nfs4_ff_layout_mirror *ff_layout_alloc_mirror(gfp_t gfp_flags)
216 {
217 	struct nfs4_ff_layout_mirror *mirror;
218 
219 	mirror = kzalloc(sizeof(*mirror), gfp_flags);
220 	if (mirror != NULL) {
221 		spin_lock_init(&mirror->lock);
222 		refcount_set(&mirror->ref, 1);
223 		INIT_LIST_HEAD(&mirror->mirrors);
224 	}
225 	return mirror;
226 }
227 
228 static void ff_layout_free_mirror(struct nfs4_ff_layout_mirror *mirror)
229 {
230 	const struct cred	*cred;
231 
232 	ff_layout_remove_mirror(mirror);
233 	kfree(mirror->fh_versions);
234 	cred = rcu_access_pointer(mirror->ro_cred);
235 	put_cred(cred);
236 	cred = rcu_access_pointer(mirror->rw_cred);
237 	put_cred(cred);
238 	nfs4_ff_layout_put_deviceid(mirror->mirror_ds);
239 	kfree(mirror);
240 }
241 
242 static void ff_layout_put_mirror(struct nfs4_ff_layout_mirror *mirror)
243 {
244 	if (mirror != NULL && refcount_dec_and_test(&mirror->ref))
245 		ff_layout_free_mirror(mirror);
246 }
247 
248 static void ff_layout_free_mirror_array(struct nfs4_ff_layout_segment *fls)
249 {
250 	int i;
251 
252 	if (fls->mirror_array) {
253 		for (i = 0; i < fls->mirror_array_cnt; i++) {
254 			/* normally mirror_ds is freed in
255 			 * .free_deviceid_node but we still do it here
256 			 * for .alloc_lseg error path */
257 			ff_layout_put_mirror(fls->mirror_array[i]);
258 		}
259 		kfree(fls->mirror_array);
260 		fls->mirror_array = NULL;
261 	}
262 }
263 
264 static int ff_layout_check_layout(struct nfs4_layoutget_res *lgr)
265 {
266 	int ret = 0;
267 
268 	dprintk("--> %s\n", __func__);
269 
270 	/* FIXME: remove this check when layout segment support is added */
271 	if (lgr->range.offset != 0 ||
272 	    lgr->range.length != NFS4_MAX_UINT64) {
273 		dprintk("%s Only whole file layouts supported. Use MDS i/o\n",
274 			__func__);
275 		ret = -EINVAL;
276 	}
277 
278 	dprintk("--> %s returns %d\n", __func__, ret);
279 	return ret;
280 }
281 
282 static void _ff_layout_free_lseg(struct nfs4_ff_layout_segment *fls)
283 {
284 	if (fls) {
285 		ff_layout_free_mirror_array(fls);
286 		kfree(fls);
287 	}
288 }
289 
290 static bool
291 ff_lseg_range_is_after(const struct pnfs_layout_range *l1,
292 		const struct pnfs_layout_range *l2)
293 {
294 	u64 end1, end2;
295 
296 	if (l1->iomode != l2->iomode)
297 		return l1->iomode != IOMODE_READ;
298 	end1 = pnfs_calc_offset_end(l1->offset, l1->length);
299 	end2 = pnfs_calc_offset_end(l2->offset, l2->length);
300 	if (end1 < l2->offset)
301 		return false;
302 	if (end2 < l1->offset)
303 		return true;
304 	return l2->offset <= l1->offset;
305 }
306 
307 static bool
308 ff_lseg_merge(struct pnfs_layout_segment *new,
309 		struct pnfs_layout_segment *old)
310 {
311 	u64 new_end, old_end;
312 
313 	if (test_bit(NFS_LSEG_LAYOUTRETURN, &old->pls_flags))
314 		return false;
315 	if (new->pls_range.iomode != old->pls_range.iomode)
316 		return false;
317 	old_end = pnfs_calc_offset_end(old->pls_range.offset,
318 			old->pls_range.length);
319 	if (old_end < new->pls_range.offset)
320 		return false;
321 	new_end = pnfs_calc_offset_end(new->pls_range.offset,
322 			new->pls_range.length);
323 	if (new_end < old->pls_range.offset)
324 		return false;
325 
326 	/* Mergeable: copy info from 'old' to 'new' */
327 	if (new_end < old_end)
328 		new_end = old_end;
329 	if (new->pls_range.offset < old->pls_range.offset)
330 		new->pls_range.offset = old->pls_range.offset;
331 	new->pls_range.length = pnfs_calc_offset_length(new->pls_range.offset,
332 			new_end);
333 	if (test_bit(NFS_LSEG_ROC, &old->pls_flags))
334 		set_bit(NFS_LSEG_ROC, &new->pls_flags);
335 	return true;
336 }
337 
338 static void
339 ff_layout_add_lseg(struct pnfs_layout_hdr *lo,
340 		struct pnfs_layout_segment *lseg,
341 		struct list_head *free_me)
342 {
343 	pnfs_generic_layout_insert_lseg(lo, lseg,
344 			ff_lseg_range_is_after,
345 			ff_lseg_merge,
346 			free_me);
347 }
348 
349 static void ff_layout_sort_mirrors(struct nfs4_ff_layout_segment *fls)
350 {
351 	int i, j;
352 
353 	for (i = 0; i < fls->mirror_array_cnt - 1; i++) {
354 		for (j = i + 1; j < fls->mirror_array_cnt; j++)
355 			if (fls->mirror_array[i]->efficiency <
356 			    fls->mirror_array[j]->efficiency)
357 				swap(fls->mirror_array[i],
358 				     fls->mirror_array[j]);
359 	}
360 }
361 
362 static struct pnfs_layout_segment *
363 ff_layout_alloc_lseg(struct pnfs_layout_hdr *lh,
364 		     struct nfs4_layoutget_res *lgr,
365 		     gfp_t gfp_flags)
366 {
367 	struct pnfs_layout_segment *ret;
368 	struct nfs4_ff_layout_segment *fls = NULL;
369 	struct xdr_stream stream;
370 	struct xdr_buf buf;
371 	struct page *scratch;
372 	u64 stripe_unit;
373 	u32 mirror_array_cnt;
374 	__be32 *p;
375 	int i, rc;
376 
377 	dprintk("--> %s\n", __func__);
378 	scratch = alloc_page(gfp_flags);
379 	if (!scratch)
380 		return ERR_PTR(-ENOMEM);
381 
382 	xdr_init_decode_pages(&stream, &buf, lgr->layoutp->pages,
383 			      lgr->layoutp->len);
384 	xdr_set_scratch_buffer(&stream, page_address(scratch), PAGE_SIZE);
385 
386 	/* stripe unit and mirror_array_cnt */
387 	rc = -EIO;
388 	p = xdr_inline_decode(&stream, 8 + 4);
389 	if (!p)
390 		goto out_err_free;
391 
392 	p = xdr_decode_hyper(p, &stripe_unit);
393 	mirror_array_cnt = be32_to_cpup(p++);
394 	dprintk("%s: stripe_unit=%llu mirror_array_cnt=%u\n", __func__,
395 		stripe_unit, mirror_array_cnt);
396 
397 	if (mirror_array_cnt > NFS4_FLEXFILE_LAYOUT_MAX_MIRROR_CNT ||
398 	    mirror_array_cnt == 0)
399 		goto out_err_free;
400 
401 	rc = -ENOMEM;
402 	fls = kzalloc(sizeof(*fls), gfp_flags);
403 	if (!fls)
404 		goto out_err_free;
405 
406 	fls->mirror_array_cnt = mirror_array_cnt;
407 	fls->stripe_unit = stripe_unit;
408 	fls->mirror_array = kcalloc(fls->mirror_array_cnt,
409 				    sizeof(fls->mirror_array[0]), gfp_flags);
410 	if (fls->mirror_array == NULL)
411 		goto out_err_free;
412 
413 	for (i = 0; i < fls->mirror_array_cnt; i++) {
414 		struct nfs4_ff_layout_mirror *mirror;
415 		struct cred *kcred;
416 		const struct cred __rcu *cred;
417 		kuid_t uid;
418 		kgid_t gid;
419 		u32 ds_count, fh_count, id;
420 		int j;
421 
422 		rc = -EIO;
423 		p = xdr_inline_decode(&stream, 4);
424 		if (!p)
425 			goto out_err_free;
426 		ds_count = be32_to_cpup(p);
427 
428 		/* FIXME: allow for striping? */
429 		if (ds_count != 1)
430 			goto out_err_free;
431 
432 		fls->mirror_array[i] = ff_layout_alloc_mirror(gfp_flags);
433 		if (fls->mirror_array[i] == NULL) {
434 			rc = -ENOMEM;
435 			goto out_err_free;
436 		}
437 
438 		fls->mirror_array[i]->ds_count = ds_count;
439 
440 		/* deviceid */
441 		rc = decode_deviceid(&stream, &fls->mirror_array[i]->devid);
442 		if (rc)
443 			goto out_err_free;
444 
445 		/* efficiency */
446 		rc = -EIO;
447 		p = xdr_inline_decode(&stream, 4);
448 		if (!p)
449 			goto out_err_free;
450 		fls->mirror_array[i]->efficiency = be32_to_cpup(p);
451 
452 		/* stateid */
453 		rc = decode_pnfs_stateid(&stream, &fls->mirror_array[i]->stateid);
454 		if (rc)
455 			goto out_err_free;
456 
457 		/* fh */
458 		rc = -EIO;
459 		p = xdr_inline_decode(&stream, 4);
460 		if (!p)
461 			goto out_err_free;
462 		fh_count = be32_to_cpup(p);
463 
464 		fls->mirror_array[i]->fh_versions =
465 			kcalloc(fh_count, sizeof(struct nfs_fh),
466 				gfp_flags);
467 		if (fls->mirror_array[i]->fh_versions == NULL) {
468 			rc = -ENOMEM;
469 			goto out_err_free;
470 		}
471 
472 		for (j = 0; j < fh_count; j++) {
473 			rc = decode_nfs_fh(&stream,
474 					   &fls->mirror_array[i]->fh_versions[j]);
475 			if (rc)
476 				goto out_err_free;
477 		}
478 
479 		fls->mirror_array[i]->fh_versions_cnt = fh_count;
480 
481 		/* user */
482 		rc = decode_name(&stream, &id);
483 		if (rc)
484 			goto out_err_free;
485 
486 		uid = make_kuid(&init_user_ns, id);
487 
488 		/* group */
489 		rc = decode_name(&stream, &id);
490 		if (rc)
491 			goto out_err_free;
492 
493 		gid = make_kgid(&init_user_ns, id);
494 
495 		if (gfp_flags & __GFP_FS)
496 			kcred = prepare_kernel_cred(NULL);
497 		else {
498 			unsigned int nofs_flags = memalloc_nofs_save();
499 			kcred = prepare_kernel_cred(NULL);
500 			memalloc_nofs_restore(nofs_flags);
501 		}
502 		rc = -ENOMEM;
503 		if (!kcred)
504 			goto out_err_free;
505 		kcred->fsuid = uid;
506 		kcred->fsgid = gid;
507 		cred = RCU_INITIALIZER(kcred);
508 
509 		if (lgr->range.iomode == IOMODE_READ)
510 			rcu_assign_pointer(fls->mirror_array[i]->ro_cred, cred);
511 		else
512 			rcu_assign_pointer(fls->mirror_array[i]->rw_cred, cred);
513 
514 		mirror = ff_layout_add_mirror(lh, fls->mirror_array[i]);
515 		if (mirror != fls->mirror_array[i]) {
516 			/* swap cred ptrs so free_mirror will clean up old */
517 			if (lgr->range.iomode == IOMODE_READ) {
518 				cred = xchg(&mirror->ro_cred, cred);
519 				rcu_assign_pointer(fls->mirror_array[i]->ro_cred, cred);
520 			} else {
521 				cred = xchg(&mirror->rw_cred, cred);
522 				rcu_assign_pointer(fls->mirror_array[i]->rw_cred, cred);
523 			}
524 			ff_layout_free_mirror(fls->mirror_array[i]);
525 			fls->mirror_array[i] = mirror;
526 		}
527 
528 		dprintk("%s: iomode %s uid %u gid %u\n", __func__,
529 			lgr->range.iomode == IOMODE_READ ? "READ" : "RW",
530 			from_kuid(&init_user_ns, uid),
531 			from_kgid(&init_user_ns, gid));
532 	}
533 
534 	p = xdr_inline_decode(&stream, 4);
535 	if (!p)
536 		goto out_sort_mirrors;
537 	fls->flags = be32_to_cpup(p);
538 
539 	p = xdr_inline_decode(&stream, 4);
540 	if (!p)
541 		goto out_sort_mirrors;
542 	for (i=0; i < fls->mirror_array_cnt; i++)
543 		fls->mirror_array[i]->report_interval = be32_to_cpup(p);
544 
545 out_sort_mirrors:
546 	ff_layout_sort_mirrors(fls);
547 	rc = ff_layout_check_layout(lgr);
548 	if (rc)
549 		goto out_err_free;
550 	ret = &fls->generic_hdr;
551 	dprintk("<-- %s (success)\n", __func__);
552 out_free_page:
553 	__free_page(scratch);
554 	return ret;
555 out_err_free:
556 	_ff_layout_free_lseg(fls);
557 	ret = ERR_PTR(rc);
558 	dprintk("<-- %s (%d)\n", __func__, rc);
559 	goto out_free_page;
560 }
561 
562 static bool ff_layout_has_rw_segments(struct pnfs_layout_hdr *layout)
563 {
564 	struct pnfs_layout_segment *lseg;
565 
566 	list_for_each_entry(lseg, &layout->plh_segs, pls_list)
567 		if (lseg->pls_range.iomode == IOMODE_RW)
568 			return true;
569 
570 	return false;
571 }
572 
573 static void
574 ff_layout_free_lseg(struct pnfs_layout_segment *lseg)
575 {
576 	struct nfs4_ff_layout_segment *fls = FF_LAYOUT_LSEG(lseg);
577 
578 	dprintk("--> %s\n", __func__);
579 
580 	if (lseg->pls_range.iomode == IOMODE_RW) {
581 		struct nfs4_flexfile_layout *ffl;
582 		struct inode *inode;
583 
584 		ffl = FF_LAYOUT_FROM_HDR(lseg->pls_layout);
585 		inode = ffl->generic_hdr.plh_inode;
586 		spin_lock(&inode->i_lock);
587 		if (!ff_layout_has_rw_segments(lseg->pls_layout)) {
588 			ffl->commit_info.nbuckets = 0;
589 			kfree(ffl->commit_info.buckets);
590 			ffl->commit_info.buckets = NULL;
591 		}
592 		spin_unlock(&inode->i_lock);
593 	}
594 	_ff_layout_free_lseg(fls);
595 }
596 
597 /* Return 1 until we have multiple lsegs support */
598 static int
599 ff_layout_get_lseg_count(struct nfs4_ff_layout_segment *fls)
600 {
601 	return 1;
602 }
603 
604 static void
605 nfs4_ff_start_busy_timer(struct nfs4_ff_busy_timer *timer, ktime_t now)
606 {
607 	/* first IO request? */
608 	if (atomic_inc_return(&timer->n_ops) == 1) {
609 		timer->start_time = now;
610 	}
611 }
612 
613 static ktime_t
614 nfs4_ff_end_busy_timer(struct nfs4_ff_busy_timer *timer, ktime_t now)
615 {
616 	ktime_t start;
617 
618 	if (atomic_dec_return(&timer->n_ops) < 0)
619 		WARN_ON_ONCE(1);
620 
621 	start = timer->start_time;
622 	timer->start_time = now;
623 	return ktime_sub(now, start);
624 }
625 
626 static bool
627 nfs4_ff_layoutstat_start_io(struct nfs4_ff_layout_mirror *mirror,
628 			    struct nfs4_ff_layoutstat *layoutstat,
629 			    ktime_t now)
630 {
631 	s64 report_interval = FF_LAYOUTSTATS_REPORT_INTERVAL;
632 	struct nfs4_flexfile_layout *ffl = FF_LAYOUT_FROM_HDR(mirror->layout);
633 
634 	nfs4_ff_start_busy_timer(&layoutstat->busy_timer, now);
635 	if (!mirror->start_time)
636 		mirror->start_time = now;
637 	if (mirror->report_interval != 0)
638 		report_interval = (s64)mirror->report_interval * 1000LL;
639 	else if (layoutstats_timer != 0)
640 		report_interval = (s64)layoutstats_timer * 1000LL;
641 	if (ktime_to_ms(ktime_sub(now, ffl->last_report_time)) >=
642 			report_interval) {
643 		ffl->last_report_time = now;
644 		return true;
645 	}
646 
647 	return false;
648 }
649 
650 static void
651 nfs4_ff_layout_stat_io_update_requested(struct nfs4_ff_layoutstat *layoutstat,
652 		__u64 requested)
653 {
654 	struct nfs4_ff_io_stat *iostat = &layoutstat->io_stat;
655 
656 	iostat->ops_requested++;
657 	iostat->bytes_requested += requested;
658 }
659 
660 static void
661 nfs4_ff_layout_stat_io_update_completed(struct nfs4_ff_layoutstat *layoutstat,
662 		__u64 requested,
663 		__u64 completed,
664 		ktime_t time_completed,
665 		ktime_t time_started)
666 {
667 	struct nfs4_ff_io_stat *iostat = &layoutstat->io_stat;
668 	ktime_t completion_time = ktime_sub(time_completed, time_started);
669 	ktime_t timer;
670 
671 	iostat->ops_completed++;
672 	iostat->bytes_completed += completed;
673 	iostat->bytes_not_delivered += requested - completed;
674 
675 	timer = nfs4_ff_end_busy_timer(&layoutstat->busy_timer, time_completed);
676 	iostat->total_busy_time =
677 			ktime_add(iostat->total_busy_time, timer);
678 	iostat->aggregate_completion_time =
679 			ktime_add(iostat->aggregate_completion_time,
680 					completion_time);
681 }
682 
683 static void
684 nfs4_ff_layout_stat_io_start_read(struct inode *inode,
685 		struct nfs4_ff_layout_mirror *mirror,
686 		__u64 requested, ktime_t now)
687 {
688 	bool report;
689 
690 	spin_lock(&mirror->lock);
691 	report = nfs4_ff_layoutstat_start_io(mirror, &mirror->read_stat, now);
692 	nfs4_ff_layout_stat_io_update_requested(&mirror->read_stat, requested);
693 	set_bit(NFS4_FF_MIRROR_STAT_AVAIL, &mirror->flags);
694 	spin_unlock(&mirror->lock);
695 
696 	if (report)
697 		pnfs_report_layoutstat(inode, GFP_KERNEL);
698 }
699 
700 static void
701 nfs4_ff_layout_stat_io_end_read(struct rpc_task *task,
702 		struct nfs4_ff_layout_mirror *mirror,
703 		__u64 requested,
704 		__u64 completed)
705 {
706 	spin_lock(&mirror->lock);
707 	nfs4_ff_layout_stat_io_update_completed(&mirror->read_stat,
708 			requested, completed,
709 			ktime_get(), task->tk_start);
710 	set_bit(NFS4_FF_MIRROR_STAT_AVAIL, &mirror->flags);
711 	spin_unlock(&mirror->lock);
712 }
713 
714 static void
715 nfs4_ff_layout_stat_io_start_write(struct inode *inode,
716 		struct nfs4_ff_layout_mirror *mirror,
717 		__u64 requested, ktime_t now)
718 {
719 	bool report;
720 
721 	spin_lock(&mirror->lock);
722 	report = nfs4_ff_layoutstat_start_io(mirror , &mirror->write_stat, now);
723 	nfs4_ff_layout_stat_io_update_requested(&mirror->write_stat, requested);
724 	set_bit(NFS4_FF_MIRROR_STAT_AVAIL, &mirror->flags);
725 	spin_unlock(&mirror->lock);
726 
727 	if (report)
728 		pnfs_report_layoutstat(inode, GFP_NOIO);
729 }
730 
731 static void
732 nfs4_ff_layout_stat_io_end_write(struct rpc_task *task,
733 		struct nfs4_ff_layout_mirror *mirror,
734 		__u64 requested,
735 		__u64 completed,
736 		enum nfs3_stable_how committed)
737 {
738 	if (committed == NFS_UNSTABLE)
739 		requested = completed = 0;
740 
741 	spin_lock(&mirror->lock);
742 	nfs4_ff_layout_stat_io_update_completed(&mirror->write_stat,
743 			requested, completed, ktime_get(), task->tk_start);
744 	set_bit(NFS4_FF_MIRROR_STAT_AVAIL, &mirror->flags);
745 	spin_unlock(&mirror->lock);
746 }
747 
748 static int
749 ff_layout_alloc_commit_info(struct pnfs_layout_segment *lseg,
750 			    struct nfs_commit_info *cinfo,
751 			    gfp_t gfp_flags)
752 {
753 	struct nfs4_ff_layout_segment *fls = FF_LAYOUT_LSEG(lseg);
754 	struct pnfs_commit_bucket *buckets;
755 	int size;
756 
757 	if (cinfo->ds->nbuckets != 0) {
758 		/* This assumes there is only one RW lseg per file.
759 		 * To support multiple lseg per file, we need to
760 		 * change struct pnfs_commit_bucket to allow dynamic
761 		 * increasing nbuckets.
762 		 */
763 		return 0;
764 	}
765 
766 	size = ff_layout_get_lseg_count(fls) * FF_LAYOUT_MIRROR_COUNT(lseg);
767 
768 	buckets = kcalloc(size, sizeof(struct pnfs_commit_bucket),
769 			  gfp_flags);
770 	if (!buckets)
771 		return -ENOMEM;
772 	else {
773 		int i;
774 
775 		spin_lock(&cinfo->inode->i_lock);
776 		if (cinfo->ds->nbuckets != 0)
777 			kfree(buckets);
778 		else {
779 			cinfo->ds->buckets = buckets;
780 			cinfo->ds->nbuckets = size;
781 			for (i = 0; i < size; i++) {
782 				INIT_LIST_HEAD(&buckets[i].written);
783 				INIT_LIST_HEAD(&buckets[i].committing);
784 				/* mark direct verifier as unset */
785 				buckets[i].direct_verf.committed =
786 					NFS_INVALID_STABLE_HOW;
787 			}
788 		}
789 		spin_unlock(&cinfo->inode->i_lock);
790 		return 0;
791 	}
792 }
793 
794 static void
795 ff_layout_mark_ds_unreachable(struct pnfs_layout_segment *lseg, int idx)
796 {
797 	struct nfs4_deviceid_node *devid = FF_LAYOUT_DEVID_NODE(lseg, idx);
798 
799 	if (devid)
800 		nfs4_mark_deviceid_unavailable(devid);
801 }
802 
803 static void
804 ff_layout_mark_ds_reachable(struct pnfs_layout_segment *lseg, int idx)
805 {
806 	struct nfs4_deviceid_node *devid = FF_LAYOUT_DEVID_NODE(lseg, idx);
807 
808 	if (devid)
809 		nfs4_mark_deviceid_available(devid);
810 }
811 
812 static struct nfs4_pnfs_ds *
813 ff_layout_choose_ds_for_read(struct pnfs_layout_segment *lseg,
814 			     int start_idx, int *best_idx,
815 			     bool check_device)
816 {
817 	struct nfs4_ff_layout_segment *fls = FF_LAYOUT_LSEG(lseg);
818 	struct nfs4_ff_layout_mirror *mirror;
819 	struct nfs4_pnfs_ds *ds;
820 	bool fail_return = false;
821 	int idx;
822 
823 	/* mirrors are initially sorted by efficiency */
824 	for (idx = start_idx; idx < fls->mirror_array_cnt; idx++) {
825 		if (idx+1 == fls->mirror_array_cnt)
826 			fail_return = !check_device;
827 
828 		mirror = FF_LAYOUT_COMP(lseg, idx);
829 		ds = nfs4_ff_layout_prepare_ds(lseg, mirror, fail_return);
830 		if (!ds)
831 			continue;
832 
833 		if (check_device &&
834 		    nfs4_test_deviceid_unavailable(&mirror->mirror_ds->id_node))
835 			continue;
836 
837 		*best_idx = idx;
838 		return ds;
839 	}
840 
841 	return NULL;
842 }
843 
844 static struct nfs4_pnfs_ds *
845 ff_layout_choose_any_ds_for_read(struct pnfs_layout_segment *lseg,
846 				 int start_idx, int *best_idx)
847 {
848 	return ff_layout_choose_ds_for_read(lseg, start_idx, best_idx, false);
849 }
850 
851 static struct nfs4_pnfs_ds *
852 ff_layout_choose_valid_ds_for_read(struct pnfs_layout_segment *lseg,
853 				   int start_idx, int *best_idx)
854 {
855 	return ff_layout_choose_ds_for_read(lseg, start_idx, best_idx, true);
856 }
857 
858 static struct nfs4_pnfs_ds *
859 ff_layout_choose_best_ds_for_read(struct pnfs_layout_segment *lseg,
860 				  int start_idx, int *best_idx)
861 {
862 	struct nfs4_pnfs_ds *ds;
863 
864 	ds = ff_layout_choose_valid_ds_for_read(lseg, start_idx, best_idx);
865 	if (ds)
866 		return ds;
867 	return ff_layout_choose_any_ds_for_read(lseg, start_idx, best_idx);
868 }
869 
870 static void
871 ff_layout_pg_get_read(struct nfs_pageio_descriptor *pgio,
872 		      struct nfs_page *req,
873 		      bool strict_iomode)
874 {
875 	pnfs_put_lseg(pgio->pg_lseg);
876 	pgio->pg_lseg = pnfs_update_layout(pgio->pg_inode,
877 					   nfs_req_openctx(req),
878 					   0,
879 					   NFS4_MAX_UINT64,
880 					   IOMODE_READ,
881 					   strict_iomode,
882 					   GFP_KERNEL);
883 	if (IS_ERR(pgio->pg_lseg)) {
884 		pgio->pg_error = PTR_ERR(pgio->pg_lseg);
885 		pgio->pg_lseg = NULL;
886 	}
887 }
888 
889 static void
890 ff_layout_pg_init_read(struct nfs_pageio_descriptor *pgio,
891 			struct nfs_page *req)
892 {
893 	struct nfs_pgio_mirror *pgm;
894 	struct nfs4_ff_layout_mirror *mirror;
895 	struct nfs4_pnfs_ds *ds;
896 	int ds_idx;
897 
898 retry:
899 	pnfs_generic_pg_check_layout(pgio);
900 	/* Use full layout for now */
901 	if (!pgio->pg_lseg) {
902 		ff_layout_pg_get_read(pgio, req, false);
903 		if (!pgio->pg_lseg)
904 			goto out_nolseg;
905 	}
906 	if (ff_layout_avoid_read_on_rw(pgio->pg_lseg)) {
907 		ff_layout_pg_get_read(pgio, req, true);
908 		if (!pgio->pg_lseg)
909 			goto out_nolseg;
910 	}
911 
912 	ds = ff_layout_choose_best_ds_for_read(pgio->pg_lseg, 0, &ds_idx);
913 	if (!ds) {
914 		if (!ff_layout_no_fallback_to_mds(pgio->pg_lseg))
915 			goto out_mds;
916 		pnfs_put_lseg(pgio->pg_lseg);
917 		pgio->pg_lseg = NULL;
918 		/* Sleep for 1 second before retrying */
919 		ssleep(1);
920 		goto retry;
921 	}
922 
923 	mirror = FF_LAYOUT_COMP(pgio->pg_lseg, ds_idx);
924 
925 	pgio->pg_mirror_idx = ds_idx;
926 
927 	/* read always uses only one mirror - idx 0 for pgio layer */
928 	pgm = &pgio->pg_mirrors[0];
929 	pgm->pg_bsize = mirror->mirror_ds->ds_versions[0].rsize;
930 
931 	pgio->pg_maxretrans = io_maxretrans;
932 	return;
933 out_nolseg:
934 	if (pgio->pg_error < 0)
935 		return;
936 out_mds:
937 	trace_pnfs_mds_fallback_pg_init_read(pgio->pg_inode,
938 			0, NFS4_MAX_UINT64, IOMODE_READ,
939 			NFS_I(pgio->pg_inode)->layout,
940 			pgio->pg_lseg);
941 	pnfs_put_lseg(pgio->pg_lseg);
942 	pgio->pg_lseg = NULL;
943 	nfs_pageio_reset_read_mds(pgio);
944 }
945 
946 static void
947 ff_layout_pg_init_write(struct nfs_pageio_descriptor *pgio,
948 			struct nfs_page *req)
949 {
950 	struct nfs4_ff_layout_mirror *mirror;
951 	struct nfs_pgio_mirror *pgm;
952 	struct nfs_commit_info cinfo;
953 	struct nfs4_pnfs_ds *ds;
954 	int i;
955 	int status;
956 
957 retry:
958 	pnfs_generic_pg_check_layout(pgio);
959 	if (!pgio->pg_lseg) {
960 		pgio->pg_lseg = pnfs_update_layout(pgio->pg_inode,
961 						   nfs_req_openctx(req),
962 						   0,
963 						   NFS4_MAX_UINT64,
964 						   IOMODE_RW,
965 						   false,
966 						   GFP_NOFS);
967 		if (IS_ERR(pgio->pg_lseg)) {
968 			pgio->pg_error = PTR_ERR(pgio->pg_lseg);
969 			pgio->pg_lseg = NULL;
970 			return;
971 		}
972 	}
973 	/* If no lseg, fall back to write through mds */
974 	if (pgio->pg_lseg == NULL)
975 		goto out_mds;
976 
977 	nfs_init_cinfo(&cinfo, pgio->pg_inode, pgio->pg_dreq);
978 	status = ff_layout_alloc_commit_info(pgio->pg_lseg, &cinfo, GFP_NOFS);
979 	if (status < 0)
980 		goto out_mds;
981 
982 	/* Use a direct mapping of ds_idx to pgio mirror_idx */
983 	if (WARN_ON_ONCE(pgio->pg_mirror_count !=
984 	    FF_LAYOUT_MIRROR_COUNT(pgio->pg_lseg)))
985 		goto out_mds;
986 
987 	for (i = 0; i < pgio->pg_mirror_count; i++) {
988 		mirror = FF_LAYOUT_COMP(pgio->pg_lseg, i);
989 		ds = nfs4_ff_layout_prepare_ds(pgio->pg_lseg, mirror, true);
990 		if (!ds) {
991 			if (!ff_layout_no_fallback_to_mds(pgio->pg_lseg))
992 				goto out_mds;
993 			pnfs_put_lseg(pgio->pg_lseg);
994 			pgio->pg_lseg = NULL;
995 			/* Sleep for 1 second before retrying */
996 			ssleep(1);
997 			goto retry;
998 		}
999 		pgm = &pgio->pg_mirrors[i];
1000 		pgm->pg_bsize = mirror->mirror_ds->ds_versions[0].wsize;
1001 	}
1002 
1003 	pgio->pg_maxretrans = io_maxretrans;
1004 	return;
1005 
1006 out_mds:
1007 	trace_pnfs_mds_fallback_pg_init_write(pgio->pg_inode,
1008 			0, NFS4_MAX_UINT64, IOMODE_RW,
1009 			NFS_I(pgio->pg_inode)->layout,
1010 			pgio->pg_lseg);
1011 	pnfs_put_lseg(pgio->pg_lseg);
1012 	pgio->pg_lseg = NULL;
1013 	nfs_pageio_reset_write_mds(pgio);
1014 }
1015 
1016 static unsigned int
1017 ff_layout_pg_get_mirror_count_write(struct nfs_pageio_descriptor *pgio,
1018 				    struct nfs_page *req)
1019 {
1020 	if (!pgio->pg_lseg) {
1021 		pgio->pg_lseg = pnfs_update_layout(pgio->pg_inode,
1022 						   nfs_req_openctx(req),
1023 						   0,
1024 						   NFS4_MAX_UINT64,
1025 						   IOMODE_RW,
1026 						   false,
1027 						   GFP_NOFS);
1028 		if (IS_ERR(pgio->pg_lseg)) {
1029 			pgio->pg_error = PTR_ERR(pgio->pg_lseg);
1030 			pgio->pg_lseg = NULL;
1031 			goto out;
1032 		}
1033 	}
1034 	if (pgio->pg_lseg)
1035 		return FF_LAYOUT_MIRROR_COUNT(pgio->pg_lseg);
1036 
1037 	trace_pnfs_mds_fallback_pg_get_mirror_count(pgio->pg_inode,
1038 			0, NFS4_MAX_UINT64, IOMODE_RW,
1039 			NFS_I(pgio->pg_inode)->layout,
1040 			pgio->pg_lseg);
1041 	/* no lseg means that pnfs is not in use, so no mirroring here */
1042 	nfs_pageio_reset_write_mds(pgio);
1043 out:
1044 	return 1;
1045 }
1046 
1047 static const struct nfs_pageio_ops ff_layout_pg_read_ops = {
1048 	.pg_init = ff_layout_pg_init_read,
1049 	.pg_test = pnfs_generic_pg_test,
1050 	.pg_doio = pnfs_generic_pg_readpages,
1051 	.pg_cleanup = pnfs_generic_pg_cleanup,
1052 };
1053 
1054 static const struct nfs_pageio_ops ff_layout_pg_write_ops = {
1055 	.pg_init = ff_layout_pg_init_write,
1056 	.pg_test = pnfs_generic_pg_test,
1057 	.pg_doio = pnfs_generic_pg_writepages,
1058 	.pg_get_mirror_count = ff_layout_pg_get_mirror_count_write,
1059 	.pg_cleanup = pnfs_generic_pg_cleanup,
1060 };
1061 
1062 static void ff_layout_reset_write(struct nfs_pgio_header *hdr, bool retry_pnfs)
1063 {
1064 	struct rpc_task *task = &hdr->task;
1065 
1066 	pnfs_layoutcommit_inode(hdr->inode, false);
1067 
1068 	if (retry_pnfs) {
1069 		dprintk("%s Reset task %5u for i/o through pNFS "
1070 			"(req %s/%llu, %u bytes @ offset %llu)\n", __func__,
1071 			hdr->task.tk_pid,
1072 			hdr->inode->i_sb->s_id,
1073 			(unsigned long long)NFS_FILEID(hdr->inode),
1074 			hdr->args.count,
1075 			(unsigned long long)hdr->args.offset);
1076 
1077 		hdr->completion_ops->reschedule_io(hdr);
1078 		return;
1079 	}
1080 
1081 	if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
1082 		dprintk("%s Reset task %5u for i/o through MDS "
1083 			"(req %s/%llu, %u bytes @ offset %llu)\n", __func__,
1084 			hdr->task.tk_pid,
1085 			hdr->inode->i_sb->s_id,
1086 			(unsigned long long)NFS_FILEID(hdr->inode),
1087 			hdr->args.count,
1088 			(unsigned long long)hdr->args.offset);
1089 
1090 		trace_pnfs_mds_fallback_write_done(hdr->inode,
1091 				hdr->args.offset, hdr->args.count,
1092 				IOMODE_RW, NFS_I(hdr->inode)->layout,
1093 				hdr->lseg);
1094 		task->tk_status = pnfs_write_done_resend_to_mds(hdr);
1095 	}
1096 }
1097 
1098 static void ff_layout_reset_read(struct nfs_pgio_header *hdr)
1099 {
1100 	struct rpc_task *task = &hdr->task;
1101 
1102 	pnfs_layoutcommit_inode(hdr->inode, false);
1103 
1104 	if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
1105 		dprintk("%s Reset task %5u for i/o through MDS "
1106 			"(req %s/%llu, %u bytes @ offset %llu)\n", __func__,
1107 			hdr->task.tk_pid,
1108 			hdr->inode->i_sb->s_id,
1109 			(unsigned long long)NFS_FILEID(hdr->inode),
1110 			hdr->args.count,
1111 			(unsigned long long)hdr->args.offset);
1112 
1113 		trace_pnfs_mds_fallback_read_done(hdr->inode,
1114 				hdr->args.offset, hdr->args.count,
1115 				IOMODE_READ, NFS_I(hdr->inode)->layout,
1116 				hdr->lseg);
1117 		task->tk_status = pnfs_read_done_resend_to_mds(hdr);
1118 	}
1119 }
1120 
1121 static int ff_layout_async_handle_error_v4(struct rpc_task *task,
1122 					   struct nfs4_state *state,
1123 					   struct nfs_client *clp,
1124 					   struct pnfs_layout_segment *lseg,
1125 					   int idx)
1126 {
1127 	struct pnfs_layout_hdr *lo = lseg->pls_layout;
1128 	struct inode *inode = lo->plh_inode;
1129 	struct nfs4_deviceid_node *devid = FF_LAYOUT_DEVID_NODE(lseg, idx);
1130 	struct nfs4_slot_table *tbl = &clp->cl_session->fc_slot_table;
1131 
1132 	switch (task->tk_status) {
1133 	case -NFS4ERR_BADSESSION:
1134 	case -NFS4ERR_BADSLOT:
1135 	case -NFS4ERR_BAD_HIGH_SLOT:
1136 	case -NFS4ERR_DEADSESSION:
1137 	case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
1138 	case -NFS4ERR_SEQ_FALSE_RETRY:
1139 	case -NFS4ERR_SEQ_MISORDERED:
1140 		dprintk("%s ERROR %d, Reset session. Exchangeid "
1141 			"flags 0x%x\n", __func__, task->tk_status,
1142 			clp->cl_exchange_flags);
1143 		nfs4_schedule_session_recovery(clp->cl_session, task->tk_status);
1144 		break;
1145 	case -NFS4ERR_DELAY:
1146 	case -NFS4ERR_GRACE:
1147 		rpc_delay(task, FF_LAYOUT_POLL_RETRY_MAX);
1148 		break;
1149 	case -NFS4ERR_RETRY_UNCACHED_REP:
1150 		break;
1151 	case -EAGAIN:
1152 		return -NFS4ERR_RESET_TO_PNFS;
1153 	/* Invalidate Layout errors */
1154 	case -NFS4ERR_PNFS_NO_LAYOUT:
1155 	case -ESTALE:           /* mapped NFS4ERR_STALE */
1156 	case -EBADHANDLE:       /* mapped NFS4ERR_BADHANDLE */
1157 	case -EISDIR:           /* mapped NFS4ERR_ISDIR */
1158 	case -NFS4ERR_FHEXPIRED:
1159 	case -NFS4ERR_WRONG_TYPE:
1160 		dprintk("%s Invalid layout error %d\n", __func__,
1161 			task->tk_status);
1162 		/*
1163 		 * Destroy layout so new i/o will get a new layout.
1164 		 * Layout will not be destroyed until all current lseg
1165 		 * references are put. Mark layout as invalid to resend failed
1166 		 * i/o and all i/o waiting on the slot table to the MDS until
1167 		 * layout is destroyed and a new valid layout is obtained.
1168 		 */
1169 		pnfs_destroy_layout(NFS_I(inode));
1170 		rpc_wake_up(&tbl->slot_tbl_waitq);
1171 		goto reset;
1172 	/* RPC connection errors */
1173 	case -ECONNREFUSED:
1174 	case -EHOSTDOWN:
1175 	case -EHOSTUNREACH:
1176 	case -ENETUNREACH:
1177 	case -EIO:
1178 	case -ETIMEDOUT:
1179 	case -EPIPE:
1180 		dprintk("%s DS connection error %d\n", __func__,
1181 			task->tk_status);
1182 		nfs4_delete_deviceid(devid->ld, devid->nfs_client,
1183 				&devid->deviceid);
1184 		rpc_wake_up(&tbl->slot_tbl_waitq);
1185 		/* fall through */
1186 	default:
1187 		if (ff_layout_avoid_mds_available_ds(lseg))
1188 			return -NFS4ERR_RESET_TO_PNFS;
1189 reset:
1190 		dprintk("%s Retry through MDS. Error %d\n", __func__,
1191 			task->tk_status);
1192 		return -NFS4ERR_RESET_TO_MDS;
1193 	}
1194 	task->tk_status = 0;
1195 	return -EAGAIN;
1196 }
1197 
1198 /* Retry all errors through either pNFS or MDS except for -EJUKEBOX */
1199 static int ff_layout_async_handle_error_v3(struct rpc_task *task,
1200 					   struct pnfs_layout_segment *lseg,
1201 					   int idx)
1202 {
1203 	struct nfs4_deviceid_node *devid = FF_LAYOUT_DEVID_NODE(lseg, idx);
1204 
1205 	switch (task->tk_status) {
1206 	/* File access problems. Don't mark the device as unavailable */
1207 	case -EACCES:
1208 	case -ESTALE:
1209 	case -EISDIR:
1210 	case -EBADHANDLE:
1211 	case -ELOOP:
1212 	case -ENOSPC:
1213 	case -EAGAIN:
1214 		break;
1215 	case -EJUKEBOX:
1216 		nfs_inc_stats(lseg->pls_layout->plh_inode, NFSIOS_DELAY);
1217 		goto out_retry;
1218 	default:
1219 		dprintk("%s DS connection error %d\n", __func__,
1220 			task->tk_status);
1221 		nfs4_delete_deviceid(devid->ld, devid->nfs_client,
1222 				&devid->deviceid);
1223 	}
1224 	/* FIXME: Need to prevent infinite looping here. */
1225 	return -NFS4ERR_RESET_TO_PNFS;
1226 out_retry:
1227 	task->tk_status = 0;
1228 	rpc_restart_call_prepare(task);
1229 	rpc_delay(task, NFS_JUKEBOX_RETRY_TIME);
1230 	return -EAGAIN;
1231 }
1232 
1233 static int ff_layout_async_handle_error(struct rpc_task *task,
1234 					struct nfs4_state *state,
1235 					struct nfs_client *clp,
1236 					struct pnfs_layout_segment *lseg,
1237 					int idx)
1238 {
1239 	int vers = clp->cl_nfs_mod->rpc_vers->number;
1240 
1241 	if (task->tk_status >= 0) {
1242 		ff_layout_mark_ds_reachable(lseg, idx);
1243 		return 0;
1244 	}
1245 
1246 	/* Handle the case of an invalid layout segment */
1247 	if (!pnfs_is_valid_lseg(lseg))
1248 		return -NFS4ERR_RESET_TO_PNFS;
1249 
1250 	switch (vers) {
1251 	case 3:
1252 		return ff_layout_async_handle_error_v3(task, lseg, idx);
1253 	case 4:
1254 		return ff_layout_async_handle_error_v4(task, state, clp,
1255 						       lseg, idx);
1256 	default:
1257 		/* should never happen */
1258 		WARN_ON_ONCE(1);
1259 		return 0;
1260 	}
1261 }
1262 
1263 static void ff_layout_io_track_ds_error(struct pnfs_layout_segment *lseg,
1264 					int idx, u64 offset, u64 length,
1265 					u32 status, int opnum, int error)
1266 {
1267 	struct nfs4_ff_layout_mirror *mirror;
1268 	int err;
1269 
1270 	if (status == 0) {
1271 		switch (error) {
1272 		case -ETIMEDOUT:
1273 		case -EPFNOSUPPORT:
1274 		case -EPROTONOSUPPORT:
1275 		case -EOPNOTSUPP:
1276 		case -ECONNREFUSED:
1277 		case -ECONNRESET:
1278 		case -EHOSTDOWN:
1279 		case -EHOSTUNREACH:
1280 		case -ENETUNREACH:
1281 		case -EADDRINUSE:
1282 		case -ENOBUFS:
1283 		case -EPIPE:
1284 		case -EPERM:
1285 			status = NFS4ERR_NXIO;
1286 			break;
1287 		case -EACCES:
1288 			status = NFS4ERR_ACCESS;
1289 			break;
1290 		default:
1291 			return;
1292 		}
1293 	}
1294 
1295 	switch (status) {
1296 	case NFS4ERR_DELAY:
1297 	case NFS4ERR_GRACE:
1298 		return;
1299 	default:
1300 		break;
1301 	}
1302 
1303 	mirror = FF_LAYOUT_COMP(lseg, idx);
1304 	err = ff_layout_track_ds_error(FF_LAYOUT_FROM_HDR(lseg->pls_layout),
1305 				       mirror, offset, length, status, opnum,
1306 				       GFP_NOIO);
1307 	if (status == NFS4ERR_NXIO)
1308 		ff_layout_mark_ds_unreachable(lseg, idx);
1309 	pnfs_error_mark_layout_for_return(lseg->pls_layout->plh_inode, lseg);
1310 	dprintk("%s: err %d op %d status %u\n", __func__, err, opnum, status);
1311 }
1312 
1313 /* NFS_PROTO call done callback routines */
1314 static int ff_layout_read_done_cb(struct rpc_task *task,
1315 				struct nfs_pgio_header *hdr)
1316 {
1317 	int new_idx = hdr->pgio_mirror_idx;
1318 	int err;
1319 
1320 	trace_nfs4_pnfs_read(hdr, task->tk_status);
1321 	if (task->tk_status < 0)
1322 		ff_layout_io_track_ds_error(hdr->lseg, hdr->pgio_mirror_idx,
1323 					    hdr->args.offset, hdr->args.count,
1324 					    hdr->res.op_status, OP_READ,
1325 					    task->tk_status);
1326 	err = ff_layout_async_handle_error(task, hdr->args.context->state,
1327 					   hdr->ds_clp, hdr->lseg,
1328 					   hdr->pgio_mirror_idx);
1329 
1330 	clear_bit(NFS_IOHDR_RESEND_PNFS, &hdr->flags);
1331 	clear_bit(NFS_IOHDR_RESEND_MDS, &hdr->flags);
1332 	switch (err) {
1333 	case -NFS4ERR_RESET_TO_PNFS:
1334 		if (ff_layout_choose_best_ds_for_read(hdr->lseg,
1335 					hdr->pgio_mirror_idx + 1,
1336 					&new_idx))
1337 			goto out_layouterror;
1338 		set_bit(NFS_IOHDR_RESEND_PNFS, &hdr->flags);
1339 		return task->tk_status;
1340 	case -NFS4ERR_RESET_TO_MDS:
1341 		set_bit(NFS_IOHDR_RESEND_MDS, &hdr->flags);
1342 		return task->tk_status;
1343 	case -EAGAIN:
1344 		goto out_eagain;
1345 	}
1346 
1347 	return 0;
1348 out_layouterror:
1349 	ff_layout_read_record_layoutstats_done(task, hdr);
1350 	ff_layout_send_layouterror(hdr->lseg);
1351 	hdr->pgio_mirror_idx = new_idx;
1352 out_eagain:
1353 	rpc_restart_call_prepare(task);
1354 	return -EAGAIN;
1355 }
1356 
1357 static bool
1358 ff_layout_need_layoutcommit(struct pnfs_layout_segment *lseg)
1359 {
1360 	return !(FF_LAYOUT_LSEG(lseg)->flags & FF_FLAGS_NO_LAYOUTCOMMIT);
1361 }
1362 
1363 /*
1364  * We reference the rpc_cred of the first WRITE that triggers the need for
1365  * a LAYOUTCOMMIT, and use it to send the layoutcommit compound.
1366  * rfc5661 is not clear about which credential should be used.
1367  *
1368  * Flexlayout client should treat DS replied FILE_SYNC as DATA_SYNC, so
1369  * to follow http://www.rfc-editor.org/errata_search.php?rfc=5661&eid=2751
1370  * we always send layoutcommit after DS writes.
1371  */
1372 static void
1373 ff_layout_set_layoutcommit(struct inode *inode,
1374 		struct pnfs_layout_segment *lseg,
1375 		loff_t end_offset)
1376 {
1377 	if (!ff_layout_need_layoutcommit(lseg))
1378 		return;
1379 
1380 	pnfs_set_layoutcommit(inode, lseg, end_offset);
1381 	dprintk("%s inode %lu pls_end_pos %llu\n", __func__, inode->i_ino,
1382 		(unsigned long long) NFS_I(inode)->layout->plh_lwb);
1383 }
1384 
1385 static void ff_layout_read_record_layoutstats_start(struct rpc_task *task,
1386 		struct nfs_pgio_header *hdr)
1387 {
1388 	if (test_and_set_bit(NFS_IOHDR_STAT, &hdr->flags))
1389 		return;
1390 	nfs4_ff_layout_stat_io_start_read(hdr->inode,
1391 			FF_LAYOUT_COMP(hdr->lseg, hdr->pgio_mirror_idx),
1392 			hdr->args.count,
1393 			task->tk_start);
1394 }
1395 
1396 static void ff_layout_read_record_layoutstats_done(struct rpc_task *task,
1397 		struct nfs_pgio_header *hdr)
1398 {
1399 	if (!test_and_clear_bit(NFS_IOHDR_STAT, &hdr->flags))
1400 		return;
1401 	nfs4_ff_layout_stat_io_end_read(task,
1402 			FF_LAYOUT_COMP(hdr->lseg, hdr->pgio_mirror_idx),
1403 			hdr->args.count,
1404 			hdr->res.count);
1405 	set_bit(NFS_LSEG_LAYOUTRETURN, &hdr->lseg->pls_flags);
1406 }
1407 
1408 static int ff_layout_read_prepare_common(struct rpc_task *task,
1409 					 struct nfs_pgio_header *hdr)
1410 {
1411 	if (unlikely(test_bit(NFS_CONTEXT_BAD, &hdr->args.context->flags))) {
1412 		rpc_exit(task, -EIO);
1413 		return -EIO;
1414 	}
1415 
1416 	ff_layout_read_record_layoutstats_start(task, hdr);
1417 	return 0;
1418 }
1419 
1420 /*
1421  * Call ops for the async read/write cases
1422  * In the case of dense layouts, the offset needs to be reset to its
1423  * original value.
1424  */
1425 static void ff_layout_read_prepare_v3(struct rpc_task *task, void *data)
1426 {
1427 	struct nfs_pgio_header *hdr = data;
1428 
1429 	if (ff_layout_read_prepare_common(task, hdr))
1430 		return;
1431 
1432 	rpc_call_start(task);
1433 }
1434 
1435 static void ff_layout_read_prepare_v4(struct rpc_task *task, void *data)
1436 {
1437 	struct nfs_pgio_header *hdr = data;
1438 
1439 	if (nfs4_setup_sequence(hdr->ds_clp,
1440 				&hdr->args.seq_args,
1441 				&hdr->res.seq_res,
1442 				task))
1443 		return;
1444 
1445 	ff_layout_read_prepare_common(task, hdr);
1446 }
1447 
1448 static void
1449 ff_layout_io_prepare_transmit(struct rpc_task *task,
1450 		void *data)
1451 {
1452 	struct nfs_pgio_header *hdr = data;
1453 
1454 	if (!pnfs_is_valid_lseg(hdr->lseg))
1455 		rpc_exit(task, -EAGAIN);
1456 }
1457 
1458 static void ff_layout_read_call_done(struct rpc_task *task, void *data)
1459 {
1460 	struct nfs_pgio_header *hdr = data;
1461 
1462 	dprintk("--> %s task->tk_status %d\n", __func__, task->tk_status);
1463 
1464 	if (test_bit(NFS_IOHDR_REDO, &hdr->flags) &&
1465 	    task->tk_status == 0) {
1466 		nfs4_sequence_done(task, &hdr->res.seq_res);
1467 		return;
1468 	}
1469 
1470 	/* Note this may cause RPC to be resent */
1471 	hdr->mds_ops->rpc_call_done(task, hdr);
1472 }
1473 
1474 static void ff_layout_read_count_stats(struct rpc_task *task, void *data)
1475 {
1476 	struct nfs_pgio_header *hdr = data;
1477 
1478 	ff_layout_read_record_layoutstats_done(task, hdr);
1479 	rpc_count_iostats_metrics(task,
1480 	    &NFS_CLIENT(hdr->inode)->cl_metrics[NFSPROC4_CLNT_READ]);
1481 }
1482 
1483 static void ff_layout_read_release(void *data)
1484 {
1485 	struct nfs_pgio_header *hdr = data;
1486 
1487 	ff_layout_read_record_layoutstats_done(&hdr->task, hdr);
1488 	if (test_bit(NFS_IOHDR_RESEND_PNFS, &hdr->flags)) {
1489 		ff_layout_send_layouterror(hdr->lseg);
1490 		pnfs_read_resend_pnfs(hdr);
1491 	} else if (test_bit(NFS_IOHDR_RESEND_MDS, &hdr->flags))
1492 		ff_layout_reset_read(hdr);
1493 	pnfs_generic_rw_release(data);
1494 }
1495 
1496 
1497 static int ff_layout_write_done_cb(struct rpc_task *task,
1498 				struct nfs_pgio_header *hdr)
1499 {
1500 	loff_t end_offs = 0;
1501 	int err;
1502 
1503 	trace_nfs4_pnfs_write(hdr, task->tk_status);
1504 	if (task->tk_status < 0)
1505 		ff_layout_io_track_ds_error(hdr->lseg, hdr->pgio_mirror_idx,
1506 					    hdr->args.offset, hdr->args.count,
1507 					    hdr->res.op_status, OP_WRITE,
1508 					    task->tk_status);
1509 	err = ff_layout_async_handle_error(task, hdr->args.context->state,
1510 					   hdr->ds_clp, hdr->lseg,
1511 					   hdr->pgio_mirror_idx);
1512 
1513 	clear_bit(NFS_IOHDR_RESEND_PNFS, &hdr->flags);
1514 	clear_bit(NFS_IOHDR_RESEND_MDS, &hdr->flags);
1515 	switch (err) {
1516 	case -NFS4ERR_RESET_TO_PNFS:
1517 		set_bit(NFS_IOHDR_RESEND_PNFS, &hdr->flags);
1518 		return task->tk_status;
1519 	case -NFS4ERR_RESET_TO_MDS:
1520 		set_bit(NFS_IOHDR_RESEND_MDS, &hdr->flags);
1521 		return task->tk_status;
1522 	case -EAGAIN:
1523 		return -EAGAIN;
1524 	}
1525 
1526 	if (hdr->res.verf->committed == NFS_FILE_SYNC ||
1527 	    hdr->res.verf->committed == NFS_DATA_SYNC)
1528 		end_offs = hdr->mds_offset + (loff_t)hdr->res.count;
1529 
1530 	/* Note: if the write is unstable, don't set end_offs until commit */
1531 	ff_layout_set_layoutcommit(hdr->inode, hdr->lseg, end_offs);
1532 
1533 	/* zero out fattr since we don't care DS attr at all */
1534 	hdr->fattr.valid = 0;
1535 	if (task->tk_status >= 0)
1536 		nfs_writeback_update_inode(hdr);
1537 
1538 	return 0;
1539 }
1540 
1541 static int ff_layout_commit_done_cb(struct rpc_task *task,
1542 				     struct nfs_commit_data *data)
1543 {
1544 	int err;
1545 
1546 	trace_nfs4_pnfs_commit_ds(data, task->tk_status);
1547 	if (task->tk_status < 0)
1548 		ff_layout_io_track_ds_error(data->lseg, data->ds_commit_index,
1549 					    data->args.offset, data->args.count,
1550 					    data->res.op_status, OP_COMMIT,
1551 					    task->tk_status);
1552 	err = ff_layout_async_handle_error(task, NULL, data->ds_clp,
1553 					   data->lseg, data->ds_commit_index);
1554 
1555 	switch (err) {
1556 	case -NFS4ERR_RESET_TO_PNFS:
1557 		pnfs_generic_prepare_to_resend_writes(data);
1558 		return -EAGAIN;
1559 	case -NFS4ERR_RESET_TO_MDS:
1560 		pnfs_generic_prepare_to_resend_writes(data);
1561 		return -EAGAIN;
1562 	case -EAGAIN:
1563 		rpc_restart_call_prepare(task);
1564 		return -EAGAIN;
1565 	}
1566 
1567 	ff_layout_set_layoutcommit(data->inode, data->lseg, data->lwb);
1568 
1569 	return 0;
1570 }
1571 
1572 static void ff_layout_write_record_layoutstats_start(struct rpc_task *task,
1573 		struct nfs_pgio_header *hdr)
1574 {
1575 	if (test_and_set_bit(NFS_IOHDR_STAT, &hdr->flags))
1576 		return;
1577 	nfs4_ff_layout_stat_io_start_write(hdr->inode,
1578 			FF_LAYOUT_COMP(hdr->lseg, hdr->pgio_mirror_idx),
1579 			hdr->args.count,
1580 			task->tk_start);
1581 }
1582 
1583 static void ff_layout_write_record_layoutstats_done(struct rpc_task *task,
1584 		struct nfs_pgio_header *hdr)
1585 {
1586 	if (!test_and_clear_bit(NFS_IOHDR_STAT, &hdr->flags))
1587 		return;
1588 	nfs4_ff_layout_stat_io_end_write(task,
1589 			FF_LAYOUT_COMP(hdr->lseg, hdr->pgio_mirror_idx),
1590 			hdr->args.count, hdr->res.count,
1591 			hdr->res.verf->committed);
1592 	set_bit(NFS_LSEG_LAYOUTRETURN, &hdr->lseg->pls_flags);
1593 }
1594 
1595 static int ff_layout_write_prepare_common(struct rpc_task *task,
1596 					  struct nfs_pgio_header *hdr)
1597 {
1598 	if (unlikely(test_bit(NFS_CONTEXT_BAD, &hdr->args.context->flags))) {
1599 		rpc_exit(task, -EIO);
1600 		return -EIO;
1601 	}
1602 
1603 	ff_layout_write_record_layoutstats_start(task, hdr);
1604 	return 0;
1605 }
1606 
1607 static void ff_layout_write_prepare_v3(struct rpc_task *task, void *data)
1608 {
1609 	struct nfs_pgio_header *hdr = data;
1610 
1611 	if (ff_layout_write_prepare_common(task, hdr))
1612 		return;
1613 
1614 	rpc_call_start(task);
1615 }
1616 
1617 static void ff_layout_write_prepare_v4(struct rpc_task *task, void *data)
1618 {
1619 	struct nfs_pgio_header *hdr = data;
1620 
1621 	if (nfs4_setup_sequence(hdr->ds_clp,
1622 				&hdr->args.seq_args,
1623 				&hdr->res.seq_res,
1624 				task))
1625 		return;
1626 
1627 	ff_layout_write_prepare_common(task, hdr);
1628 }
1629 
1630 static void ff_layout_write_call_done(struct rpc_task *task, void *data)
1631 {
1632 	struct nfs_pgio_header *hdr = data;
1633 
1634 	if (test_bit(NFS_IOHDR_REDO, &hdr->flags) &&
1635 	    task->tk_status == 0) {
1636 		nfs4_sequence_done(task, &hdr->res.seq_res);
1637 		return;
1638 	}
1639 
1640 	/* Note this may cause RPC to be resent */
1641 	hdr->mds_ops->rpc_call_done(task, hdr);
1642 }
1643 
1644 static void ff_layout_write_count_stats(struct rpc_task *task, void *data)
1645 {
1646 	struct nfs_pgio_header *hdr = data;
1647 
1648 	ff_layout_write_record_layoutstats_done(task, hdr);
1649 	rpc_count_iostats_metrics(task,
1650 	    &NFS_CLIENT(hdr->inode)->cl_metrics[NFSPROC4_CLNT_WRITE]);
1651 }
1652 
1653 static void ff_layout_write_release(void *data)
1654 {
1655 	struct nfs_pgio_header *hdr = data;
1656 
1657 	ff_layout_write_record_layoutstats_done(&hdr->task, hdr);
1658 	if (test_bit(NFS_IOHDR_RESEND_PNFS, &hdr->flags)) {
1659 		ff_layout_send_layouterror(hdr->lseg);
1660 		ff_layout_reset_write(hdr, true);
1661 	} else if (test_bit(NFS_IOHDR_RESEND_MDS, &hdr->flags))
1662 		ff_layout_reset_write(hdr, false);
1663 	pnfs_generic_rw_release(data);
1664 }
1665 
1666 static void ff_layout_commit_record_layoutstats_start(struct rpc_task *task,
1667 		struct nfs_commit_data *cdata)
1668 {
1669 	if (test_and_set_bit(NFS_IOHDR_STAT, &cdata->flags))
1670 		return;
1671 	nfs4_ff_layout_stat_io_start_write(cdata->inode,
1672 			FF_LAYOUT_COMP(cdata->lseg, cdata->ds_commit_index),
1673 			0, task->tk_start);
1674 }
1675 
1676 static void ff_layout_commit_record_layoutstats_done(struct rpc_task *task,
1677 		struct nfs_commit_data *cdata)
1678 {
1679 	struct nfs_page *req;
1680 	__u64 count = 0;
1681 
1682 	if (!test_and_clear_bit(NFS_IOHDR_STAT, &cdata->flags))
1683 		return;
1684 
1685 	if (task->tk_status == 0) {
1686 		list_for_each_entry(req, &cdata->pages, wb_list)
1687 			count += req->wb_bytes;
1688 	}
1689 	nfs4_ff_layout_stat_io_end_write(task,
1690 			FF_LAYOUT_COMP(cdata->lseg, cdata->ds_commit_index),
1691 			count, count, NFS_FILE_SYNC);
1692 	set_bit(NFS_LSEG_LAYOUTRETURN, &cdata->lseg->pls_flags);
1693 }
1694 
1695 static void ff_layout_commit_prepare_common(struct rpc_task *task,
1696 		struct nfs_commit_data *cdata)
1697 {
1698 	ff_layout_commit_record_layoutstats_start(task, cdata);
1699 }
1700 
1701 static void ff_layout_commit_prepare_v3(struct rpc_task *task, void *data)
1702 {
1703 	ff_layout_commit_prepare_common(task, data);
1704 	rpc_call_start(task);
1705 }
1706 
1707 static void ff_layout_commit_prepare_v4(struct rpc_task *task, void *data)
1708 {
1709 	struct nfs_commit_data *wdata = data;
1710 
1711 	if (nfs4_setup_sequence(wdata->ds_clp,
1712 				&wdata->args.seq_args,
1713 				&wdata->res.seq_res,
1714 				task))
1715 		return;
1716 	ff_layout_commit_prepare_common(task, data);
1717 }
1718 
1719 static void ff_layout_commit_done(struct rpc_task *task, void *data)
1720 {
1721 	pnfs_generic_write_commit_done(task, data);
1722 }
1723 
1724 static void ff_layout_commit_count_stats(struct rpc_task *task, void *data)
1725 {
1726 	struct nfs_commit_data *cdata = data;
1727 
1728 	ff_layout_commit_record_layoutstats_done(task, cdata);
1729 	rpc_count_iostats_metrics(task,
1730 	    &NFS_CLIENT(cdata->inode)->cl_metrics[NFSPROC4_CLNT_COMMIT]);
1731 }
1732 
1733 static void ff_layout_commit_release(void *data)
1734 {
1735 	struct nfs_commit_data *cdata = data;
1736 
1737 	ff_layout_commit_record_layoutstats_done(&cdata->task, cdata);
1738 	pnfs_generic_commit_release(data);
1739 }
1740 
1741 static const struct rpc_call_ops ff_layout_read_call_ops_v3 = {
1742 	.rpc_call_prepare = ff_layout_read_prepare_v3,
1743 	.rpc_call_prepare_transmit = ff_layout_io_prepare_transmit,
1744 	.rpc_call_done = ff_layout_read_call_done,
1745 	.rpc_count_stats = ff_layout_read_count_stats,
1746 	.rpc_release = ff_layout_read_release,
1747 };
1748 
1749 static const struct rpc_call_ops ff_layout_read_call_ops_v4 = {
1750 	.rpc_call_prepare = ff_layout_read_prepare_v4,
1751 	.rpc_call_prepare_transmit = ff_layout_io_prepare_transmit,
1752 	.rpc_call_done = ff_layout_read_call_done,
1753 	.rpc_count_stats = ff_layout_read_count_stats,
1754 	.rpc_release = ff_layout_read_release,
1755 };
1756 
1757 static const struct rpc_call_ops ff_layout_write_call_ops_v3 = {
1758 	.rpc_call_prepare = ff_layout_write_prepare_v3,
1759 	.rpc_call_prepare_transmit = ff_layout_io_prepare_transmit,
1760 	.rpc_call_done = ff_layout_write_call_done,
1761 	.rpc_count_stats = ff_layout_write_count_stats,
1762 	.rpc_release = ff_layout_write_release,
1763 };
1764 
1765 static const struct rpc_call_ops ff_layout_write_call_ops_v4 = {
1766 	.rpc_call_prepare = ff_layout_write_prepare_v4,
1767 	.rpc_call_prepare_transmit = ff_layout_io_prepare_transmit,
1768 	.rpc_call_done = ff_layout_write_call_done,
1769 	.rpc_count_stats = ff_layout_write_count_stats,
1770 	.rpc_release = ff_layout_write_release,
1771 };
1772 
1773 static const struct rpc_call_ops ff_layout_commit_call_ops_v3 = {
1774 	.rpc_call_prepare = ff_layout_commit_prepare_v3,
1775 	.rpc_call_done = ff_layout_commit_done,
1776 	.rpc_count_stats = ff_layout_commit_count_stats,
1777 	.rpc_release = ff_layout_commit_release,
1778 };
1779 
1780 static const struct rpc_call_ops ff_layout_commit_call_ops_v4 = {
1781 	.rpc_call_prepare = ff_layout_commit_prepare_v4,
1782 	.rpc_call_done = ff_layout_commit_done,
1783 	.rpc_count_stats = ff_layout_commit_count_stats,
1784 	.rpc_release = ff_layout_commit_release,
1785 };
1786 
1787 static enum pnfs_try_status
1788 ff_layout_read_pagelist(struct nfs_pgio_header *hdr)
1789 {
1790 	struct pnfs_layout_segment *lseg = hdr->lseg;
1791 	struct nfs4_pnfs_ds *ds;
1792 	struct rpc_clnt *ds_clnt;
1793 	struct nfs4_ff_layout_mirror *mirror;
1794 	const struct cred *ds_cred;
1795 	loff_t offset = hdr->args.offset;
1796 	u32 idx = hdr->pgio_mirror_idx;
1797 	int vers;
1798 	struct nfs_fh *fh;
1799 
1800 	dprintk("--> %s ino %lu pgbase %u req %zu@%llu\n",
1801 		__func__, hdr->inode->i_ino,
1802 		hdr->args.pgbase, (size_t)hdr->args.count, offset);
1803 
1804 	mirror = FF_LAYOUT_COMP(lseg, idx);
1805 	ds = nfs4_ff_layout_prepare_ds(lseg, mirror, false);
1806 	if (!ds)
1807 		goto out_failed;
1808 
1809 	ds_clnt = nfs4_ff_find_or_create_ds_client(mirror, ds->ds_clp,
1810 						   hdr->inode);
1811 	if (IS_ERR(ds_clnt))
1812 		goto out_failed;
1813 
1814 	ds_cred = ff_layout_get_ds_cred(mirror, &lseg->pls_range, hdr->cred);
1815 	if (!ds_cred)
1816 		goto out_failed;
1817 
1818 	vers = nfs4_ff_layout_ds_version(mirror);
1819 
1820 	dprintk("%s USE DS: %s cl_count %d vers %d\n", __func__,
1821 		ds->ds_remotestr, refcount_read(&ds->ds_clp->cl_count), vers);
1822 
1823 	hdr->pgio_done_cb = ff_layout_read_done_cb;
1824 	refcount_inc(&ds->ds_clp->cl_count);
1825 	hdr->ds_clp = ds->ds_clp;
1826 	fh = nfs4_ff_layout_select_ds_fh(mirror);
1827 	if (fh)
1828 		hdr->args.fh = fh;
1829 
1830 	nfs4_ff_layout_select_ds_stateid(mirror, &hdr->args.stateid);
1831 
1832 	/*
1833 	 * Note that if we ever decide to split across DSes,
1834 	 * then we may need to handle dense-like offsets.
1835 	 */
1836 	hdr->args.offset = offset;
1837 	hdr->mds_offset = offset;
1838 
1839 	/* Perform an asynchronous read to ds */
1840 	nfs_initiate_pgio(ds_clnt, hdr, ds_cred, ds->ds_clp->rpc_ops,
1841 			  vers == 3 ? &ff_layout_read_call_ops_v3 :
1842 				      &ff_layout_read_call_ops_v4,
1843 			  0, RPC_TASK_SOFTCONN);
1844 	put_cred(ds_cred);
1845 	return PNFS_ATTEMPTED;
1846 
1847 out_failed:
1848 	if (ff_layout_avoid_mds_available_ds(lseg))
1849 		return PNFS_TRY_AGAIN;
1850 	trace_pnfs_mds_fallback_read_pagelist(hdr->inode,
1851 			hdr->args.offset, hdr->args.count,
1852 			IOMODE_READ, NFS_I(hdr->inode)->layout, lseg);
1853 	return PNFS_NOT_ATTEMPTED;
1854 }
1855 
1856 /* Perform async writes. */
1857 static enum pnfs_try_status
1858 ff_layout_write_pagelist(struct nfs_pgio_header *hdr, int sync)
1859 {
1860 	struct pnfs_layout_segment *lseg = hdr->lseg;
1861 	struct nfs4_pnfs_ds *ds;
1862 	struct rpc_clnt *ds_clnt;
1863 	struct nfs4_ff_layout_mirror *mirror;
1864 	const struct cred *ds_cred;
1865 	loff_t offset = hdr->args.offset;
1866 	int vers;
1867 	struct nfs_fh *fh;
1868 	int idx = hdr->pgio_mirror_idx;
1869 
1870 	mirror = FF_LAYOUT_COMP(lseg, idx);
1871 	ds = nfs4_ff_layout_prepare_ds(lseg, mirror, true);
1872 	if (!ds)
1873 		goto out_failed;
1874 
1875 	ds_clnt = nfs4_ff_find_or_create_ds_client(mirror, ds->ds_clp,
1876 						   hdr->inode);
1877 	if (IS_ERR(ds_clnt))
1878 		goto out_failed;
1879 
1880 	ds_cred = ff_layout_get_ds_cred(mirror, &lseg->pls_range, hdr->cred);
1881 	if (!ds_cred)
1882 		goto out_failed;
1883 
1884 	vers = nfs4_ff_layout_ds_version(mirror);
1885 
1886 	dprintk("%s ino %lu sync %d req %zu@%llu DS: %s cl_count %d vers %d\n",
1887 		__func__, hdr->inode->i_ino, sync, (size_t) hdr->args.count,
1888 		offset, ds->ds_remotestr, refcount_read(&ds->ds_clp->cl_count),
1889 		vers);
1890 
1891 	hdr->pgio_done_cb = ff_layout_write_done_cb;
1892 	refcount_inc(&ds->ds_clp->cl_count);
1893 	hdr->ds_clp = ds->ds_clp;
1894 	hdr->ds_commit_idx = idx;
1895 	fh = nfs4_ff_layout_select_ds_fh(mirror);
1896 	if (fh)
1897 		hdr->args.fh = fh;
1898 
1899 	nfs4_ff_layout_select_ds_stateid(mirror, &hdr->args.stateid);
1900 
1901 	/*
1902 	 * Note that if we ever decide to split across DSes,
1903 	 * then we may need to handle dense-like offsets.
1904 	 */
1905 	hdr->args.offset = offset;
1906 
1907 	/* Perform an asynchronous write */
1908 	nfs_initiate_pgio(ds_clnt, hdr, ds_cred, ds->ds_clp->rpc_ops,
1909 			  vers == 3 ? &ff_layout_write_call_ops_v3 :
1910 				      &ff_layout_write_call_ops_v4,
1911 			  sync, RPC_TASK_SOFTCONN);
1912 	put_cred(ds_cred);
1913 	return PNFS_ATTEMPTED;
1914 
1915 out_failed:
1916 	if (ff_layout_avoid_mds_available_ds(lseg))
1917 		return PNFS_TRY_AGAIN;
1918 	trace_pnfs_mds_fallback_write_pagelist(hdr->inode,
1919 			hdr->args.offset, hdr->args.count,
1920 			IOMODE_RW, NFS_I(hdr->inode)->layout, lseg);
1921 	return PNFS_NOT_ATTEMPTED;
1922 }
1923 
1924 static u32 calc_ds_index_from_commit(struct pnfs_layout_segment *lseg, u32 i)
1925 {
1926 	return i;
1927 }
1928 
1929 static struct nfs_fh *
1930 select_ds_fh_from_commit(struct pnfs_layout_segment *lseg, u32 i)
1931 {
1932 	struct nfs4_ff_layout_segment *flseg = FF_LAYOUT_LSEG(lseg);
1933 
1934 	/* FIXME: Assume that there is only one NFS version available
1935 	 * for the DS.
1936 	 */
1937 	return &flseg->mirror_array[i]->fh_versions[0];
1938 }
1939 
1940 static int ff_layout_initiate_commit(struct nfs_commit_data *data, int how)
1941 {
1942 	struct pnfs_layout_segment *lseg = data->lseg;
1943 	struct nfs4_pnfs_ds *ds;
1944 	struct rpc_clnt *ds_clnt;
1945 	struct nfs4_ff_layout_mirror *mirror;
1946 	const struct cred *ds_cred;
1947 	u32 idx;
1948 	int vers, ret;
1949 	struct nfs_fh *fh;
1950 
1951 	if (!lseg || !(pnfs_is_valid_lseg(lseg) ||
1952 	    test_bit(NFS_LSEG_LAYOUTRETURN, &lseg->pls_flags)))
1953 		goto out_err;
1954 
1955 	idx = calc_ds_index_from_commit(lseg, data->ds_commit_index);
1956 	mirror = FF_LAYOUT_COMP(lseg, idx);
1957 	ds = nfs4_ff_layout_prepare_ds(lseg, mirror, true);
1958 	if (!ds)
1959 		goto out_err;
1960 
1961 	ds_clnt = nfs4_ff_find_or_create_ds_client(mirror, ds->ds_clp,
1962 						   data->inode);
1963 	if (IS_ERR(ds_clnt))
1964 		goto out_err;
1965 
1966 	ds_cred = ff_layout_get_ds_cred(mirror, &lseg->pls_range, data->cred);
1967 	if (!ds_cred)
1968 		goto out_err;
1969 
1970 	vers = nfs4_ff_layout_ds_version(mirror);
1971 
1972 	dprintk("%s ino %lu, how %d cl_count %d vers %d\n", __func__,
1973 		data->inode->i_ino, how, refcount_read(&ds->ds_clp->cl_count),
1974 		vers);
1975 	data->commit_done_cb = ff_layout_commit_done_cb;
1976 	data->cred = ds_cred;
1977 	refcount_inc(&ds->ds_clp->cl_count);
1978 	data->ds_clp = ds->ds_clp;
1979 	fh = select_ds_fh_from_commit(lseg, data->ds_commit_index);
1980 	if (fh)
1981 		data->args.fh = fh;
1982 
1983 	ret = nfs_initiate_commit(ds_clnt, data, ds->ds_clp->rpc_ops,
1984 				   vers == 3 ? &ff_layout_commit_call_ops_v3 :
1985 					       &ff_layout_commit_call_ops_v4,
1986 				   how, RPC_TASK_SOFTCONN);
1987 	put_cred(ds_cred);
1988 	return ret;
1989 out_err:
1990 	pnfs_generic_prepare_to_resend_writes(data);
1991 	pnfs_generic_commit_release(data);
1992 	return -EAGAIN;
1993 }
1994 
1995 static int
1996 ff_layout_commit_pagelist(struct inode *inode, struct list_head *mds_pages,
1997 			   int how, struct nfs_commit_info *cinfo)
1998 {
1999 	return pnfs_generic_commit_pagelist(inode, mds_pages, how, cinfo,
2000 					    ff_layout_initiate_commit);
2001 }
2002 
2003 static struct pnfs_ds_commit_info *
2004 ff_layout_get_ds_info(struct inode *inode)
2005 {
2006 	struct pnfs_layout_hdr *layout = NFS_I(inode)->layout;
2007 
2008 	if (layout == NULL)
2009 		return NULL;
2010 
2011 	return &FF_LAYOUT_FROM_HDR(layout)->commit_info;
2012 }
2013 
2014 static void
2015 ff_layout_free_deviceid_node(struct nfs4_deviceid_node *d)
2016 {
2017 	nfs4_ff_layout_free_deviceid(container_of(d, struct nfs4_ff_layout_ds,
2018 						  id_node));
2019 }
2020 
2021 static int ff_layout_encode_ioerr(struct xdr_stream *xdr,
2022 				  const struct nfs4_layoutreturn_args *args,
2023 				  const struct nfs4_flexfile_layoutreturn_args *ff_args)
2024 {
2025 	__be32 *start;
2026 
2027 	start = xdr_reserve_space(xdr, 4);
2028 	if (unlikely(!start))
2029 		return -E2BIG;
2030 
2031 	*start = cpu_to_be32(ff_args->num_errors);
2032 	/* This assume we always return _ALL_ layouts */
2033 	return ff_layout_encode_ds_ioerr(xdr, &ff_args->errors);
2034 }
2035 
2036 static void
2037 encode_opaque_fixed(struct xdr_stream *xdr, const void *buf, size_t len)
2038 {
2039 	WARN_ON_ONCE(xdr_stream_encode_opaque_fixed(xdr, buf, len) < 0);
2040 }
2041 
2042 static void
2043 ff_layout_encode_ff_iostat_head(struct xdr_stream *xdr,
2044 			    const nfs4_stateid *stateid,
2045 			    const struct nfs42_layoutstat_devinfo *devinfo)
2046 {
2047 	__be32 *p;
2048 
2049 	p = xdr_reserve_space(xdr, 8 + 8);
2050 	p = xdr_encode_hyper(p, devinfo->offset);
2051 	p = xdr_encode_hyper(p, devinfo->length);
2052 	encode_opaque_fixed(xdr, stateid->data, NFS4_STATEID_SIZE);
2053 	p = xdr_reserve_space(xdr, 4*8);
2054 	p = xdr_encode_hyper(p, devinfo->read_count);
2055 	p = xdr_encode_hyper(p, devinfo->read_bytes);
2056 	p = xdr_encode_hyper(p, devinfo->write_count);
2057 	p = xdr_encode_hyper(p, devinfo->write_bytes);
2058 	encode_opaque_fixed(xdr, devinfo->dev_id.data, NFS4_DEVICEID4_SIZE);
2059 }
2060 
2061 static void
2062 ff_layout_encode_ff_iostat(struct xdr_stream *xdr,
2063 			    const nfs4_stateid *stateid,
2064 			    const struct nfs42_layoutstat_devinfo *devinfo)
2065 {
2066 	ff_layout_encode_ff_iostat_head(xdr, stateid, devinfo);
2067 	ff_layout_encode_ff_layoutupdate(xdr, devinfo,
2068 			devinfo->ld_private.data);
2069 }
2070 
2071 /* report nothing for now */
2072 static void ff_layout_encode_iostats_array(struct xdr_stream *xdr,
2073 		const struct nfs4_layoutreturn_args *args,
2074 		struct nfs4_flexfile_layoutreturn_args *ff_args)
2075 {
2076 	__be32 *p;
2077 	int i;
2078 
2079 	p = xdr_reserve_space(xdr, 4);
2080 	*p = cpu_to_be32(ff_args->num_dev);
2081 	for (i = 0; i < ff_args->num_dev; i++)
2082 		ff_layout_encode_ff_iostat(xdr,
2083 				&args->layout->plh_stateid,
2084 				&ff_args->devinfo[i]);
2085 }
2086 
2087 static void
2088 ff_layout_free_iostats_array(struct nfs42_layoutstat_devinfo *devinfo,
2089 		unsigned int num_entries)
2090 {
2091 	unsigned int i;
2092 
2093 	for (i = 0; i < num_entries; i++) {
2094 		if (!devinfo[i].ld_private.ops)
2095 			continue;
2096 		if (!devinfo[i].ld_private.ops->free)
2097 			continue;
2098 		devinfo[i].ld_private.ops->free(&devinfo[i].ld_private);
2099 	}
2100 }
2101 
2102 static struct nfs4_deviceid_node *
2103 ff_layout_alloc_deviceid_node(struct nfs_server *server,
2104 			      struct pnfs_device *pdev, gfp_t gfp_flags)
2105 {
2106 	struct nfs4_ff_layout_ds *dsaddr;
2107 
2108 	dsaddr = nfs4_ff_alloc_deviceid_node(server, pdev, gfp_flags);
2109 	if (!dsaddr)
2110 		return NULL;
2111 	return &dsaddr->id_node;
2112 }
2113 
2114 static void
2115 ff_layout_encode_layoutreturn(struct xdr_stream *xdr,
2116 		const void *voidargs,
2117 		const struct nfs4_xdr_opaque_data *ff_opaque)
2118 {
2119 	const struct nfs4_layoutreturn_args *args = voidargs;
2120 	struct nfs4_flexfile_layoutreturn_args *ff_args = ff_opaque->data;
2121 	struct xdr_buf tmp_buf = {
2122 		.head = {
2123 			[0] = {
2124 				.iov_base = page_address(ff_args->pages[0]),
2125 			},
2126 		},
2127 		.buflen = PAGE_SIZE,
2128 	};
2129 	struct xdr_stream tmp_xdr;
2130 	__be32 *start;
2131 
2132 	dprintk("%s: Begin\n", __func__);
2133 
2134 	xdr_init_encode(&tmp_xdr, &tmp_buf, NULL, NULL);
2135 
2136 	ff_layout_encode_ioerr(&tmp_xdr, args, ff_args);
2137 	ff_layout_encode_iostats_array(&tmp_xdr, args, ff_args);
2138 
2139 	start = xdr_reserve_space(xdr, 4);
2140 	*start = cpu_to_be32(tmp_buf.len);
2141 	xdr_write_pages(xdr, ff_args->pages, 0, tmp_buf.len);
2142 
2143 	dprintk("%s: Return\n", __func__);
2144 }
2145 
2146 static void
2147 ff_layout_free_layoutreturn(struct nfs4_xdr_opaque_data *args)
2148 {
2149 	struct nfs4_flexfile_layoutreturn_args *ff_args;
2150 
2151 	if (!args->data)
2152 		return;
2153 	ff_args = args->data;
2154 	args->data = NULL;
2155 
2156 	ff_layout_free_ds_ioerr(&ff_args->errors);
2157 	ff_layout_free_iostats_array(ff_args->devinfo, ff_args->num_dev);
2158 
2159 	put_page(ff_args->pages[0]);
2160 	kfree(ff_args);
2161 }
2162 
2163 static const struct nfs4_xdr_opaque_ops layoutreturn_ops = {
2164 	.encode = ff_layout_encode_layoutreturn,
2165 	.free = ff_layout_free_layoutreturn,
2166 };
2167 
2168 static int
2169 ff_layout_prepare_layoutreturn(struct nfs4_layoutreturn_args *args)
2170 {
2171 	struct nfs4_flexfile_layoutreturn_args *ff_args;
2172 	struct nfs4_flexfile_layout *ff_layout = FF_LAYOUT_FROM_HDR(args->layout);
2173 
2174 	ff_args = kmalloc(sizeof(*ff_args), GFP_KERNEL);
2175 	if (!ff_args)
2176 		goto out_nomem;
2177 	ff_args->pages[0] = alloc_page(GFP_KERNEL);
2178 	if (!ff_args->pages[0])
2179 		goto out_nomem_free;
2180 
2181 	INIT_LIST_HEAD(&ff_args->errors);
2182 	ff_args->num_errors = ff_layout_fetch_ds_ioerr(args->layout,
2183 			&args->range, &ff_args->errors,
2184 			FF_LAYOUTRETURN_MAXERR);
2185 
2186 	spin_lock(&args->inode->i_lock);
2187 	ff_args->num_dev = ff_layout_mirror_prepare_stats(&ff_layout->generic_hdr,
2188 			&ff_args->devinfo[0], ARRAY_SIZE(ff_args->devinfo));
2189 	spin_unlock(&args->inode->i_lock);
2190 
2191 	args->ld_private->ops = &layoutreturn_ops;
2192 	args->ld_private->data = ff_args;
2193 	return 0;
2194 out_nomem_free:
2195 	kfree(ff_args);
2196 out_nomem:
2197 	return -ENOMEM;
2198 }
2199 
2200 #ifdef CONFIG_NFS_V4_2
2201 void
2202 ff_layout_send_layouterror(struct pnfs_layout_segment *lseg)
2203 {
2204 	struct pnfs_layout_hdr *lo = lseg->pls_layout;
2205 	struct nfs42_layout_error *errors;
2206 	LIST_HEAD(head);
2207 
2208 	if (!nfs_server_capable(lo->plh_inode, NFS_CAP_LAYOUTERROR))
2209 		return;
2210 	ff_layout_fetch_ds_ioerr(lo, &lseg->pls_range, &head, -1);
2211 	if (list_empty(&head))
2212 		return;
2213 
2214 	errors = kmalloc_array(NFS42_LAYOUTERROR_MAX,
2215 			sizeof(*errors), GFP_NOFS);
2216 	if (errors != NULL) {
2217 		const struct nfs4_ff_layout_ds_err *pos;
2218 		size_t n = 0;
2219 
2220 		list_for_each_entry(pos, &head, list) {
2221 			errors[n].offset = pos->offset;
2222 			errors[n].length = pos->length;
2223 			nfs4_stateid_copy(&errors[n].stateid, &pos->stateid);
2224 			errors[n].errors[0].dev_id = pos->deviceid;
2225 			errors[n].errors[0].status = pos->status;
2226 			errors[n].errors[0].opnum = pos->opnum;
2227 			n++;
2228 			if (!list_is_last(&pos->list, &head) &&
2229 			    n < NFS42_LAYOUTERROR_MAX)
2230 				continue;
2231 			if (nfs42_proc_layouterror(lseg, errors, n) < 0)
2232 				break;
2233 			n = 0;
2234 		}
2235 		kfree(errors);
2236 	}
2237 	ff_layout_free_ds_ioerr(&head);
2238 }
2239 #else
2240 void
2241 ff_layout_send_layouterror(struct pnfs_layout_segment *lseg)
2242 {
2243 }
2244 #endif
2245 
2246 static int
2247 ff_layout_ntop4(const struct sockaddr *sap, char *buf, const size_t buflen)
2248 {
2249 	const struct sockaddr_in *sin = (struct sockaddr_in *)sap;
2250 
2251 	return snprintf(buf, buflen, "%pI4", &sin->sin_addr);
2252 }
2253 
2254 static size_t
2255 ff_layout_ntop6_noscopeid(const struct sockaddr *sap, char *buf,
2256 			  const int buflen)
2257 {
2258 	const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sap;
2259 	const struct in6_addr *addr = &sin6->sin6_addr;
2260 
2261 	/*
2262 	 * RFC 4291, Section 2.2.2
2263 	 *
2264 	 * Shorthanded ANY address
2265 	 */
2266 	if (ipv6_addr_any(addr))
2267 		return snprintf(buf, buflen, "::");
2268 
2269 	/*
2270 	 * RFC 4291, Section 2.2.2
2271 	 *
2272 	 * Shorthanded loopback address
2273 	 */
2274 	if (ipv6_addr_loopback(addr))
2275 		return snprintf(buf, buflen, "::1");
2276 
2277 	/*
2278 	 * RFC 4291, Section 2.2.3
2279 	 *
2280 	 * Special presentation address format for mapped v4
2281 	 * addresses.
2282 	 */
2283 	if (ipv6_addr_v4mapped(addr))
2284 		return snprintf(buf, buflen, "::ffff:%pI4",
2285 					&addr->s6_addr32[3]);
2286 
2287 	/*
2288 	 * RFC 4291, Section 2.2.1
2289 	 */
2290 	return snprintf(buf, buflen, "%pI6c", addr);
2291 }
2292 
2293 /* Derived from rpc_sockaddr2uaddr */
2294 static void
2295 ff_layout_encode_netaddr(struct xdr_stream *xdr, struct nfs4_pnfs_ds_addr *da)
2296 {
2297 	struct sockaddr *sap = (struct sockaddr *)&da->da_addr;
2298 	char portbuf[RPCBIND_MAXUADDRPLEN];
2299 	char addrbuf[RPCBIND_MAXUADDRLEN];
2300 	char *netid;
2301 	unsigned short port;
2302 	int len, netid_len;
2303 	__be32 *p;
2304 
2305 	switch (sap->sa_family) {
2306 	case AF_INET:
2307 		if (ff_layout_ntop4(sap, addrbuf, sizeof(addrbuf)) == 0)
2308 			return;
2309 		port = ntohs(((struct sockaddr_in *)sap)->sin_port);
2310 		netid = "tcp";
2311 		netid_len = 3;
2312 		break;
2313 	case AF_INET6:
2314 		if (ff_layout_ntop6_noscopeid(sap, addrbuf, sizeof(addrbuf)) == 0)
2315 			return;
2316 		port = ntohs(((struct sockaddr_in6 *)sap)->sin6_port);
2317 		netid = "tcp6";
2318 		netid_len = 4;
2319 		break;
2320 	default:
2321 		/* we only support tcp and tcp6 */
2322 		WARN_ON_ONCE(1);
2323 		return;
2324 	}
2325 
2326 	snprintf(portbuf, sizeof(portbuf), ".%u.%u", port >> 8, port & 0xff);
2327 	len = strlcat(addrbuf, portbuf, sizeof(addrbuf));
2328 
2329 	p = xdr_reserve_space(xdr, 4 + netid_len);
2330 	xdr_encode_opaque(p, netid, netid_len);
2331 
2332 	p = xdr_reserve_space(xdr, 4 + len);
2333 	xdr_encode_opaque(p, addrbuf, len);
2334 }
2335 
2336 static void
2337 ff_layout_encode_nfstime(struct xdr_stream *xdr,
2338 			 ktime_t t)
2339 {
2340 	struct timespec64 ts;
2341 	__be32 *p;
2342 
2343 	p = xdr_reserve_space(xdr, 12);
2344 	ts = ktime_to_timespec64(t);
2345 	p = xdr_encode_hyper(p, ts.tv_sec);
2346 	*p++ = cpu_to_be32(ts.tv_nsec);
2347 }
2348 
2349 static void
2350 ff_layout_encode_io_latency(struct xdr_stream *xdr,
2351 			    struct nfs4_ff_io_stat *stat)
2352 {
2353 	__be32 *p;
2354 
2355 	p = xdr_reserve_space(xdr, 5 * 8);
2356 	p = xdr_encode_hyper(p, stat->ops_requested);
2357 	p = xdr_encode_hyper(p, stat->bytes_requested);
2358 	p = xdr_encode_hyper(p, stat->ops_completed);
2359 	p = xdr_encode_hyper(p, stat->bytes_completed);
2360 	p = xdr_encode_hyper(p, stat->bytes_not_delivered);
2361 	ff_layout_encode_nfstime(xdr, stat->total_busy_time);
2362 	ff_layout_encode_nfstime(xdr, stat->aggregate_completion_time);
2363 }
2364 
2365 static void
2366 ff_layout_encode_ff_layoutupdate(struct xdr_stream *xdr,
2367 			      const struct nfs42_layoutstat_devinfo *devinfo,
2368 			      struct nfs4_ff_layout_mirror *mirror)
2369 {
2370 	struct nfs4_pnfs_ds_addr *da;
2371 	struct nfs4_pnfs_ds *ds = mirror->mirror_ds->ds;
2372 	struct nfs_fh *fh = &mirror->fh_versions[0];
2373 	__be32 *p;
2374 
2375 	da = list_first_entry(&ds->ds_addrs, struct nfs4_pnfs_ds_addr, da_node);
2376 	dprintk("%s: DS %s: encoding address %s\n",
2377 		__func__, ds->ds_remotestr, da->da_remotestr);
2378 	/* netaddr4 */
2379 	ff_layout_encode_netaddr(xdr, da);
2380 	/* nfs_fh4 */
2381 	p = xdr_reserve_space(xdr, 4 + fh->size);
2382 	xdr_encode_opaque(p, fh->data, fh->size);
2383 	/* ff_io_latency4 read */
2384 	spin_lock(&mirror->lock);
2385 	ff_layout_encode_io_latency(xdr, &mirror->read_stat.io_stat);
2386 	/* ff_io_latency4 write */
2387 	ff_layout_encode_io_latency(xdr, &mirror->write_stat.io_stat);
2388 	spin_unlock(&mirror->lock);
2389 	/* nfstime4 */
2390 	ff_layout_encode_nfstime(xdr, ktime_sub(ktime_get(), mirror->start_time));
2391 	/* bool */
2392 	p = xdr_reserve_space(xdr, 4);
2393 	*p = cpu_to_be32(false);
2394 }
2395 
2396 static void
2397 ff_layout_encode_layoutstats(struct xdr_stream *xdr, const void *args,
2398 			     const struct nfs4_xdr_opaque_data *opaque)
2399 {
2400 	struct nfs42_layoutstat_devinfo *devinfo = container_of(opaque,
2401 			struct nfs42_layoutstat_devinfo, ld_private);
2402 	__be32 *start;
2403 
2404 	/* layoutupdate length */
2405 	start = xdr_reserve_space(xdr, 4);
2406 	ff_layout_encode_ff_layoutupdate(xdr, devinfo, opaque->data);
2407 
2408 	*start = cpu_to_be32((xdr->p - start - 1) * 4);
2409 }
2410 
2411 static void
2412 ff_layout_free_layoutstats(struct nfs4_xdr_opaque_data *opaque)
2413 {
2414 	struct nfs4_ff_layout_mirror *mirror = opaque->data;
2415 
2416 	ff_layout_put_mirror(mirror);
2417 }
2418 
2419 static const struct nfs4_xdr_opaque_ops layoutstat_ops = {
2420 	.encode = ff_layout_encode_layoutstats,
2421 	.free	= ff_layout_free_layoutstats,
2422 };
2423 
2424 static int
2425 ff_layout_mirror_prepare_stats(struct pnfs_layout_hdr *lo,
2426 			       struct nfs42_layoutstat_devinfo *devinfo,
2427 			       int dev_limit)
2428 {
2429 	struct nfs4_flexfile_layout *ff_layout = FF_LAYOUT_FROM_HDR(lo);
2430 	struct nfs4_ff_layout_mirror *mirror;
2431 	struct nfs4_deviceid_node *dev;
2432 	int i = 0;
2433 
2434 	list_for_each_entry(mirror, &ff_layout->mirrors, mirrors) {
2435 		if (i >= dev_limit)
2436 			break;
2437 		if (IS_ERR_OR_NULL(mirror->mirror_ds))
2438 			continue;
2439 		if (!test_and_clear_bit(NFS4_FF_MIRROR_STAT_AVAIL, &mirror->flags))
2440 			continue;
2441 		/* mirror refcount put in cleanup_layoutstats */
2442 		if (!refcount_inc_not_zero(&mirror->ref))
2443 			continue;
2444 		dev = &mirror->mirror_ds->id_node;
2445 		memcpy(&devinfo->dev_id, &dev->deviceid, NFS4_DEVICEID4_SIZE);
2446 		devinfo->offset = 0;
2447 		devinfo->length = NFS4_MAX_UINT64;
2448 		spin_lock(&mirror->lock);
2449 		devinfo->read_count = mirror->read_stat.io_stat.ops_completed;
2450 		devinfo->read_bytes = mirror->read_stat.io_stat.bytes_completed;
2451 		devinfo->write_count = mirror->write_stat.io_stat.ops_completed;
2452 		devinfo->write_bytes = mirror->write_stat.io_stat.bytes_completed;
2453 		spin_unlock(&mirror->lock);
2454 		devinfo->layout_type = LAYOUT_FLEX_FILES;
2455 		devinfo->ld_private.ops = &layoutstat_ops;
2456 		devinfo->ld_private.data = mirror;
2457 
2458 		devinfo++;
2459 		i++;
2460 	}
2461 	return i;
2462 }
2463 
2464 static int
2465 ff_layout_prepare_layoutstats(struct nfs42_layoutstat_args *args)
2466 {
2467 	struct nfs4_flexfile_layout *ff_layout;
2468 	const int dev_count = PNFS_LAYOUTSTATS_MAXDEV;
2469 
2470 	/* For now, send at most PNFS_LAYOUTSTATS_MAXDEV statistics */
2471 	args->devinfo = kmalloc_array(dev_count, sizeof(*args->devinfo), GFP_NOIO);
2472 	if (!args->devinfo)
2473 		return -ENOMEM;
2474 
2475 	spin_lock(&args->inode->i_lock);
2476 	ff_layout = FF_LAYOUT_FROM_HDR(NFS_I(args->inode)->layout);
2477 	args->num_dev = ff_layout_mirror_prepare_stats(&ff_layout->generic_hdr,
2478 			&args->devinfo[0], dev_count);
2479 	spin_unlock(&args->inode->i_lock);
2480 	if (!args->num_dev) {
2481 		kfree(args->devinfo);
2482 		args->devinfo = NULL;
2483 		return -ENOENT;
2484 	}
2485 
2486 	return 0;
2487 }
2488 
2489 static int
2490 ff_layout_set_layoutdriver(struct nfs_server *server,
2491 		const struct nfs_fh *dummy)
2492 {
2493 #if IS_ENABLED(CONFIG_NFS_V4_2)
2494 	server->caps |= NFS_CAP_LAYOUTSTATS;
2495 #endif
2496 	return 0;
2497 }
2498 
2499 static struct pnfs_layoutdriver_type flexfilelayout_type = {
2500 	.id			= LAYOUT_FLEX_FILES,
2501 	.name			= "LAYOUT_FLEX_FILES",
2502 	.owner			= THIS_MODULE,
2503 	.flags			= PNFS_LAYOUTGET_ON_OPEN,
2504 	.max_layoutget_response	= 4096, /* 1 page or so... */
2505 	.set_layoutdriver	= ff_layout_set_layoutdriver,
2506 	.alloc_layout_hdr	= ff_layout_alloc_layout_hdr,
2507 	.free_layout_hdr	= ff_layout_free_layout_hdr,
2508 	.alloc_lseg		= ff_layout_alloc_lseg,
2509 	.free_lseg		= ff_layout_free_lseg,
2510 	.add_lseg		= ff_layout_add_lseg,
2511 	.pg_read_ops		= &ff_layout_pg_read_ops,
2512 	.pg_write_ops		= &ff_layout_pg_write_ops,
2513 	.get_ds_info		= ff_layout_get_ds_info,
2514 	.free_deviceid_node	= ff_layout_free_deviceid_node,
2515 	.mark_request_commit	= pnfs_layout_mark_request_commit,
2516 	.clear_request_commit	= pnfs_generic_clear_request_commit,
2517 	.scan_commit_lists	= pnfs_generic_scan_commit_lists,
2518 	.recover_commit_reqs	= pnfs_generic_recover_commit_reqs,
2519 	.commit_pagelist	= ff_layout_commit_pagelist,
2520 	.read_pagelist		= ff_layout_read_pagelist,
2521 	.write_pagelist		= ff_layout_write_pagelist,
2522 	.alloc_deviceid_node    = ff_layout_alloc_deviceid_node,
2523 	.prepare_layoutreturn   = ff_layout_prepare_layoutreturn,
2524 	.sync			= pnfs_nfs_generic_sync,
2525 	.prepare_layoutstats	= ff_layout_prepare_layoutstats,
2526 };
2527 
2528 static int __init nfs4flexfilelayout_init(void)
2529 {
2530 	printk(KERN_INFO "%s: NFSv4 Flexfile Layout Driver Registering...\n",
2531 	       __func__);
2532 	return pnfs_register_layoutdriver(&flexfilelayout_type);
2533 }
2534 
2535 static void __exit nfs4flexfilelayout_exit(void)
2536 {
2537 	printk(KERN_INFO "%s: NFSv4 Flexfile Layout Driver Unregistering...\n",
2538 	       __func__);
2539 	pnfs_unregister_layoutdriver(&flexfilelayout_type);
2540 }
2541 
2542 MODULE_ALIAS("nfs-layouttype4-4");
2543 
2544 MODULE_LICENSE("GPL");
2545 MODULE_DESCRIPTION("The NFSv4 flexfile layout driver");
2546 
2547 module_init(nfs4flexfilelayout_init);
2548 module_exit(nfs4flexfilelayout_exit);
2549 
2550 module_param(io_maxretrans, ushort, 0644);
2551 MODULE_PARM_DESC(io_maxretrans, "The  number of times the NFSv4.1 client "
2552 			"retries an I/O request before returning an error. ");
2553