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