NFSv4.1: cleanup filelayout invalid deviceid handling
[cascardo/linux.git] / fs / nfs / nfs4filelayout.c
1 /*
2  *  Module for the pnfs nfs4 file layout driver.
3  *  Defines all I/O and Policy interface operations, plus code
4  *  to register itself with the pNFS client.
5  *
6  *  Copyright (c) 2002
7  *  The Regents of the University of Michigan
8  *  All Rights Reserved
9  *
10  *  Dean Hildebrand <dhildebz@umich.edu>
11  *
12  *  Permission is granted to use, copy, create derivative works, and
13  *  redistribute this software and such derivative works for any purpose,
14  *  so long as the name of the University of Michigan is not used in
15  *  any advertising or publicity pertaining to the use or distribution
16  *  of this software without specific, written prior authorization. If
17  *  the above copyright notice or any other identification of the
18  *  University of Michigan is included in any copy of any portion of
19  *  this software, then the disclaimer below must also be included.
20  *
21  *  This software is provided as is, without representation or warranty
22  *  of any kind either express or implied, including without limitation
23  *  the implied warranties of merchantability, fitness for a particular
24  *  purpose, or noninfringement.  The Regents of the University of
25  *  Michigan shall not be liable for any damages, including special,
26  *  indirect, incidental, or consequential damages, with respect to any
27  *  claim arising out of or in connection with the use of the software,
28  *  even if it has been or is hereafter advised of the possibility of
29  *  such damages.
30  */
31
32 #include <linux/nfs_fs.h>
33 #include <linux/nfs_page.h>
34 #include <linux/module.h>
35
36 #include <linux/sunrpc/metrics.h>
37
38 #include "internal.h"
39 #include "delegation.h"
40 #include "nfs4filelayout.h"
41
42 #define NFSDBG_FACILITY         NFSDBG_PNFS_LD
43
44 MODULE_LICENSE("GPL");
45 MODULE_AUTHOR("Dean Hildebrand <dhildebz@umich.edu>");
46 MODULE_DESCRIPTION("The NFSv4 file layout driver");
47
48 #define FILELAYOUT_POLL_RETRY_MAX     (15*HZ)
49
50 static loff_t
51 filelayout_get_dense_offset(struct nfs4_filelayout_segment *flseg,
52                             loff_t offset)
53 {
54         u32 stripe_width = flseg->stripe_unit * flseg->dsaddr->stripe_count;
55         u64 stripe_no;
56         u32 rem;
57
58         offset -= flseg->pattern_offset;
59         stripe_no = div_u64(offset, stripe_width);
60         div_u64_rem(offset, flseg->stripe_unit, &rem);
61
62         return stripe_no * flseg->stripe_unit + rem;
63 }
64
65 /* This function is used by the layout driver to calculate the
66  * offset of the file on the dserver based on whether the
67  * layout type is STRIPE_DENSE or STRIPE_SPARSE
68  */
69 static loff_t
70 filelayout_get_dserver_offset(struct pnfs_layout_segment *lseg, loff_t offset)
71 {
72         struct nfs4_filelayout_segment *flseg = FILELAYOUT_LSEG(lseg);
73
74         switch (flseg->stripe_type) {
75         case STRIPE_SPARSE:
76                 return offset;
77
78         case STRIPE_DENSE:
79                 return filelayout_get_dense_offset(flseg, offset);
80         }
81
82         BUG();
83 }
84
85 static int filelayout_async_handle_error(struct rpc_task *task,
86                                          struct nfs4_state *state,
87                                          struct nfs_client *clp,
88                                          int *reset)
89 {
90         struct nfs_server *mds_server = NFS_SERVER(state->inode);
91         struct nfs_client *mds_client = mds_server->nfs_client;
92
93         if (task->tk_status >= 0)
94                 return 0;
95         *reset = 0;
96
97         switch (task->tk_status) {
98         /* MDS state errors */
99         case -NFS4ERR_DELEG_REVOKED:
100         case -NFS4ERR_ADMIN_REVOKED:
101         case -NFS4ERR_BAD_STATEID:
102                 nfs_remove_bad_delegation(state->inode);
103         case -NFS4ERR_OPENMODE:
104                 nfs4_schedule_stateid_recovery(mds_server, state);
105                 goto wait_on_recovery;
106         case -NFS4ERR_EXPIRED:
107                 nfs4_schedule_stateid_recovery(mds_server, state);
108                 nfs4_schedule_lease_recovery(mds_client);
109                 goto wait_on_recovery;
110         /* DS session errors */
111         case -NFS4ERR_BADSESSION:
112         case -NFS4ERR_BADSLOT:
113         case -NFS4ERR_BAD_HIGH_SLOT:
114         case -NFS4ERR_DEADSESSION:
115         case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
116         case -NFS4ERR_SEQ_FALSE_RETRY:
117         case -NFS4ERR_SEQ_MISORDERED:
118                 dprintk("%s ERROR %d, Reset session. Exchangeid "
119                         "flags 0x%x\n", __func__, task->tk_status,
120                         clp->cl_exchange_flags);
121                 nfs4_schedule_session_recovery(clp->cl_session);
122                 break;
123         case -NFS4ERR_DELAY:
124         case -NFS4ERR_GRACE:
125         case -EKEYEXPIRED:
126                 rpc_delay(task, FILELAYOUT_POLL_RETRY_MAX);
127                 break;
128         case -NFS4ERR_RETRY_UNCACHED_REP:
129                 break;
130         default:
131                 dprintk("%s DS error. Retry through MDS %d\n", __func__,
132                         task->tk_status);
133                 *reset = 1;
134                 break;
135         }
136 out:
137         task->tk_status = 0;
138         return -EAGAIN;
139 wait_on_recovery:
140         rpc_sleep_on(&mds_client->cl_rpcwaitq, task, NULL);
141         if (test_bit(NFS4CLNT_MANAGER_RUNNING, &mds_client->cl_state) == 0)
142                 rpc_wake_up_queued_task(&mds_client->cl_rpcwaitq, task);
143         goto out;
144 }
145
146 /* NFS_PROTO call done callback routines */
147
148 static int filelayout_read_done_cb(struct rpc_task *task,
149                                 struct nfs_read_data *data)
150 {
151         struct nfs_pgio_header *hdr = data->header;
152         int reset = 0;
153
154         dprintk("%s DS read\n", __func__);
155
156         if (filelayout_async_handle_error(task, data->args.context->state,
157                                           data->ds_clp, &reset) == -EAGAIN) {
158                 dprintk("%s calling restart ds_clp %p ds_clp->cl_session %p\n",
159                         __func__, data->ds_clp, data->ds_clp->cl_session);
160                 if (reset) {
161                         pnfs_set_lo_fail(hdr->lseg);
162                         nfs4_reset_read(task, data);
163                 }
164                 rpc_restart_call_prepare(task);
165                 return -EAGAIN;
166         }
167
168         return 0;
169 }
170
171 /*
172  * We reference the rpc_cred of the first WRITE that triggers the need for
173  * a LAYOUTCOMMIT, and use it to send the layoutcommit compound.
174  * rfc5661 is not clear about which credential should be used.
175  */
176 static void
177 filelayout_set_layoutcommit(struct nfs_write_data *wdata)
178 {
179         struct nfs_pgio_header *hdr = wdata->header;
180
181         if (FILELAYOUT_LSEG(hdr->lseg)->commit_through_mds ||
182             wdata->res.verf->committed == NFS_FILE_SYNC)
183                 return;
184
185         pnfs_set_layoutcommit(wdata);
186         dprintk("%s ionde %lu pls_end_pos %lu\n", __func__, hdr->inode->i_ino,
187                 (unsigned long) NFS_I(hdr->inode)->layout->plh_lwb);
188 }
189
190 /*
191  * Call ops for the async read/write cases
192  * In the case of dense layouts, the offset needs to be reset to its
193  * original value.
194  */
195 static void filelayout_read_prepare(struct rpc_task *task, void *data)
196 {
197         struct nfs_read_data *rdata = data;
198
199         rdata->read_done_cb = filelayout_read_done_cb;
200
201         if (nfs41_setup_sequence(rdata->ds_clp->cl_session,
202                                 &rdata->args.seq_args, &rdata->res.seq_res,
203                                 task))
204                 return;
205
206         rpc_call_start(task);
207 }
208
209 static void filelayout_read_call_done(struct rpc_task *task, void *data)
210 {
211         struct nfs_read_data *rdata = data;
212
213         dprintk("--> %s task->tk_status %d\n", __func__, task->tk_status);
214
215         /* Note this may cause RPC to be resent */
216         rdata->header->mds_ops->rpc_call_done(task, data);
217 }
218
219 static void filelayout_read_count_stats(struct rpc_task *task, void *data)
220 {
221         struct nfs_read_data *rdata = data;
222
223         rpc_count_iostats(task, NFS_SERVER(rdata->header->inode)->client->cl_metrics);
224 }
225
226 static void filelayout_read_release(void *data)
227 {
228         struct nfs_read_data *rdata = data;
229
230         rdata->header->mds_ops->rpc_release(data);
231 }
232
233 static int filelayout_write_done_cb(struct rpc_task *task,
234                                 struct nfs_write_data *data)
235 {
236         struct nfs_pgio_header *hdr = data->header;
237         int reset = 0;
238
239         if (filelayout_async_handle_error(task, data->args.context->state,
240                                           data->ds_clp, &reset) == -EAGAIN) {
241                 dprintk("%s calling restart ds_clp %p ds_clp->cl_session %p\n",
242                         __func__, data->ds_clp, data->ds_clp->cl_session);
243                 if (reset) {
244                         pnfs_set_lo_fail(hdr->lseg);
245                         nfs4_reset_write(task, data);
246                 }
247                 rpc_restart_call_prepare(task);
248                 return -EAGAIN;
249         }
250
251         filelayout_set_layoutcommit(data);
252         return 0;
253 }
254
255 /* Fake up some data that will cause nfs_commit_release to retry the writes. */
256 static void prepare_to_resend_writes(struct nfs_commit_data *data)
257 {
258         struct nfs_page *first = nfs_list_entry(data->pages.next);
259
260         data->task.tk_status = 0;
261         memcpy(data->verf.verifier, first->wb_verf.verifier,
262                sizeof(first->wb_verf.verifier));
263         data->verf.verifier[0]++; /* ensure verifier mismatch */
264 }
265
266 static int filelayout_commit_done_cb(struct rpc_task *task,
267                                      struct nfs_commit_data *data)
268 {
269         int reset = 0;
270
271         if (filelayout_async_handle_error(task, data->context->state,
272                                           data->ds_clp, &reset) == -EAGAIN) {
273                 dprintk("%s calling restart ds_clp %p ds_clp->cl_session %p\n",
274                         __func__, data->ds_clp, data->ds_clp->cl_session);
275                 if (reset) {
276                         prepare_to_resend_writes(data);
277                         pnfs_set_lo_fail(data->lseg);
278                 } else
279                         rpc_restart_call_prepare(task);
280                 return -EAGAIN;
281         }
282
283         return 0;
284 }
285
286 static void filelayout_write_prepare(struct rpc_task *task, void *data)
287 {
288         struct nfs_write_data *wdata = data;
289
290         if (nfs41_setup_sequence(wdata->ds_clp->cl_session,
291                                 &wdata->args.seq_args, &wdata->res.seq_res,
292                                 task))
293                 return;
294
295         rpc_call_start(task);
296 }
297
298 static void filelayout_write_call_done(struct rpc_task *task, void *data)
299 {
300         struct nfs_write_data *wdata = data;
301
302         /* Note this may cause RPC to be resent */
303         wdata->header->mds_ops->rpc_call_done(task, data);
304 }
305
306 static void filelayout_write_count_stats(struct rpc_task *task, void *data)
307 {
308         struct nfs_write_data *wdata = data;
309
310         rpc_count_iostats(task, NFS_SERVER(wdata->header->inode)->client->cl_metrics);
311 }
312
313 static void filelayout_write_release(void *data)
314 {
315         struct nfs_write_data *wdata = data;
316
317         wdata->header->mds_ops->rpc_release(data);
318 }
319
320 static void filelayout_commit_prepare(struct rpc_task *task, void *data)
321 {
322         struct nfs_commit_data *wdata = data;
323
324         if (nfs41_setup_sequence(wdata->ds_clp->cl_session,
325                                 &wdata->args.seq_args, &wdata->res.seq_res,
326                                 task))
327                 return;
328
329         rpc_call_start(task);
330 }
331
332 static void filelayout_write_commit_done(struct rpc_task *task, void *data)
333 {
334         struct nfs_commit_data *wdata = data;
335
336         /* Note this may cause RPC to be resent */
337         wdata->mds_ops->rpc_call_done(task, data);
338 }
339
340 static void filelayout_commit_count_stats(struct rpc_task *task, void *data)
341 {
342         struct nfs_commit_data *cdata = data;
343
344         rpc_count_iostats(task, NFS_SERVER(cdata->inode)->client->cl_metrics);
345 }
346
347 static void filelayout_commit_release(void *calldata)
348 {
349         struct nfs_commit_data *data = calldata;
350
351         data->completion_ops->completion(data);
352         put_lseg(data->lseg);
353         nfs_commitdata_release(data);
354 }
355
356 static const struct rpc_call_ops filelayout_read_call_ops = {
357         .rpc_call_prepare = filelayout_read_prepare,
358         .rpc_call_done = filelayout_read_call_done,
359         .rpc_count_stats = filelayout_read_count_stats,
360         .rpc_release = filelayout_read_release,
361 };
362
363 static const struct rpc_call_ops filelayout_write_call_ops = {
364         .rpc_call_prepare = filelayout_write_prepare,
365         .rpc_call_done = filelayout_write_call_done,
366         .rpc_count_stats = filelayout_write_count_stats,
367         .rpc_release = filelayout_write_release,
368 };
369
370 static const struct rpc_call_ops filelayout_commit_call_ops = {
371         .rpc_call_prepare = filelayout_commit_prepare,
372         .rpc_call_done = filelayout_write_commit_done,
373         .rpc_count_stats = filelayout_commit_count_stats,
374         .rpc_release = filelayout_commit_release,
375 };
376
377 static enum pnfs_try_status
378 filelayout_read_pagelist(struct nfs_read_data *data)
379 {
380         struct nfs_pgio_header *hdr = data->header;
381         struct pnfs_layout_segment *lseg = hdr->lseg;
382         struct nfs4_pnfs_ds *ds;
383         loff_t offset = data->args.offset;
384         u32 j, idx;
385         struct nfs_fh *fh;
386         int status;
387
388         dprintk("--> %s ino %lu pgbase %u req %Zu@%llu\n",
389                 __func__, hdr->inode->i_ino,
390                 data->args.pgbase, (size_t)data->args.count, offset);
391
392         /* Retrieve the correct rpc_client for the byte range */
393         j = nfs4_fl_calc_j_index(lseg, offset);
394         idx = nfs4_fl_calc_ds_index(lseg, j);
395         ds = nfs4_fl_prepare_ds(lseg, idx);
396         if (!ds) {
397                 /* Either layout fh index faulty, or ds connect failed */
398                 set_bit(lo_fail_bit(IOMODE_RW), &lseg->pls_layout->plh_flags);
399                 set_bit(lo_fail_bit(IOMODE_READ), &lseg->pls_layout->plh_flags);
400                 return PNFS_NOT_ATTEMPTED;
401         }
402         dprintk("%s USE DS: %s\n", __func__, ds->ds_remotestr);
403
404         /* No multipath support. Use first DS */
405         data->ds_clp = ds->ds_clp;
406         fh = nfs4_fl_select_ds_fh(lseg, j);
407         if (fh)
408                 data->args.fh = fh;
409
410         data->args.offset = filelayout_get_dserver_offset(lseg, offset);
411         data->mds_offset = offset;
412
413         /* Perform an asynchronous read to ds */
414         status = nfs_initiate_read(ds->ds_clp->cl_rpcclient, data,
415                                    &filelayout_read_call_ops);
416         BUG_ON(status != 0);
417         return PNFS_ATTEMPTED;
418 }
419
420 /* Perform async writes. */
421 static enum pnfs_try_status
422 filelayout_write_pagelist(struct nfs_write_data *data, int sync)
423 {
424         struct nfs_pgio_header *hdr = data->header;
425         struct pnfs_layout_segment *lseg = hdr->lseg;
426         struct nfs4_pnfs_ds *ds;
427         loff_t offset = data->args.offset;
428         u32 j, idx;
429         struct nfs_fh *fh;
430         int status;
431
432         /* Retrieve the correct rpc_client for the byte range */
433         j = nfs4_fl_calc_j_index(lseg, offset);
434         idx = nfs4_fl_calc_ds_index(lseg, j);
435         ds = nfs4_fl_prepare_ds(lseg, idx);
436         if (!ds) {
437                 set_bit(lo_fail_bit(IOMODE_RW), &lseg->pls_layout->plh_flags);
438                 set_bit(lo_fail_bit(IOMODE_READ), &lseg->pls_layout->plh_flags);
439                 return PNFS_NOT_ATTEMPTED;
440         }
441         dprintk("%s ino %lu sync %d req %Zu@%llu DS: %s\n", __func__,
442                 hdr->inode->i_ino, sync, (size_t) data->args.count, offset,
443                 ds->ds_remotestr);
444
445         data->write_done_cb = filelayout_write_done_cb;
446         data->ds_clp = ds->ds_clp;
447         fh = nfs4_fl_select_ds_fh(lseg, j);
448         if (fh)
449                 data->args.fh = fh;
450         /*
451          * Get the file offset on the dserver. Set the write offset to
452          * this offset and save the original offset.
453          */
454         data->args.offset = filelayout_get_dserver_offset(lseg, offset);
455
456         /* Perform an asynchronous write */
457         status = nfs_initiate_write(ds->ds_clp->cl_rpcclient, data,
458                                     &filelayout_write_call_ops, sync);
459         BUG_ON(status != 0);
460         return PNFS_ATTEMPTED;
461 }
462
463 /*
464  * filelayout_check_layout()
465  *
466  * Make sure layout segment parameters are sane WRT the device.
467  * At this point no generic layer initialization of the lseg has occurred,
468  * and nothing has been added to the layout_hdr cache.
469  *
470  */
471 static int
472 filelayout_check_layout(struct pnfs_layout_hdr *lo,
473                         struct nfs4_filelayout_segment *fl,
474                         struct nfs4_layoutget_res *lgr,
475                         struct nfs4_deviceid *id,
476                         gfp_t gfp_flags)
477 {
478         struct nfs4_deviceid_node *d;
479         struct nfs4_file_layout_dsaddr *dsaddr;
480         int status = -EINVAL;
481         struct nfs_server *nfss = NFS_SERVER(lo->plh_inode);
482
483         dprintk("--> %s\n", __func__);
484
485         /* FIXME: remove this check when layout segment support is added */
486         if (lgr->range.offset != 0 ||
487             lgr->range.length != NFS4_MAX_UINT64) {
488                 dprintk("%s Only whole file layouts supported. Use MDS i/o\n",
489                         __func__);
490                 goto out;
491         }
492
493         if (fl->pattern_offset > lgr->range.offset) {
494                 dprintk("%s pattern_offset %lld too large\n",
495                                 __func__, fl->pattern_offset);
496                 goto out;
497         }
498
499         if (!fl->stripe_unit || fl->stripe_unit % PAGE_SIZE) {
500                 dprintk("%s Invalid stripe unit (%u)\n",
501                         __func__, fl->stripe_unit);
502                 goto out;
503         }
504
505         /* find and reference the deviceid */
506         d = nfs4_find_get_deviceid(NFS_SERVER(lo->plh_inode)->pnfs_curr_ld,
507                                    NFS_SERVER(lo->plh_inode)->nfs_client, id);
508         if (d == NULL) {
509                 dsaddr = get_device_info(lo->plh_inode, id, gfp_flags);
510                 if (dsaddr == NULL)
511                         goto out;
512         } else
513                 dsaddr = container_of(d, struct nfs4_file_layout_dsaddr, id_node);
514         /* Found deviceid is being reaped */
515         if (test_bit(NFS_DEVICEID_INVALID, &dsaddr->id_node.flags))
516                         goto out_put;
517
518         fl->dsaddr = dsaddr;
519
520         if (fl->first_stripe_index >= dsaddr->stripe_count) {
521                 dprintk("%s Bad first_stripe_index %u\n",
522                                 __func__, fl->first_stripe_index);
523                 goto out_put;
524         }
525
526         if ((fl->stripe_type == STRIPE_SPARSE &&
527             fl->num_fh > 1 && fl->num_fh != dsaddr->ds_num) ||
528             (fl->stripe_type == STRIPE_DENSE &&
529             fl->num_fh != dsaddr->stripe_count)) {
530                 dprintk("%s num_fh %u not valid for given packing\n",
531                         __func__, fl->num_fh);
532                 goto out_put;
533         }
534
535         if (fl->stripe_unit % nfss->rsize || fl->stripe_unit % nfss->wsize) {
536                 dprintk("%s Stripe unit (%u) not aligned with rsize %u "
537                         "wsize %u\n", __func__, fl->stripe_unit, nfss->rsize,
538                         nfss->wsize);
539         }
540
541         status = 0;
542 out:
543         dprintk("--> %s returns %d\n", __func__, status);
544         return status;
545 out_put:
546         nfs4_fl_put_deviceid(dsaddr);
547         goto out;
548 }
549
550 static void filelayout_free_fh_array(struct nfs4_filelayout_segment *fl)
551 {
552         int i;
553
554         for (i = 0; i < fl->num_fh; i++) {
555                 if (!fl->fh_array[i])
556                         break;
557                 kfree(fl->fh_array[i]);
558         }
559         kfree(fl->fh_array);
560         fl->fh_array = NULL;
561 }
562
563 static void
564 _filelayout_free_lseg(struct nfs4_filelayout_segment *fl)
565 {
566         filelayout_free_fh_array(fl);
567         kfree(fl);
568 }
569
570 static int
571 filelayout_decode_layout(struct pnfs_layout_hdr *flo,
572                          struct nfs4_filelayout_segment *fl,
573                          struct nfs4_layoutget_res *lgr,
574                          struct nfs4_deviceid *id,
575                          gfp_t gfp_flags)
576 {
577         struct xdr_stream stream;
578         struct xdr_buf buf;
579         struct page *scratch;
580         __be32 *p;
581         uint32_t nfl_util;
582         int i;
583
584         dprintk("%s: set_layout_map Begin\n", __func__);
585
586         scratch = alloc_page(gfp_flags);
587         if (!scratch)
588                 return -ENOMEM;
589
590         xdr_init_decode_pages(&stream, &buf, lgr->layoutp->pages, lgr->layoutp->len);
591         xdr_set_scratch_buffer(&stream, page_address(scratch), PAGE_SIZE);
592
593         /* 20 = ufl_util (4), first_stripe_index (4), pattern_offset (8),
594          * num_fh (4) */
595         p = xdr_inline_decode(&stream, NFS4_DEVICEID4_SIZE + 20);
596         if (unlikely(!p))
597                 goto out_err;
598
599         memcpy(id, p, sizeof(*id));
600         p += XDR_QUADLEN(NFS4_DEVICEID4_SIZE);
601         nfs4_print_deviceid(id);
602
603         nfl_util = be32_to_cpup(p++);
604         if (nfl_util & NFL4_UFLG_COMMIT_THRU_MDS)
605                 fl->commit_through_mds = 1;
606         if (nfl_util & NFL4_UFLG_DENSE)
607                 fl->stripe_type = STRIPE_DENSE;
608         else
609                 fl->stripe_type = STRIPE_SPARSE;
610         fl->stripe_unit = nfl_util & ~NFL4_UFLG_MASK;
611
612         fl->first_stripe_index = be32_to_cpup(p++);
613         p = xdr_decode_hyper(p, &fl->pattern_offset);
614         fl->num_fh = be32_to_cpup(p++);
615
616         dprintk("%s: nfl_util 0x%X num_fh %u fsi %u po %llu\n",
617                 __func__, nfl_util, fl->num_fh, fl->first_stripe_index,
618                 fl->pattern_offset);
619
620         /* Note that a zero value for num_fh is legal for STRIPE_SPARSE.
621          * Futher checking is done in filelayout_check_layout */
622         if (fl->num_fh >
623             max(NFS4_PNFS_MAX_STRIPE_CNT, NFS4_PNFS_MAX_MULTI_CNT))
624                 goto out_err;
625
626         if (fl->num_fh > 0) {
627                 fl->fh_array = kzalloc(fl->num_fh * sizeof(struct nfs_fh *),
628                                        gfp_flags);
629                 if (!fl->fh_array)
630                         goto out_err;
631         }
632
633         for (i = 0; i < fl->num_fh; i++) {
634                 /* Do we want to use a mempool here? */
635                 fl->fh_array[i] = kmalloc(sizeof(struct nfs_fh), gfp_flags);
636                 if (!fl->fh_array[i])
637                         goto out_err_free;
638
639                 p = xdr_inline_decode(&stream, 4);
640                 if (unlikely(!p))
641                         goto out_err_free;
642                 fl->fh_array[i]->size = be32_to_cpup(p++);
643                 if (sizeof(struct nfs_fh) < fl->fh_array[i]->size) {
644                         printk(KERN_ERR "NFS: Too big fh %d received %d\n",
645                                i, fl->fh_array[i]->size);
646                         goto out_err_free;
647                 }
648
649                 p = xdr_inline_decode(&stream, fl->fh_array[i]->size);
650                 if (unlikely(!p))
651                         goto out_err_free;
652                 memcpy(fl->fh_array[i]->data, p, fl->fh_array[i]->size);
653                 dprintk("DEBUG: %s: fh len %d\n", __func__,
654                         fl->fh_array[i]->size);
655         }
656
657         __free_page(scratch);
658         return 0;
659
660 out_err_free:
661         filelayout_free_fh_array(fl);
662 out_err:
663         __free_page(scratch);
664         return -EIO;
665 }
666
667 static void
668 filelayout_free_lseg(struct pnfs_layout_segment *lseg)
669 {
670         struct nfs4_filelayout_segment *fl = FILELAYOUT_LSEG(lseg);
671
672         dprintk("--> %s\n", __func__);
673         nfs4_fl_put_deviceid(fl->dsaddr);
674         /* This assumes a single RW lseg */
675         if (lseg->pls_range.iomode == IOMODE_RW) {
676                 struct nfs4_filelayout *flo;
677
678                 flo = FILELAYOUT_FROM_HDR(lseg->pls_layout);
679                 flo->commit_info.nbuckets = 0;
680                 kfree(flo->commit_info.buckets);
681                 flo->commit_info.buckets = NULL;
682         }
683         _filelayout_free_lseg(fl);
684 }
685
686 static int
687 filelayout_alloc_commit_info(struct pnfs_layout_segment *lseg,
688                              struct nfs_commit_info *cinfo,
689                              gfp_t gfp_flags)
690 {
691         struct nfs4_filelayout_segment *fl = FILELAYOUT_LSEG(lseg);
692         struct pnfs_commit_bucket *buckets;
693         int size;
694
695         if (fl->commit_through_mds)
696                 return 0;
697         if (cinfo->ds->nbuckets != 0) {
698                 /* This assumes there is only one IOMODE_RW lseg.  What
699                  * we really want to do is have a layout_hdr level
700                  * dictionary of <multipath_list4, fh> keys, each
701                  * associated with a struct list_head, populated by calls
702                  * to filelayout_write_pagelist().
703                  * */
704                 return 0;
705         }
706
707         size = (fl->stripe_type == STRIPE_SPARSE) ?
708                 fl->dsaddr->ds_num : fl->dsaddr->stripe_count;
709
710         buckets = kcalloc(size, sizeof(struct pnfs_commit_bucket),
711                           gfp_flags);
712         if (!buckets)
713                 return -ENOMEM;
714         else {
715                 int i;
716
717                 spin_lock(cinfo->lock);
718                 if (cinfo->ds->nbuckets != 0)
719                         kfree(buckets);
720                 else {
721                         cinfo->ds->buckets = buckets;
722                         cinfo->ds->nbuckets = size;
723                         for (i = 0; i < size; i++) {
724                                 INIT_LIST_HEAD(&buckets[i].written);
725                                 INIT_LIST_HEAD(&buckets[i].committing);
726                         }
727                 }
728                 spin_unlock(cinfo->lock);
729                 return 0;
730         }
731 }
732
733 static struct pnfs_layout_segment *
734 filelayout_alloc_lseg(struct pnfs_layout_hdr *layoutid,
735                       struct nfs4_layoutget_res *lgr,
736                       gfp_t gfp_flags)
737 {
738         struct nfs4_filelayout_segment *fl;
739         int rc;
740         struct nfs4_deviceid id;
741
742         dprintk("--> %s\n", __func__);
743         fl = kzalloc(sizeof(*fl), gfp_flags);
744         if (!fl)
745                 return NULL;
746
747         rc = filelayout_decode_layout(layoutid, fl, lgr, &id, gfp_flags);
748         if (rc != 0 || filelayout_check_layout(layoutid, fl, lgr, &id, gfp_flags)) {
749                 _filelayout_free_lseg(fl);
750                 return NULL;
751         }
752         return &fl->generic_hdr;
753 }
754
755 /*
756  * filelayout_pg_test(). Called by nfs_can_coalesce_requests()
757  *
758  * return true  : coalesce page
759  * return false : don't coalesce page
760  */
761 static bool
762 filelayout_pg_test(struct nfs_pageio_descriptor *pgio, struct nfs_page *prev,
763                    struct nfs_page *req)
764 {
765         u64 p_stripe, r_stripe;
766         u32 stripe_unit;
767
768         if (!pnfs_generic_pg_test(pgio, prev, req) ||
769             !nfs_generic_pg_test(pgio, prev, req))
770                 return false;
771
772         p_stripe = (u64)req_offset(prev);
773         r_stripe = (u64)req_offset(req);
774         stripe_unit = FILELAYOUT_LSEG(pgio->pg_lseg)->stripe_unit;
775
776         do_div(p_stripe, stripe_unit);
777         do_div(r_stripe, stripe_unit);
778
779         return (p_stripe == r_stripe);
780 }
781
782 static void
783 filelayout_pg_init_read(struct nfs_pageio_descriptor *pgio,
784                         struct nfs_page *req)
785 {
786         BUG_ON(pgio->pg_lseg != NULL);
787
788         if (req->wb_offset != req->wb_pgbase) {
789                 /*
790                  * Handling unaligned pages is difficult, because have to
791                  * somehow split a req in two in certain cases in the
792                  * pg.test code.  Avoid this by just not using pnfs
793                  * in this case.
794                  */
795                 nfs_pageio_reset_read_mds(pgio);
796                 return;
797         }
798         pgio->pg_lseg = pnfs_update_layout(pgio->pg_inode,
799                                            req->wb_context,
800                                            0,
801                                            NFS4_MAX_UINT64,
802                                            IOMODE_READ,
803                                            GFP_KERNEL);
804         /* If no lseg, fall back to read through mds */
805         if (pgio->pg_lseg == NULL)
806                 nfs_pageio_reset_read_mds(pgio);
807 }
808
809 static void
810 filelayout_pg_init_write(struct nfs_pageio_descriptor *pgio,
811                          struct nfs_page *req)
812 {
813         struct nfs_commit_info cinfo;
814         int status;
815
816         BUG_ON(pgio->pg_lseg != NULL);
817
818         if (req->wb_offset != req->wb_pgbase)
819                 goto out_mds;
820         pgio->pg_lseg = pnfs_update_layout(pgio->pg_inode,
821                                            req->wb_context,
822                                            0,
823                                            NFS4_MAX_UINT64,
824                                            IOMODE_RW,
825                                            GFP_NOFS);
826         /* If no lseg, fall back to write through mds */
827         if (pgio->pg_lseg == NULL)
828                 goto out_mds;
829         nfs_init_cinfo(&cinfo, pgio->pg_inode, pgio->pg_dreq);
830         status = filelayout_alloc_commit_info(pgio->pg_lseg, &cinfo, GFP_NOFS);
831         if (status < 0) {
832                 put_lseg(pgio->pg_lseg);
833                 pgio->pg_lseg = NULL;
834                 goto out_mds;
835         }
836         return;
837 out_mds:
838         nfs_pageio_reset_write_mds(pgio);
839 }
840
841 static const struct nfs_pageio_ops filelayout_pg_read_ops = {
842         .pg_init = filelayout_pg_init_read,
843         .pg_test = filelayout_pg_test,
844         .pg_doio = pnfs_generic_pg_readpages,
845 };
846
847 static const struct nfs_pageio_ops filelayout_pg_write_ops = {
848         .pg_init = filelayout_pg_init_write,
849         .pg_test = filelayout_pg_test,
850         .pg_doio = pnfs_generic_pg_writepages,
851 };
852
853 static u32 select_bucket_index(struct nfs4_filelayout_segment *fl, u32 j)
854 {
855         if (fl->stripe_type == STRIPE_SPARSE)
856                 return nfs4_fl_calc_ds_index(&fl->generic_hdr, j);
857         else
858                 return j;
859 }
860
861 /* The generic layer is about to remove the req from the commit list.
862  * If this will make the bucket empty, it will need to put the lseg reference.
863  */
864 static void
865 filelayout_clear_request_commit(struct nfs_page *req,
866                                 struct nfs_commit_info *cinfo)
867 {
868         struct pnfs_layout_segment *freeme = NULL;
869
870         spin_lock(cinfo->lock);
871         if (!test_and_clear_bit(PG_COMMIT_TO_DS, &req->wb_flags))
872                 goto out;
873         cinfo->ds->nwritten--;
874         if (list_is_singular(&req->wb_list)) {
875                 struct pnfs_commit_bucket *bucket;
876
877                 bucket = list_first_entry(&req->wb_list,
878                                           struct pnfs_commit_bucket,
879                                           written);
880                 freeme = bucket->wlseg;
881                 bucket->wlseg = NULL;
882         }
883 out:
884         nfs_request_remove_commit_list(req, cinfo);
885         spin_unlock(cinfo->lock);
886         put_lseg(freeme);
887 }
888
889 static struct list_head *
890 filelayout_choose_commit_list(struct nfs_page *req,
891                               struct pnfs_layout_segment *lseg,
892                               struct nfs_commit_info *cinfo)
893 {
894         struct nfs4_filelayout_segment *fl = FILELAYOUT_LSEG(lseg);
895         u32 i, j;
896         struct list_head *list;
897         struct pnfs_commit_bucket *buckets;
898
899         if (fl->commit_through_mds)
900                 return &cinfo->mds->list;
901
902         /* Note that we are calling nfs4_fl_calc_j_index on each page
903          * that ends up being committed to a data server.  An attractive
904          * alternative is to add a field to nfs_write_data and nfs_page
905          * to store the value calculated in filelayout_write_pagelist
906          * and just use that here.
907          */
908         j = nfs4_fl_calc_j_index(lseg, req_offset(req));
909         i = select_bucket_index(fl, j);
910         buckets = cinfo->ds->buckets;
911         list = &buckets[i].written;
912         if (list_empty(list)) {
913                 /* Non-empty buckets hold a reference on the lseg.  That ref
914                  * is normally transferred to the COMMIT call and released
915                  * there.  It could also be released if the last req is pulled
916                  * off due to a rewrite, in which case it will be done in
917                  * filelayout_clear_request_commit
918                  */
919                 buckets[i].wlseg = get_lseg(lseg);
920         }
921         set_bit(PG_COMMIT_TO_DS, &req->wb_flags);
922         cinfo->ds->nwritten++;
923         return list;
924 }
925
926 static void
927 filelayout_mark_request_commit(struct nfs_page *req,
928                                struct pnfs_layout_segment *lseg,
929                                struct nfs_commit_info *cinfo)
930 {
931         struct list_head *list;
932
933         list = filelayout_choose_commit_list(req, lseg, cinfo);
934         nfs_request_add_commit_list(req, list, cinfo);
935 }
936
937 static u32 calc_ds_index_from_commit(struct pnfs_layout_segment *lseg, u32 i)
938 {
939         struct nfs4_filelayout_segment *flseg = FILELAYOUT_LSEG(lseg);
940
941         if (flseg->stripe_type == STRIPE_SPARSE)
942                 return i;
943         else
944                 return nfs4_fl_calc_ds_index(lseg, i);
945 }
946
947 static struct nfs_fh *
948 select_ds_fh_from_commit(struct pnfs_layout_segment *lseg, u32 i)
949 {
950         struct nfs4_filelayout_segment *flseg = FILELAYOUT_LSEG(lseg);
951
952         if (flseg->stripe_type == STRIPE_SPARSE) {
953                 if (flseg->num_fh == 1)
954                         i = 0;
955                 else if (flseg->num_fh == 0)
956                         /* Use the MDS OPEN fh set in nfs_read_rpcsetup */
957                         return NULL;
958         }
959         return flseg->fh_array[i];
960 }
961
962 static int filelayout_initiate_commit(struct nfs_commit_data *data, int how)
963 {
964         struct pnfs_layout_segment *lseg = data->lseg;
965         struct nfs4_pnfs_ds *ds;
966         u32 idx;
967         struct nfs_fh *fh;
968
969         idx = calc_ds_index_from_commit(lseg, data->ds_commit_index);
970         ds = nfs4_fl_prepare_ds(lseg, idx);
971         if (!ds) {
972                 set_bit(lo_fail_bit(IOMODE_RW), &lseg->pls_layout->plh_flags);
973                 set_bit(lo_fail_bit(IOMODE_READ), &lseg->pls_layout->plh_flags);
974                 prepare_to_resend_writes(data);
975                 filelayout_commit_release(data);
976                 return -EAGAIN;
977         }
978         dprintk("%s ino %lu, how %d\n", __func__, data->inode->i_ino, how);
979         data->commit_done_cb = filelayout_commit_done_cb;
980         data->ds_clp = ds->ds_clp;
981         fh = select_ds_fh_from_commit(lseg, data->ds_commit_index);
982         if (fh)
983                 data->args.fh = fh;
984         return nfs_initiate_commit(ds->ds_clp->cl_rpcclient, data,
985                                    &filelayout_commit_call_ops, how);
986 }
987
988 static int
989 transfer_commit_list(struct list_head *src, struct list_head *dst,
990                      struct nfs_commit_info *cinfo, int max)
991 {
992         struct nfs_page *req, *tmp;
993         int ret = 0;
994
995         list_for_each_entry_safe(req, tmp, src, wb_list) {
996                 if (!nfs_lock_request(req))
997                         continue;
998                 if (cond_resched_lock(cinfo->lock))
999                         list_safe_reset_next(req, tmp, wb_list);
1000                 nfs_request_remove_commit_list(req, cinfo);
1001                 clear_bit(PG_COMMIT_TO_DS, &req->wb_flags);
1002                 nfs_list_add_request(req, dst);
1003                 ret++;
1004                 if ((ret == max) && !cinfo->dreq)
1005                         break;
1006         }
1007         return ret;
1008 }
1009
1010 static int
1011 filelayout_scan_ds_commit_list(struct pnfs_commit_bucket *bucket,
1012                                struct nfs_commit_info *cinfo,
1013                                int max)
1014 {
1015         struct list_head *src = &bucket->written;
1016         struct list_head *dst = &bucket->committing;
1017         int ret;
1018
1019         ret = transfer_commit_list(src, dst, cinfo, max);
1020         if (ret) {
1021                 cinfo->ds->nwritten -= ret;
1022                 cinfo->ds->ncommitting += ret;
1023                 bucket->clseg = bucket->wlseg;
1024                 if (list_empty(src))
1025                         bucket->wlseg = NULL;
1026                 else
1027                         get_lseg(bucket->clseg);
1028         }
1029         return ret;
1030 }
1031
1032 /* Move reqs from written to committing lists, returning count of number moved.
1033  * Note called with cinfo->lock held.
1034  */
1035 static int filelayout_scan_commit_lists(struct nfs_commit_info *cinfo,
1036                                         int max)
1037 {
1038         int i, rv = 0, cnt;
1039
1040         for (i = 0; i < cinfo->ds->nbuckets && max != 0; i++) {
1041                 cnt = filelayout_scan_ds_commit_list(&cinfo->ds->buckets[i],
1042                                                      cinfo, max);
1043                 max -= cnt;
1044                 rv += cnt;
1045         }
1046         return rv;
1047 }
1048
1049 /* Pull everything off the committing lists and dump into @dst */
1050 static void filelayout_recover_commit_reqs(struct list_head *dst,
1051                                            struct nfs_commit_info *cinfo)
1052 {
1053         struct pnfs_commit_bucket *b;
1054         int i;
1055
1056         /* NOTE cinfo->lock is NOT held, relying on fact that this is
1057          * only called on single thread per dreq.
1058          * Can't take the lock because need to do put_lseg
1059          */
1060         for (i = 0, b = cinfo->ds->buckets; i < cinfo->ds->nbuckets; i++, b++) {
1061                 if (transfer_commit_list(&b->written, dst, cinfo, 0)) {
1062                         BUG_ON(!list_empty(&b->written));
1063                         put_lseg(b->wlseg);
1064                         b->wlseg = NULL;
1065                 }
1066         }
1067         cinfo->ds->nwritten = 0;
1068 }
1069
1070 static unsigned int
1071 alloc_ds_commits(struct nfs_commit_info *cinfo, struct list_head *list)
1072 {
1073         struct pnfs_ds_commit_info *fl_cinfo;
1074         struct pnfs_commit_bucket *bucket;
1075         struct nfs_commit_data *data;
1076         int i, j;
1077         unsigned int nreq = 0;
1078
1079         fl_cinfo = cinfo->ds;
1080         bucket = fl_cinfo->buckets;
1081         for (i = 0; i < fl_cinfo->nbuckets; i++, bucket++) {
1082                 if (list_empty(&bucket->committing))
1083                         continue;
1084                 data = nfs_commitdata_alloc();
1085                 if (!data)
1086                         break;
1087                 data->ds_commit_index = i;
1088                 data->lseg = bucket->clseg;
1089                 bucket->clseg = NULL;
1090                 list_add(&data->pages, list);
1091                 nreq++;
1092         }
1093
1094         /* Clean up on error */
1095         for (j = i; j < fl_cinfo->nbuckets; j++, bucket++) {
1096                 if (list_empty(&bucket->committing))
1097                         continue;
1098                 nfs_retry_commit(&bucket->committing, bucket->clseg, cinfo);
1099                 put_lseg(bucket->clseg);
1100                 bucket->clseg = NULL;
1101         }
1102         /* Caller will clean up entries put on list */
1103         return nreq;
1104 }
1105
1106 /* This follows nfs_commit_list pretty closely */
1107 static int
1108 filelayout_commit_pagelist(struct inode *inode, struct list_head *mds_pages,
1109                            int how, struct nfs_commit_info *cinfo)
1110 {
1111         struct nfs_commit_data *data, *tmp;
1112         LIST_HEAD(list);
1113         unsigned int nreq = 0;
1114
1115         if (!list_empty(mds_pages)) {
1116                 data = nfs_commitdata_alloc();
1117                 if (data != NULL) {
1118                         data->lseg = NULL;
1119                         list_add(&data->pages, &list);
1120                         nreq++;
1121                 } else
1122                         nfs_retry_commit(mds_pages, NULL, cinfo);
1123         }
1124
1125         nreq += alloc_ds_commits(cinfo, &list);
1126
1127         if (nreq == 0) {
1128                 cinfo->completion_ops->error_cleanup(NFS_I(inode));
1129                 goto out;
1130         }
1131
1132         atomic_add(nreq, &cinfo->mds->rpcs_out);
1133
1134         list_for_each_entry_safe(data, tmp, &list, pages) {
1135                 list_del_init(&data->pages);
1136                 if (!data->lseg) {
1137                         nfs_init_commit(data, mds_pages, NULL, cinfo);
1138                         nfs_initiate_commit(NFS_CLIENT(inode), data,
1139                                             data->mds_ops, how);
1140                 } else {
1141                         struct pnfs_commit_bucket *buckets;
1142
1143                         buckets = cinfo->ds->buckets;
1144                         nfs_init_commit(data, &buckets[data->ds_commit_index].committing, data->lseg, cinfo);
1145                         filelayout_initiate_commit(data, how);
1146                 }
1147         }
1148 out:
1149         cinfo->ds->ncommitting = 0;
1150         return PNFS_ATTEMPTED;
1151 }
1152
1153 static void
1154 filelayout_free_deveiceid_node(struct nfs4_deviceid_node *d)
1155 {
1156         nfs4_fl_free_deviceid(container_of(d, struct nfs4_file_layout_dsaddr, id_node));
1157 }
1158
1159 static struct pnfs_layout_hdr *
1160 filelayout_alloc_layout_hdr(struct inode *inode, gfp_t gfp_flags)
1161 {
1162         struct nfs4_filelayout *flo;
1163
1164         flo = kzalloc(sizeof(*flo), gfp_flags);
1165         return &flo->generic_hdr;
1166 }
1167
1168 static void
1169 filelayout_free_layout_hdr(struct pnfs_layout_hdr *lo)
1170 {
1171         kfree(FILELAYOUT_FROM_HDR(lo));
1172 }
1173
1174 static struct pnfs_ds_commit_info *
1175 filelayout_get_ds_info(struct inode *inode)
1176 {
1177         struct pnfs_layout_hdr *layout = NFS_I(inode)->layout;
1178
1179         if (layout == NULL)
1180                 return NULL;
1181         else
1182                 return &FILELAYOUT_FROM_HDR(layout)->commit_info;
1183 }
1184
1185 static struct pnfs_layoutdriver_type filelayout_type = {
1186         .id                     = LAYOUT_NFSV4_1_FILES,
1187         .name                   = "LAYOUT_NFSV4_1_FILES",
1188         .owner                  = THIS_MODULE,
1189         .alloc_layout_hdr       = filelayout_alloc_layout_hdr,
1190         .free_layout_hdr        = filelayout_free_layout_hdr,
1191         .alloc_lseg             = filelayout_alloc_lseg,
1192         .free_lseg              = filelayout_free_lseg,
1193         .pg_read_ops            = &filelayout_pg_read_ops,
1194         .pg_write_ops           = &filelayout_pg_write_ops,
1195         .get_ds_info            = &filelayout_get_ds_info,
1196         .mark_request_commit    = filelayout_mark_request_commit,
1197         .clear_request_commit   = filelayout_clear_request_commit,
1198         .scan_commit_lists      = filelayout_scan_commit_lists,
1199         .recover_commit_reqs    = filelayout_recover_commit_reqs,
1200         .commit_pagelist        = filelayout_commit_pagelist,
1201         .read_pagelist          = filelayout_read_pagelist,
1202         .write_pagelist         = filelayout_write_pagelist,
1203         .free_deviceid_node     = filelayout_free_deveiceid_node,
1204 };
1205
1206 static int __init nfs4filelayout_init(void)
1207 {
1208         printk(KERN_INFO "%s: NFSv4 File Layout Driver Registering...\n",
1209                __func__);
1210         return pnfs_register_layoutdriver(&filelayout_type);
1211 }
1212
1213 static void __exit nfs4filelayout_exit(void)
1214 {
1215         printk(KERN_INFO "%s: NFSv4 File Layout Driver Unregistering...\n",
1216                __func__);
1217         pnfs_unregister_layoutdriver(&filelayout_type);
1218 }
1219
1220 MODULE_ALIAS("nfs-layouttype4-1");
1221
1222 module_init(nfs4filelayout_init);
1223 module_exit(nfs4filelayout_exit);