nfsd: recovery - make rec_file per net
[platform/adaptation/renesas_rcar/renesas_kernel.git] / fs / nfsd / nfs4recover.c
1 /*
2 *  Copyright (c) 2004 The Regents of the University of Michigan.
3 *  Copyright (c) 2012 Jeff Layton <jlayton@redhat.com>
4 *  All rights reserved.
5 *
6 *  Andy Adamson <andros@citi.umich.edu>
7 *
8 *  Redistribution and use in source and binary forms, with or without
9 *  modification, are permitted provided that the following conditions
10 *  are met:
11 *
12 *  1. Redistributions of source code must retain the above copyright
13 *     notice, this list of conditions and the following disclaimer.
14 *  2. Redistributions in binary form must reproduce the above copyright
15 *     notice, this list of conditions and the following disclaimer in the
16 *     documentation and/or other materials provided with the distribution.
17 *  3. Neither the name of the University nor the names of its
18 *     contributors may be used to endorse or promote products derived
19 *     from this software without specific prior written permission.
20 *
21 *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
22 *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
23 *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 *  DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
28 *  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 *
33 */
34
35 #include <linux/file.h>
36 #include <linux/slab.h>
37 #include <linux/namei.h>
38 #include <linux/crypto.h>
39 #include <linux/sched.h>
40 #include <linux/fs.h>
41 #include <linux/module.h>
42 #include <net/net_namespace.h>
43 #include <linux/sunrpc/rpc_pipe_fs.h>
44 #include <linux/sunrpc/clnt.h>
45 #include <linux/nfsd/cld.h>
46
47 #include "nfsd.h"
48 #include "state.h"
49 #include "vfs.h"
50 #include "netns.h"
51
52 #define NFSDDBG_FACILITY                NFSDDBG_PROC
53
54 /* Declarations */
55 struct nfsd4_client_tracking_ops {
56         int (*init)(struct net *);
57         void (*exit)(struct net *);
58         void (*create)(struct nfs4_client *);
59         void (*remove)(struct nfs4_client *);
60         int (*check)(struct nfs4_client *);
61         void (*grace_done)(struct nfsd_net *, time_t);
62 };
63
64 /* Globals */
65 static char user_recovery_dirname[PATH_MAX] = "/var/lib/nfs/v4recovery";
66 static struct nfsd4_client_tracking_ops *client_tracking_ops;
67 static bool in_grace;
68
69 static int
70 nfs4_save_creds(const struct cred **original_creds)
71 {
72         struct cred *new;
73
74         new = prepare_creds();
75         if (!new)
76                 return -ENOMEM;
77
78         new->fsuid = 0;
79         new->fsgid = 0;
80         *original_creds = override_creds(new);
81         put_cred(new);
82         return 0;
83 }
84
85 static void
86 nfs4_reset_creds(const struct cred *original)
87 {
88         revert_creds(original);
89 }
90
91 static void
92 md5_to_hex(char *out, char *md5)
93 {
94         int i;
95
96         for (i=0; i<16; i++) {
97                 unsigned char c = md5[i];
98
99                 *out++ = '0' + ((c&0xf0)>>4) + (c>=0xa0)*('a'-'9'-1);
100                 *out++ = '0' + (c&0x0f) + ((c&0x0f)>=0x0a)*('a'-'9'-1);
101         }
102         *out = '\0';
103 }
104
105 static int
106 nfs4_make_rec_clidname(char *dname, const struct xdr_netobj *clname)
107 {
108         struct xdr_netobj cksum;
109         struct hash_desc desc;
110         struct scatterlist sg;
111         int status;
112
113         dprintk("NFSD: nfs4_make_rec_clidname for %.*s\n",
114                         clname->len, clname->data);
115         desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
116         desc.tfm = crypto_alloc_hash("md5", 0, CRYPTO_ALG_ASYNC);
117         if (IS_ERR(desc.tfm)) {
118                 status = PTR_ERR(desc.tfm);
119                 goto out_no_tfm;
120         }
121
122         cksum.len = crypto_hash_digestsize(desc.tfm);
123         cksum.data = kmalloc(cksum.len, GFP_KERNEL);
124         if (cksum.data == NULL) {
125                 status = -ENOMEM;
126                 goto out;
127         }
128
129         sg_init_one(&sg, clname->data, clname->len);
130
131         status = crypto_hash_digest(&desc, &sg, sg.length, cksum.data);
132         if (status)
133                 goto out;
134
135         md5_to_hex(dname, cksum.data);
136
137         status = 0;
138 out:
139         kfree(cksum.data);
140         crypto_free_hash(desc.tfm);
141 out_no_tfm:
142         return status;
143 }
144
145 /*
146  * If we had an error generating the recdir name for the legacy tracker
147  * then warn the admin. If the error doesn't appear to be transient,
148  * then disable recovery tracking.
149  */
150 static void
151 legacy_recdir_name_error(int error)
152 {
153         printk(KERN_ERR "NFSD: unable to generate recoverydir "
154                         "name (%d).\n", error);
155
156         /*
157          * if the algorithm just doesn't exist, then disable the recovery
158          * tracker altogether. The crypto libs will generally return this if
159          * FIPS is enabled as well.
160          */
161         if (error == -ENOENT) {
162                 printk(KERN_ERR "NFSD: disabling legacy clientid tracking. "
163                         "Reboot recovery will not function correctly!\n");
164
165                 /* the argument is ignored by the legacy exit function */
166                 nfsd4_client_tracking_exit(NULL);
167         }
168 }
169
170 static void
171 nfsd4_create_clid_dir(struct nfs4_client *clp)
172 {
173         const struct cred *original_cred;
174         char dname[HEXDIR_LEN];
175         struct dentry *dir, *dentry;
176         struct nfs4_client_reclaim *crp;
177         int status;
178         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
179
180         dprintk("NFSD: nfsd4_create_clid_dir for \"%s\"\n", dname);
181
182         if (test_and_set_bit(NFSD4_CLIENT_STABLE, &clp->cl_flags))
183                 return;
184         if (!nn->rec_file)
185                 return;
186
187         status = nfs4_make_rec_clidname(dname, &clp->cl_name);
188         if (status)
189                 return legacy_recdir_name_error(status);
190
191         status = nfs4_save_creds(&original_cred);
192         if (status < 0)
193                 return;
194
195         status = mnt_want_write_file(nn->rec_file);
196         if (status)
197                 return;
198
199         dir = nn->rec_file->f_path.dentry;
200         /* lock the parent */
201         mutex_lock(&dir->d_inode->i_mutex);
202
203         dentry = lookup_one_len(dname, dir, HEXDIR_LEN-1);
204         if (IS_ERR(dentry)) {
205                 status = PTR_ERR(dentry);
206                 goto out_unlock;
207         }
208         if (dentry->d_inode)
209                 /*
210                  * In the 4.1 case, where we're called from
211                  * reclaim_complete(), records from the previous reboot
212                  * may still be left, so this is OK.
213                  *
214                  * In the 4.0 case, we should never get here; but we may
215                  * as well be forgiving and just succeed silently.
216                  */
217                 goto out_put;
218         status = vfs_mkdir(dir->d_inode, dentry, S_IRWXU);
219 out_put:
220         dput(dentry);
221 out_unlock:
222         mutex_unlock(&dir->d_inode->i_mutex);
223         if (status == 0) {
224                 if (in_grace) {
225                         crp = nfs4_client_to_reclaim(dname, nn);
226                         if (crp)
227                                 crp->cr_clp = clp;
228                 }
229                 vfs_fsync(nn->rec_file, 0);
230         } else {
231                 printk(KERN_ERR "NFSD: failed to write recovery record"
232                                 " (err %d); please check that %s exists"
233                                 " and is writeable", status,
234                                 user_recovery_dirname);
235         }
236         mnt_drop_write_file(nn->rec_file);
237         nfs4_reset_creds(original_cred);
238 }
239
240 typedef int (recdir_func)(struct dentry *, struct dentry *, struct nfsd_net *);
241
242 struct name_list {
243         char name[HEXDIR_LEN];
244         struct list_head list;
245 };
246
247 static int
248 nfsd4_build_namelist(void *arg, const char *name, int namlen,
249                 loff_t offset, u64 ino, unsigned int d_type)
250 {
251         struct list_head *names = arg;
252         struct name_list *entry;
253
254         if (namlen != HEXDIR_LEN - 1)
255                 return 0;
256         entry = kmalloc(sizeof(struct name_list), GFP_KERNEL);
257         if (entry == NULL)
258                 return -ENOMEM;
259         memcpy(entry->name, name, HEXDIR_LEN - 1);
260         entry->name[HEXDIR_LEN - 1] = '\0';
261         list_add(&entry->list, names);
262         return 0;
263 }
264
265 static int
266 nfsd4_list_rec_dir(recdir_func *f, struct nfsd_net *nn)
267 {
268         const struct cred *original_cred;
269         struct dentry *dir = nn->rec_file->f_path.dentry;
270         LIST_HEAD(names);
271         int status;
272
273         status = nfs4_save_creds(&original_cred);
274         if (status < 0)
275                 return status;
276
277         status = vfs_llseek(nn->rec_file, 0, SEEK_SET);
278         if (status < 0) {
279                 nfs4_reset_creds(original_cred);
280                 return status;
281         }
282
283         status = vfs_readdir(nn->rec_file, nfsd4_build_namelist, &names);
284         mutex_lock_nested(&dir->d_inode->i_mutex, I_MUTEX_PARENT);
285         while (!list_empty(&names)) {
286                 struct name_list *entry;
287                 entry = list_entry(names.next, struct name_list, list);
288                 if (!status) {
289                         struct dentry *dentry;
290                         dentry = lookup_one_len(entry->name, dir, HEXDIR_LEN-1);
291                         if (IS_ERR(dentry)) {
292                                 status = PTR_ERR(dentry);
293                                 break;
294                         }
295                         status = f(dir, dentry, nn);
296                         dput(dentry);
297                 }
298                 list_del(&entry->list);
299                 kfree(entry);
300         }
301         mutex_unlock(&dir->d_inode->i_mutex);
302         nfs4_reset_creds(original_cred);
303         return status;
304 }
305
306 static int
307 nfsd4_unlink_clid_dir(char *name, int namlen, struct nfsd_net *nn)
308 {
309         struct dentry *dir, *dentry;
310         int status;
311
312         dprintk("NFSD: nfsd4_unlink_clid_dir. name %.*s\n", namlen, name);
313
314         dir = nn->rec_file->f_path.dentry;
315         mutex_lock_nested(&dir->d_inode->i_mutex, I_MUTEX_PARENT);
316         dentry = lookup_one_len(name, dir, namlen);
317         if (IS_ERR(dentry)) {
318                 status = PTR_ERR(dentry);
319                 goto out_unlock;
320         }
321         status = -ENOENT;
322         if (!dentry->d_inode)
323                 goto out;
324         status = vfs_rmdir(dir->d_inode, dentry);
325 out:
326         dput(dentry);
327 out_unlock:
328         mutex_unlock(&dir->d_inode->i_mutex);
329         return status;
330 }
331
332 static void
333 nfsd4_remove_clid_dir(struct nfs4_client *clp)
334 {
335         const struct cred *original_cred;
336         struct nfs4_client_reclaim *crp;
337         char dname[HEXDIR_LEN];
338         int status;
339         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
340
341         if (!nn->rec_file || !test_bit(NFSD4_CLIENT_STABLE, &clp->cl_flags))
342                 return;
343
344         status = nfs4_make_rec_clidname(dname, &clp->cl_name);
345         if (status)
346                 return legacy_recdir_name_error(status);
347
348         status = mnt_want_write_file(nn->rec_file);
349         if (status)
350                 goto out;
351         clear_bit(NFSD4_CLIENT_STABLE, &clp->cl_flags);
352
353         status = nfs4_save_creds(&original_cred);
354         if (status < 0)
355                 goto out_drop_write;
356
357         status = nfsd4_unlink_clid_dir(dname, HEXDIR_LEN-1, nn);
358         nfs4_reset_creds(original_cred);
359         if (status == 0) {
360                 vfs_fsync(nn->rec_file, 0);
361                 if (in_grace) {
362                         /* remove reclaim record */
363                         crp = nfsd4_find_reclaim_client(dname, nn);
364                         if (crp)
365                                 nfs4_remove_reclaim_record(crp, nn);
366                 }
367         }
368 out_drop_write:
369         mnt_drop_write_file(nn->rec_file);
370 out:
371         if (status)
372                 printk("NFSD: Failed to remove expired client state directory"
373                                 " %.*s\n", HEXDIR_LEN, dname);
374 }
375
376 static int
377 purge_old(struct dentry *parent, struct dentry *child, struct nfsd_net *nn)
378 {
379         int status;
380
381         if (nfs4_has_reclaimed_state(child->d_name.name, nn))
382                 return 0;
383
384         status = vfs_rmdir(parent->d_inode, child);
385         if (status)
386                 printk("failed to remove client recovery directory %s\n",
387                                 child->d_name.name);
388         /* Keep trying, success or failure: */
389         return 0;
390 }
391
392 static void
393 nfsd4_recdir_purge_old(struct nfsd_net *nn, time_t boot_time)
394 {
395         int status;
396
397         in_grace = false;
398         if (!nn->rec_file)
399                 return;
400         status = mnt_want_write_file(nn->rec_file);
401         if (status)
402                 goto out;
403         status = nfsd4_list_rec_dir(purge_old, nn);
404         if (status == 0)
405                 vfs_fsync(nn->rec_file, 0);
406         mnt_drop_write_file(nn->rec_file);
407 out:
408         nfs4_release_reclaim(nn);
409         if (status)
410                 printk("nfsd4: failed to purge old clients from recovery"
411                         " directory %s\n", nn->rec_file->f_path.dentry->d_name.name);
412 }
413
414 static int
415 load_recdir(struct dentry *parent, struct dentry *child, struct nfsd_net *nn)
416 {
417         if (child->d_name.len != HEXDIR_LEN - 1) {
418                 printk("nfsd4: illegal name %s in recovery directory\n",
419                                 child->d_name.name);
420                 /* Keep trying; maybe the others are OK: */
421                 return 0;
422         }
423         nfs4_client_to_reclaim(child->d_name.name, nn);
424         return 0;
425 }
426
427 static int
428 nfsd4_recdir_load(struct net *net) {
429         int status;
430         struct nfsd_net *nn =  net_generic(net, nfsd_net_id);
431
432         if (!nn->rec_file)
433                 return 0;
434
435         status = nfsd4_list_rec_dir(load_recdir, nn);
436         if (status)
437                 printk("nfsd4: failed loading clients from recovery"
438                         " directory %s\n", nn->rec_file->f_path.dentry->d_name.name);
439         return status;
440 }
441
442 /*
443  * Hold reference to the recovery directory.
444  */
445
446 static int
447 nfsd4_init_recdir(struct net *net)
448 {
449         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
450         const struct cred *original_cred;
451         int status;
452
453         printk("NFSD: Using %s as the NFSv4 state recovery directory\n",
454                         user_recovery_dirname);
455
456         BUG_ON(nn->rec_file);
457
458         status = nfs4_save_creds(&original_cred);
459         if (status < 0) {
460                 printk("NFSD: Unable to change credentials to find recovery"
461                        " directory: error %d\n",
462                        status);
463                 return status;
464         }
465
466         nn->rec_file = filp_open(user_recovery_dirname, O_RDONLY | O_DIRECTORY, 0);
467         if (IS_ERR(nn->rec_file)) {
468                 printk("NFSD: unable to find recovery directory %s\n",
469                                 user_recovery_dirname);
470                 status = PTR_ERR(nn->rec_file);
471                 nn->rec_file = NULL;
472         }
473
474         nfs4_reset_creds(original_cred);
475         if (!status)
476                 in_grace = true;
477         return status;
478 }
479
480
481 static int
482 nfs4_legacy_state_init(struct net *net)
483 {
484         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
485         int i;
486
487         nn->reclaim_str_hashtbl = kmalloc(sizeof(struct list_head) *
488                                           CLIENT_HASH_SIZE, GFP_KERNEL);
489         if (!nn->reclaim_str_hashtbl)
490                 return -ENOMEM;
491
492         for (i = 0; i < CLIENT_HASH_SIZE; i++)
493                 INIT_LIST_HEAD(&nn->reclaim_str_hashtbl[i]);
494         nn->reclaim_str_hashtbl_size = 0;
495
496         return 0;
497 }
498
499 static void
500 nfs4_legacy_state_shutdown(struct net *net)
501 {
502         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
503
504         kfree(nn->reclaim_str_hashtbl);
505 }
506
507 static int
508 nfsd4_load_reboot_recovery_data(struct net *net)
509 {
510         int status;
511
512         status = nfsd4_init_recdir(net);
513         if (!status)
514                 status = nfsd4_recdir_load(net);
515         if (status)
516                 printk(KERN_ERR "NFSD: Failure reading reboot recovery data\n");
517         return status;
518 }
519
520 static int
521 nfsd4_legacy_tracking_init(struct net *net)
522 {
523         int status;
524
525         /* XXX: The legacy code won't work in a container */
526         if (net != &init_net) {
527                 WARN(1, KERN_ERR "NFSD: attempt to initialize legacy client "
528                         "tracking in a container!\n");
529                 return -EINVAL;
530         }
531
532         status = nfs4_legacy_state_init(net);
533         if (status)
534                 return status;
535
536         status = nfsd4_load_reboot_recovery_data(net);
537         if (status)
538                 goto err;
539         return 0;
540
541 err:
542         nfs4_legacy_state_shutdown(net);
543         return status;
544 }
545
546 static void
547 nfsd4_shutdown_recdir(struct nfsd_net *nn)
548 {
549         if (!nn->rec_file)
550                 return;
551         fput(nn->rec_file);
552         nn->rec_file = NULL;
553 }
554
555 static void
556 nfsd4_legacy_tracking_exit(struct net *net)
557 {
558         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
559
560         nfs4_release_reclaim(nn);
561         nfsd4_shutdown_recdir(nn);
562         nfs4_legacy_state_shutdown(net);
563 }
564
565 /*
566  * Change the NFSv4 recovery directory to recdir.
567  */
568 int
569 nfs4_reset_recoverydir(char *recdir)
570 {
571         int status;
572         struct path path;
573
574         status = kern_path(recdir, LOOKUP_FOLLOW, &path);
575         if (status)
576                 return status;
577         status = -ENOTDIR;
578         if (S_ISDIR(path.dentry->d_inode->i_mode)) {
579                 strcpy(user_recovery_dirname, recdir);
580                 status = 0;
581         }
582         path_put(&path);
583         return status;
584 }
585
586 char *
587 nfs4_recoverydir(void)
588 {
589         return user_recovery_dirname;
590 }
591
592 static int
593 nfsd4_check_legacy_client(struct nfs4_client *clp)
594 {
595         int status;
596         char dname[HEXDIR_LEN];
597         struct nfs4_client_reclaim *crp;
598         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
599
600         /* did we already find that this client is stable? */
601         if (test_bit(NFSD4_CLIENT_STABLE, &clp->cl_flags))
602                 return 0;
603
604         status = nfs4_make_rec_clidname(dname, &clp->cl_name);
605         if (status) {
606                 legacy_recdir_name_error(status);
607                 return status;
608         }
609
610         /* look for it in the reclaim hashtable otherwise */
611         crp = nfsd4_find_reclaim_client(dname, nn);
612         if (crp) {
613                 set_bit(NFSD4_CLIENT_STABLE, &clp->cl_flags);
614                 crp->cr_clp = clp;
615                 return 0;
616         }
617
618         return -ENOENT;
619 }
620
621 static struct nfsd4_client_tracking_ops nfsd4_legacy_tracking_ops = {
622         .init           = nfsd4_legacy_tracking_init,
623         .exit           = nfsd4_legacy_tracking_exit,
624         .create         = nfsd4_create_clid_dir,
625         .remove         = nfsd4_remove_clid_dir,
626         .check          = nfsd4_check_legacy_client,
627         .grace_done     = nfsd4_recdir_purge_old,
628 };
629
630 /* Globals */
631 #define NFSD_PIPE_DIR           "nfsd"
632 #define NFSD_CLD_PIPE           "cld"
633
634 /* per-net-ns structure for holding cld upcall info */
635 struct cld_net {
636         struct rpc_pipe         *cn_pipe;
637         spinlock_t               cn_lock;
638         struct list_head         cn_list;
639         unsigned int             cn_xid;
640 };
641
642 struct cld_upcall {
643         struct list_head         cu_list;
644         struct cld_net          *cu_net;
645         struct task_struct      *cu_task;
646         struct cld_msg           cu_msg;
647 };
648
649 static int
650 __cld_pipe_upcall(struct rpc_pipe *pipe, struct cld_msg *cmsg)
651 {
652         int ret;
653         struct rpc_pipe_msg msg;
654
655         memset(&msg, 0, sizeof(msg));
656         msg.data = cmsg;
657         msg.len = sizeof(*cmsg);
658
659         /*
660          * Set task state before we queue the upcall. That prevents
661          * wake_up_process in the downcall from racing with schedule.
662          */
663         set_current_state(TASK_UNINTERRUPTIBLE);
664         ret = rpc_queue_upcall(pipe, &msg);
665         if (ret < 0) {
666                 set_current_state(TASK_RUNNING);
667                 goto out;
668         }
669
670         schedule();
671         set_current_state(TASK_RUNNING);
672
673         if (msg.errno < 0)
674                 ret = msg.errno;
675 out:
676         return ret;
677 }
678
679 static int
680 cld_pipe_upcall(struct rpc_pipe *pipe, struct cld_msg *cmsg)
681 {
682         int ret;
683
684         /*
685          * -EAGAIN occurs when pipe is closed and reopened while there are
686          *  upcalls queued.
687          */
688         do {
689                 ret = __cld_pipe_upcall(pipe, cmsg);
690         } while (ret == -EAGAIN);
691
692         return ret;
693 }
694
695 static ssize_t
696 cld_pipe_downcall(struct file *filp, const char __user *src, size_t mlen)
697 {
698         struct cld_upcall *tmp, *cup;
699         struct cld_msg __user *cmsg = (struct cld_msg __user *)src;
700         uint32_t xid;
701         struct nfsd_net *nn = net_generic(filp->f_dentry->d_sb->s_fs_info,
702                                                 nfsd_net_id);
703         struct cld_net *cn = nn->cld_net;
704
705         if (mlen != sizeof(*cmsg)) {
706                 dprintk("%s: got %zu bytes, expected %zu\n", __func__, mlen,
707                         sizeof(*cmsg));
708                 return -EINVAL;
709         }
710
711         /* copy just the xid so we can try to find that */
712         if (copy_from_user(&xid, &cmsg->cm_xid, sizeof(xid)) != 0) {
713                 dprintk("%s: error when copying xid from userspace", __func__);
714                 return -EFAULT;
715         }
716
717         /* walk the list and find corresponding xid */
718         cup = NULL;
719         spin_lock(&cn->cn_lock);
720         list_for_each_entry(tmp, &cn->cn_list, cu_list) {
721                 if (get_unaligned(&tmp->cu_msg.cm_xid) == xid) {
722                         cup = tmp;
723                         list_del_init(&cup->cu_list);
724                         break;
725                 }
726         }
727         spin_unlock(&cn->cn_lock);
728
729         /* couldn't find upcall? */
730         if (!cup) {
731                 dprintk("%s: couldn't find upcall -- xid=%u\n", __func__, xid);
732                 return -EINVAL;
733         }
734
735         if (copy_from_user(&cup->cu_msg, src, mlen) != 0)
736                 return -EFAULT;
737
738         wake_up_process(cup->cu_task);
739         return mlen;
740 }
741
742 static void
743 cld_pipe_destroy_msg(struct rpc_pipe_msg *msg)
744 {
745         struct cld_msg *cmsg = msg->data;
746         struct cld_upcall *cup = container_of(cmsg, struct cld_upcall,
747                                                  cu_msg);
748
749         /* errno >= 0 means we got a downcall */
750         if (msg->errno >= 0)
751                 return;
752
753         wake_up_process(cup->cu_task);
754 }
755
756 static const struct rpc_pipe_ops cld_upcall_ops = {
757         .upcall         = rpc_pipe_generic_upcall,
758         .downcall       = cld_pipe_downcall,
759         .destroy_msg    = cld_pipe_destroy_msg,
760 };
761
762 static struct dentry *
763 nfsd4_cld_register_sb(struct super_block *sb, struct rpc_pipe *pipe)
764 {
765         struct dentry *dir, *dentry;
766
767         dir = rpc_d_lookup_sb(sb, NFSD_PIPE_DIR);
768         if (dir == NULL)
769                 return ERR_PTR(-ENOENT);
770         dentry = rpc_mkpipe_dentry(dir, NFSD_CLD_PIPE, NULL, pipe);
771         dput(dir);
772         return dentry;
773 }
774
775 static void
776 nfsd4_cld_unregister_sb(struct rpc_pipe *pipe)
777 {
778         if (pipe->dentry)
779                 rpc_unlink(pipe->dentry);
780 }
781
782 static struct dentry *
783 nfsd4_cld_register_net(struct net *net, struct rpc_pipe *pipe)
784 {
785         struct super_block *sb;
786         struct dentry *dentry;
787
788         sb = rpc_get_sb_net(net);
789         if (!sb)
790                 return NULL;
791         dentry = nfsd4_cld_register_sb(sb, pipe);
792         rpc_put_sb_net(net);
793         return dentry;
794 }
795
796 static void
797 nfsd4_cld_unregister_net(struct net *net, struct rpc_pipe *pipe)
798 {
799         struct super_block *sb;
800
801         sb = rpc_get_sb_net(net);
802         if (sb) {
803                 nfsd4_cld_unregister_sb(pipe);
804                 rpc_put_sb_net(net);
805         }
806 }
807
808 /* Initialize rpc_pipefs pipe for communication with client tracking daemon */
809 static int
810 nfsd4_init_cld_pipe(struct net *net)
811 {
812         int ret;
813         struct dentry *dentry;
814         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
815         struct cld_net *cn;
816
817         if (nn->cld_net)
818                 return 0;
819
820         cn = kzalloc(sizeof(*cn), GFP_KERNEL);
821         if (!cn) {
822                 ret = -ENOMEM;
823                 goto err;
824         }
825
826         cn->cn_pipe = rpc_mkpipe_data(&cld_upcall_ops, RPC_PIPE_WAIT_FOR_OPEN);
827         if (IS_ERR(cn->cn_pipe)) {
828                 ret = PTR_ERR(cn->cn_pipe);
829                 goto err;
830         }
831         spin_lock_init(&cn->cn_lock);
832         INIT_LIST_HEAD(&cn->cn_list);
833
834         dentry = nfsd4_cld_register_net(net, cn->cn_pipe);
835         if (IS_ERR(dentry)) {
836                 ret = PTR_ERR(dentry);
837                 goto err_destroy_data;
838         }
839
840         cn->cn_pipe->dentry = dentry;
841         nn->cld_net = cn;
842         return 0;
843
844 err_destroy_data:
845         rpc_destroy_pipe_data(cn->cn_pipe);
846 err:
847         kfree(cn);
848         printk(KERN_ERR "NFSD: unable to create nfsdcld upcall pipe (%d)\n",
849                         ret);
850         return ret;
851 }
852
853 static void
854 nfsd4_remove_cld_pipe(struct net *net)
855 {
856         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
857         struct cld_net *cn = nn->cld_net;
858
859         nfsd4_cld_unregister_net(net, cn->cn_pipe);
860         rpc_destroy_pipe_data(cn->cn_pipe);
861         kfree(nn->cld_net);
862         nn->cld_net = NULL;
863 }
864
865 static struct cld_upcall *
866 alloc_cld_upcall(struct cld_net *cn)
867 {
868         struct cld_upcall *new, *tmp;
869
870         new = kzalloc(sizeof(*new), GFP_KERNEL);
871         if (!new)
872                 return new;
873
874         /* FIXME: hard cap on number in flight? */
875 restart_search:
876         spin_lock(&cn->cn_lock);
877         list_for_each_entry(tmp, &cn->cn_list, cu_list) {
878                 if (tmp->cu_msg.cm_xid == cn->cn_xid) {
879                         cn->cn_xid++;
880                         spin_unlock(&cn->cn_lock);
881                         goto restart_search;
882                 }
883         }
884         new->cu_task = current;
885         new->cu_msg.cm_vers = CLD_UPCALL_VERSION;
886         put_unaligned(cn->cn_xid++, &new->cu_msg.cm_xid);
887         new->cu_net = cn;
888         list_add(&new->cu_list, &cn->cn_list);
889         spin_unlock(&cn->cn_lock);
890
891         dprintk("%s: allocated xid %u\n", __func__, new->cu_msg.cm_xid);
892
893         return new;
894 }
895
896 static void
897 free_cld_upcall(struct cld_upcall *victim)
898 {
899         struct cld_net *cn = victim->cu_net;
900
901         spin_lock(&cn->cn_lock);
902         list_del(&victim->cu_list);
903         spin_unlock(&cn->cn_lock);
904         kfree(victim);
905 }
906
907 /* Ask daemon to create a new record */
908 static void
909 nfsd4_cld_create(struct nfs4_client *clp)
910 {
911         int ret;
912         struct cld_upcall *cup;
913         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
914         struct cld_net *cn = nn->cld_net;
915
916         /* Don't upcall if it's already stored */
917         if (test_bit(NFSD4_CLIENT_STABLE, &clp->cl_flags))
918                 return;
919
920         cup = alloc_cld_upcall(cn);
921         if (!cup) {
922                 ret = -ENOMEM;
923                 goto out_err;
924         }
925
926         cup->cu_msg.cm_cmd = Cld_Create;
927         cup->cu_msg.cm_u.cm_name.cn_len = clp->cl_name.len;
928         memcpy(cup->cu_msg.cm_u.cm_name.cn_id, clp->cl_name.data,
929                         clp->cl_name.len);
930
931         ret = cld_pipe_upcall(cn->cn_pipe, &cup->cu_msg);
932         if (!ret) {
933                 ret = cup->cu_msg.cm_status;
934                 set_bit(NFSD4_CLIENT_STABLE, &clp->cl_flags);
935         }
936
937         free_cld_upcall(cup);
938 out_err:
939         if (ret)
940                 printk(KERN_ERR "NFSD: Unable to create client "
941                                 "record on stable storage: %d\n", ret);
942 }
943
944 /* Ask daemon to create a new record */
945 static void
946 nfsd4_cld_remove(struct nfs4_client *clp)
947 {
948         int ret;
949         struct cld_upcall *cup;
950         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
951         struct cld_net *cn = nn->cld_net;
952
953         /* Don't upcall if it's already removed */
954         if (!test_bit(NFSD4_CLIENT_STABLE, &clp->cl_flags))
955                 return;
956
957         cup = alloc_cld_upcall(cn);
958         if (!cup) {
959                 ret = -ENOMEM;
960                 goto out_err;
961         }
962
963         cup->cu_msg.cm_cmd = Cld_Remove;
964         cup->cu_msg.cm_u.cm_name.cn_len = clp->cl_name.len;
965         memcpy(cup->cu_msg.cm_u.cm_name.cn_id, clp->cl_name.data,
966                         clp->cl_name.len);
967
968         ret = cld_pipe_upcall(cn->cn_pipe, &cup->cu_msg);
969         if (!ret) {
970                 ret = cup->cu_msg.cm_status;
971                 clear_bit(NFSD4_CLIENT_STABLE, &clp->cl_flags);
972         }
973
974         free_cld_upcall(cup);
975 out_err:
976         if (ret)
977                 printk(KERN_ERR "NFSD: Unable to remove client "
978                                 "record from stable storage: %d\n", ret);
979 }
980
981 /* Check for presence of a record, and update its timestamp */
982 static int
983 nfsd4_cld_check(struct nfs4_client *clp)
984 {
985         int ret;
986         struct cld_upcall *cup;
987         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
988         struct cld_net *cn = nn->cld_net;
989
990         /* Don't upcall if one was already stored during this grace pd */
991         if (test_bit(NFSD4_CLIENT_STABLE, &clp->cl_flags))
992                 return 0;
993
994         cup = alloc_cld_upcall(cn);
995         if (!cup) {
996                 printk(KERN_ERR "NFSD: Unable to check client record on "
997                                 "stable storage: %d\n", -ENOMEM);
998                 return -ENOMEM;
999         }
1000
1001         cup->cu_msg.cm_cmd = Cld_Check;
1002         cup->cu_msg.cm_u.cm_name.cn_len = clp->cl_name.len;
1003         memcpy(cup->cu_msg.cm_u.cm_name.cn_id, clp->cl_name.data,
1004                         clp->cl_name.len);
1005
1006         ret = cld_pipe_upcall(cn->cn_pipe, &cup->cu_msg);
1007         if (!ret) {
1008                 ret = cup->cu_msg.cm_status;
1009                 set_bit(NFSD4_CLIENT_STABLE, &clp->cl_flags);
1010         }
1011
1012         free_cld_upcall(cup);
1013         return ret;
1014 }
1015
1016 static void
1017 nfsd4_cld_grace_done(struct nfsd_net *nn, time_t boot_time)
1018 {
1019         int ret;
1020         struct cld_upcall *cup;
1021         struct cld_net *cn = nn->cld_net;
1022
1023         cup = alloc_cld_upcall(cn);
1024         if (!cup) {
1025                 ret = -ENOMEM;
1026                 goto out_err;
1027         }
1028
1029         cup->cu_msg.cm_cmd = Cld_GraceDone;
1030         cup->cu_msg.cm_u.cm_gracetime = (int64_t)boot_time;
1031         ret = cld_pipe_upcall(cn->cn_pipe, &cup->cu_msg);
1032         if (!ret)
1033                 ret = cup->cu_msg.cm_status;
1034
1035         free_cld_upcall(cup);
1036 out_err:
1037         if (ret)
1038                 printk(KERN_ERR "NFSD: Unable to end grace period: %d\n", ret);
1039 }
1040
1041 static struct nfsd4_client_tracking_ops nfsd4_cld_tracking_ops = {
1042         .init           = nfsd4_init_cld_pipe,
1043         .exit           = nfsd4_remove_cld_pipe,
1044         .create         = nfsd4_cld_create,
1045         .remove         = nfsd4_cld_remove,
1046         .check          = nfsd4_cld_check,
1047         .grace_done     = nfsd4_cld_grace_done,
1048 };
1049
1050 /* upcall via usermodehelper */
1051 static char cltrack_prog[PATH_MAX] = "/sbin/nfsdcltrack";
1052 module_param_string(cltrack_prog, cltrack_prog, sizeof(cltrack_prog),
1053                         S_IRUGO|S_IWUSR);
1054 MODULE_PARM_DESC(cltrack_prog, "Path to the nfsdcltrack upcall program");
1055
1056 static bool cltrack_legacy_disable;
1057 module_param(cltrack_legacy_disable, bool, S_IRUGO|S_IWUSR);
1058 MODULE_PARM_DESC(cltrack_legacy_disable,
1059                 "Disable legacy recoverydir conversion. Default: false");
1060
1061 #define LEGACY_TOPDIR_ENV_PREFIX "NFSDCLTRACK_LEGACY_TOPDIR="
1062 #define LEGACY_RECDIR_ENV_PREFIX "NFSDCLTRACK_LEGACY_RECDIR="
1063
1064 static char *
1065 nfsd4_cltrack_legacy_topdir(void)
1066 {
1067         int copied;
1068         size_t len;
1069         char *result;
1070
1071         if (cltrack_legacy_disable)
1072                 return NULL;
1073
1074         len = strlen(LEGACY_TOPDIR_ENV_PREFIX) +
1075                 strlen(nfs4_recoverydir()) + 1;
1076
1077         result = kmalloc(len, GFP_KERNEL);
1078         if (!result)
1079                 return result;
1080
1081         copied = snprintf(result, len, LEGACY_TOPDIR_ENV_PREFIX "%s",
1082                                 nfs4_recoverydir());
1083         if (copied >= len) {
1084                 /* just return nothing if output was truncated */
1085                 kfree(result);
1086                 return NULL;
1087         }
1088
1089         return result;
1090 }
1091
1092 static char *
1093 nfsd4_cltrack_legacy_recdir(const struct xdr_netobj *name)
1094 {
1095         int copied;
1096         size_t len;
1097         char *result;
1098
1099         if (cltrack_legacy_disable)
1100                 return NULL;
1101
1102         /* +1 is for '/' between "topdir" and "recdir" */
1103         len = strlen(LEGACY_RECDIR_ENV_PREFIX) +
1104                 strlen(nfs4_recoverydir()) + 1 + HEXDIR_LEN;
1105
1106         result = kmalloc(len, GFP_KERNEL);
1107         if (!result)
1108                 return result;
1109
1110         copied = snprintf(result, len, LEGACY_RECDIR_ENV_PREFIX "%s/",
1111                                 nfs4_recoverydir());
1112         if (copied > (len - HEXDIR_LEN)) {
1113                 /* just return nothing if output will be truncated */
1114                 kfree(result);
1115                 return NULL;
1116         }
1117
1118         copied = nfs4_make_rec_clidname(result + copied, name);
1119         if (copied) {
1120                 kfree(result);
1121                 return NULL;
1122         }
1123
1124         return result;
1125 }
1126
1127 static int
1128 nfsd4_umh_cltrack_upcall(char *cmd, char *arg, char *legacy)
1129 {
1130         char *envp[2];
1131         char *argv[4];
1132         int ret;
1133
1134         if (unlikely(!cltrack_prog[0])) {
1135                 dprintk("%s: cltrack_prog is disabled\n", __func__);
1136                 return -EACCES;
1137         }
1138
1139         dprintk("%s: cmd: %s\n", __func__, cmd);
1140         dprintk("%s: arg: %s\n", __func__, arg ? arg : "(null)");
1141         dprintk("%s: legacy: %s\n", __func__, legacy ? legacy : "(null)");
1142
1143         envp[0] = legacy;
1144         envp[1] = NULL;
1145
1146         argv[0] = (char *)cltrack_prog;
1147         argv[1] = cmd;
1148         argv[2] = arg;
1149         argv[3] = NULL;
1150
1151         ret = call_usermodehelper(argv[0], argv, envp, UMH_WAIT_PROC);
1152         /*
1153          * Disable the upcall mechanism if we're getting an ENOENT or EACCES
1154          * error. The admin can re-enable it on the fly by using sysfs
1155          * once the problem has been fixed.
1156          */
1157         if (ret == -ENOENT || ret == -EACCES) {
1158                 dprintk("NFSD: %s was not found or isn't executable (%d). "
1159                         "Setting cltrack_prog to blank string!",
1160                         cltrack_prog, ret);
1161                 cltrack_prog[0] = '\0';
1162         }
1163         dprintk("%s: %s return value: %d\n", __func__, cltrack_prog, ret);
1164
1165         return ret;
1166 }
1167
1168 static char *
1169 bin_to_hex_dup(const unsigned char *src, int srclen)
1170 {
1171         int i;
1172         char *buf, *hex;
1173
1174         /* +1 for terminating NULL */
1175         buf = kmalloc((srclen * 2) + 1, GFP_KERNEL);
1176         if (!buf)
1177                 return buf;
1178
1179         hex = buf;
1180         for (i = 0; i < srclen; i++) {
1181                 sprintf(hex, "%2.2x", *src++);
1182                 hex += 2;
1183         }
1184         return buf;
1185 }
1186
1187 static int
1188 nfsd4_umh_cltrack_init(struct net __attribute__((unused)) *net)
1189 {
1190         return nfsd4_umh_cltrack_upcall("init", NULL, NULL);
1191 }
1192
1193 static void
1194 nfsd4_umh_cltrack_create(struct nfs4_client *clp)
1195 {
1196         char *hexid;
1197
1198         hexid = bin_to_hex_dup(clp->cl_name.data, clp->cl_name.len);
1199         if (!hexid) {
1200                 dprintk("%s: can't allocate memory for upcall!\n", __func__);
1201                 return;
1202         }
1203         nfsd4_umh_cltrack_upcall("create", hexid, NULL);
1204         kfree(hexid);
1205 }
1206
1207 static void
1208 nfsd4_umh_cltrack_remove(struct nfs4_client *clp)
1209 {
1210         char *hexid;
1211
1212         hexid = bin_to_hex_dup(clp->cl_name.data, clp->cl_name.len);
1213         if (!hexid) {
1214                 dprintk("%s: can't allocate memory for upcall!\n", __func__);
1215                 return;
1216         }
1217         nfsd4_umh_cltrack_upcall("remove", hexid, NULL);
1218         kfree(hexid);
1219 }
1220
1221 static int
1222 nfsd4_umh_cltrack_check(struct nfs4_client *clp)
1223 {
1224         int ret;
1225         char *hexid, *legacy;
1226
1227         hexid = bin_to_hex_dup(clp->cl_name.data, clp->cl_name.len);
1228         if (!hexid) {
1229                 dprintk("%s: can't allocate memory for upcall!\n", __func__);
1230                 return -ENOMEM;
1231         }
1232         legacy = nfsd4_cltrack_legacy_recdir(&clp->cl_name);
1233         ret = nfsd4_umh_cltrack_upcall("check", hexid, legacy);
1234         kfree(legacy);
1235         kfree(hexid);
1236         return ret;
1237 }
1238
1239 static void
1240 nfsd4_umh_cltrack_grace_done(struct nfsd_net __attribute__((unused)) *nn,
1241                                 time_t boot_time)
1242 {
1243         char *legacy;
1244         char timestr[22]; /* FIXME: better way to determine max size? */
1245
1246         sprintf(timestr, "%ld", boot_time);
1247         legacy = nfsd4_cltrack_legacy_topdir();
1248         nfsd4_umh_cltrack_upcall("gracedone", timestr, legacy);
1249         kfree(legacy);
1250 }
1251
1252 static struct nfsd4_client_tracking_ops nfsd4_umh_tracking_ops = {
1253         .init           = nfsd4_umh_cltrack_init,
1254         .exit           = NULL,
1255         .create         = nfsd4_umh_cltrack_create,
1256         .remove         = nfsd4_umh_cltrack_remove,
1257         .check          = nfsd4_umh_cltrack_check,
1258         .grace_done     = nfsd4_umh_cltrack_grace_done,
1259 };
1260
1261 int
1262 nfsd4_client_tracking_init(struct net *net)
1263 {
1264         int status;
1265         struct path path;
1266
1267         /* just run the init if it the method is already decided */
1268         if (client_tracking_ops)
1269                 goto do_init;
1270
1271         /*
1272          * First, try a UMH upcall. It should succeed or fail quickly, so
1273          * there's little harm in trying that first.
1274          */
1275         client_tracking_ops = &nfsd4_umh_tracking_ops;
1276         status = client_tracking_ops->init(net);
1277         if (!status)
1278                 return status;
1279
1280         /*
1281          * See if the recoverydir exists and is a directory. If it is,
1282          * then use the legacy ops.
1283          */
1284         client_tracking_ops = &nfsd4_legacy_tracking_ops;
1285         status = kern_path(nfs4_recoverydir(), LOOKUP_FOLLOW, &path);
1286         if (!status) {
1287                 status = S_ISDIR(path.dentry->d_inode->i_mode);
1288                 path_put(&path);
1289                 if (status)
1290                         goto do_init;
1291         }
1292
1293         /* Finally, try to use nfsdcld */
1294         client_tracking_ops = &nfsd4_cld_tracking_ops;
1295         printk(KERN_WARNING "NFSD: the nfsdcld client tracking upcall will be "
1296                         "removed in 3.10. Please transition to using "
1297                         "nfsdcltrack.\n");
1298 do_init:
1299         status = client_tracking_ops->init(net);
1300         if (status) {
1301                 printk(KERN_WARNING "NFSD: Unable to initialize client "
1302                                     "recovery tracking! (%d)\n", status);
1303                 client_tracking_ops = NULL;
1304         }
1305         return status;
1306 }
1307
1308 void
1309 nfsd4_client_tracking_exit(struct net *net)
1310 {
1311         if (client_tracking_ops) {
1312                 if (client_tracking_ops->exit)
1313                         client_tracking_ops->exit(net);
1314                 client_tracking_ops = NULL;
1315         }
1316 }
1317
1318 void
1319 nfsd4_client_record_create(struct nfs4_client *clp)
1320 {
1321         if (client_tracking_ops)
1322                 client_tracking_ops->create(clp);
1323 }
1324
1325 void
1326 nfsd4_client_record_remove(struct nfs4_client *clp)
1327 {
1328         if (client_tracking_ops)
1329                 client_tracking_ops->remove(clp);
1330 }
1331
1332 int
1333 nfsd4_client_record_check(struct nfs4_client *clp)
1334 {
1335         if (client_tracking_ops)
1336                 return client_tracking_ops->check(clp);
1337
1338         return -EOPNOTSUPP;
1339 }
1340
1341 void
1342 nfsd4_record_grace_done(struct nfsd_net *nn, time_t boot_time)
1343 {
1344         if (client_tracking_ops)
1345                 client_tracking_ops->grace_done(nn, boot_time);
1346 }
1347
1348 static int
1349 rpc_pipefs_event(struct notifier_block *nb, unsigned long event, void *ptr)
1350 {
1351         struct super_block *sb = ptr;
1352         struct net *net = sb->s_fs_info;
1353         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
1354         struct cld_net *cn = nn->cld_net;
1355         struct dentry *dentry;
1356         int ret = 0;
1357
1358         if (!try_module_get(THIS_MODULE))
1359                 return 0;
1360
1361         if (!cn) {
1362                 module_put(THIS_MODULE);
1363                 return 0;
1364         }
1365
1366         switch (event) {
1367         case RPC_PIPEFS_MOUNT:
1368                 dentry = nfsd4_cld_register_sb(sb, cn->cn_pipe);
1369                 if (IS_ERR(dentry)) {
1370                         ret = PTR_ERR(dentry);
1371                         break;
1372                 }
1373                 cn->cn_pipe->dentry = dentry;
1374                 break;
1375         case RPC_PIPEFS_UMOUNT:
1376                 if (cn->cn_pipe->dentry)
1377                         nfsd4_cld_unregister_sb(cn->cn_pipe);
1378                 break;
1379         default:
1380                 ret = -ENOTSUPP;
1381                 break;
1382         }
1383         module_put(THIS_MODULE);
1384         return ret;
1385 }
1386
1387 static struct notifier_block nfsd4_cld_block = {
1388         .notifier_call = rpc_pipefs_event,
1389 };
1390
1391 int
1392 register_cld_notifier(void)
1393 {
1394         return rpc_pipefs_notifier_register(&nfsd4_cld_block);
1395 }
1396
1397 void
1398 unregister_cld_notifier(void)
1399 {
1400         rpc_pipefs_notifier_unregister(&nfsd4_cld_block);
1401 }