]> Pileus Git - ~andy/linux/blob - drivers/staging/lustre/lustre/mgc/mgc_request.c
Merge tag 'iio-for-3.14a' of git://git.kernel.org/pub/scm/linux/kernel/git/jic23...
[~andy/linux] / drivers / staging / lustre / lustre / mgc / mgc_request.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2012, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/mgc/mgc_request.c
37  *
38  * Author: Nathan Rutman <nathan@clusterfs.com>
39  */
40
41 #define DEBUG_SUBSYSTEM S_MGC
42 #define D_MGC D_CONFIG /*|D_WARNING*/
43
44 # include <linux/module.h>
45 # include <linux/pagemap.h>
46 # include <linux/miscdevice.h>
47 # include <linux/init.h>
48
49 #include <obd_class.h>
50 #include <lustre_dlm.h>
51 #include <lprocfs_status.h>
52 #include <lustre_log.h>
53 #include <lustre_fsfilt.h>
54 #include <lustre_disk.h>
55 #include "mgc_internal.h"
56
57 static int mgc_name2resid(char *name, int len, struct ldlm_res_id *res_id,
58                           int type)
59 {
60         __u64 resname = 0;
61
62         if (len > 8) {
63                 CERROR("name too long: %s\n", name);
64                 return -EINVAL;
65         }
66         if (len <= 0) {
67                 CERROR("missing name: %s\n", name);
68                 return -EINVAL;
69         }
70         memcpy(&resname, name, len);
71
72         /* Always use the same endianness for the resid */
73         memset(res_id, 0, sizeof(*res_id));
74         res_id->name[0] = cpu_to_le64(resname);
75         /* XXX: unfortunately, sptlprc and config llog share one lock */
76         switch(type) {
77         case CONFIG_T_CONFIG:
78         case CONFIG_T_SPTLRPC:
79                 resname = 0;
80                 break;
81         case CONFIG_T_RECOVER:
82                 resname = type;
83                 break;
84         default:
85                 LBUG();
86         }
87         res_id->name[1] = cpu_to_le64(resname);
88         CDEBUG(D_MGC, "log %s to resid "LPX64"/"LPX64" (%.8s)\n", name,
89                res_id->name[0], res_id->name[1], (char *)&res_id->name[0]);
90         return 0;
91 }
92
93 int mgc_fsname2resid(char *fsname, struct ldlm_res_id *res_id, int type)
94 {
95         /* fsname is at most 8 chars long, maybe contain "-".
96          * e.g. "lustre", "SUN-000" */
97         return mgc_name2resid(fsname, strlen(fsname), res_id, type);
98 }
99 EXPORT_SYMBOL(mgc_fsname2resid);
100
101 int mgc_logname2resid(char *logname, struct ldlm_res_id *res_id, int type)
102 {
103         char *name_end;
104         int len;
105
106         /* logname consists of "fsname-nodetype".
107          * e.g. "lustre-MDT0001", "SUN-000-client" */
108         name_end = strrchr(logname, '-');
109         LASSERT(name_end);
110         len = name_end - logname;
111         return mgc_name2resid(logname, len, res_id, type);
112 }
113
114 /********************** config llog list **********************/
115 static LIST_HEAD(config_llog_list);
116 static DEFINE_SPINLOCK(config_list_lock);
117
118 /* Take a reference to a config log */
119 static int config_log_get(struct config_llog_data *cld)
120 {
121         atomic_inc(&cld->cld_refcount);
122         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
123                atomic_read(&cld->cld_refcount));
124         return 0;
125 }
126
127 /* Drop a reference to a config log.  When no longer referenced,
128    we can free the config log data */
129 static void config_log_put(struct config_llog_data *cld)
130 {
131         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
132                atomic_read(&cld->cld_refcount));
133         LASSERT(atomic_read(&cld->cld_refcount) > 0);
134
135         /* spinlock to make sure no item with 0 refcount in the list */
136         if (atomic_dec_and_lock(&cld->cld_refcount, &config_list_lock)) {
137                 list_del(&cld->cld_list_chain);
138                 spin_unlock(&config_list_lock);
139
140                 CDEBUG(D_MGC, "dropping config log %s\n", cld->cld_logname);
141
142                 if (cld->cld_recover)
143                         config_log_put(cld->cld_recover);
144                 if (cld->cld_sptlrpc)
145                         config_log_put(cld->cld_sptlrpc);
146                 if (cld_is_sptlrpc(cld))
147                         sptlrpc_conf_log_stop(cld->cld_logname);
148
149                 class_export_put(cld->cld_mgcexp);
150                 OBD_FREE(cld, sizeof(*cld) + strlen(cld->cld_logname) + 1);
151         }
152 }
153
154 /* Find a config log by name */
155 static
156 struct config_llog_data *config_log_find(char *logname,
157                                          struct config_llog_instance *cfg)
158 {
159         struct config_llog_data *cld;
160         struct config_llog_data *found = NULL;
161         void *             instance;
162
163         LASSERT(logname != NULL);
164
165         instance = cfg ? cfg->cfg_instance : NULL;
166         spin_lock(&config_list_lock);
167         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
168                 /* check if instance equals */
169                 if (instance != cld->cld_cfg.cfg_instance)
170                         continue;
171
172                 /* instance may be NULL, should check name */
173                 if (strcmp(logname, cld->cld_logname) == 0) {
174                         found = cld;
175                         break;
176                 }
177         }
178         if (found) {
179                 atomic_inc(&found->cld_refcount);
180                 LASSERT(found->cld_stopping == 0 || cld_is_sptlrpc(found) == 0);
181         }
182         spin_unlock(&config_list_lock);
183         return found;
184 }
185
186 static
187 struct config_llog_data *do_config_log_add(struct obd_device *obd,
188                                            char *logname,
189                                            int type,
190                                            struct config_llog_instance *cfg,
191                                            struct super_block *sb)
192 {
193         struct config_llog_data *cld;
194         int                   rc;
195
196         CDEBUG(D_MGC, "do adding config log %s:%p\n", logname,
197                cfg ? cfg->cfg_instance : 0);
198
199         OBD_ALLOC(cld, sizeof(*cld) + strlen(logname) + 1);
200         if (!cld)
201                 return ERR_PTR(-ENOMEM);
202
203         strcpy(cld->cld_logname, logname);
204         if (cfg)
205                 cld->cld_cfg = *cfg;
206         else
207                 cld->cld_cfg.cfg_callback = class_config_llog_handler;
208         mutex_init(&cld->cld_lock);
209         cld->cld_cfg.cfg_last_idx = 0;
210         cld->cld_cfg.cfg_flags = 0;
211         cld->cld_cfg.cfg_sb = sb;
212         cld->cld_type = type;
213         atomic_set(&cld->cld_refcount, 1);
214
215         /* Keep the mgc around until we are done */
216         cld->cld_mgcexp = class_export_get(obd->obd_self_export);
217
218         if (cld_is_sptlrpc(cld)) {
219                 sptlrpc_conf_log_start(logname);
220                 cld->cld_cfg.cfg_obdname = obd->obd_name;
221         }
222
223         rc = mgc_logname2resid(logname, &cld->cld_resid, type);
224
225         spin_lock(&config_list_lock);
226         list_add(&cld->cld_list_chain, &config_llog_list);
227         spin_unlock(&config_list_lock);
228
229         if (rc) {
230                 config_log_put(cld);
231                 return ERR_PTR(rc);
232         }
233
234         if (cld_is_sptlrpc(cld)) {
235                 rc = mgc_process_log(obd, cld);
236                 if (rc && rc != -ENOENT)
237                         CERROR("failed processing sptlrpc log: %d\n", rc);
238         }
239
240         return cld;
241 }
242
243 static struct config_llog_data *config_recover_log_add(struct obd_device *obd,
244         char *fsname,
245         struct config_llog_instance *cfg,
246         struct super_block *sb)
247 {
248         struct config_llog_instance lcfg = *cfg;
249         struct lustre_sb_info *lsi = s2lsi(sb);
250         struct config_llog_data *cld;
251         char logname[32];
252
253         if (IS_OST(lsi))
254                 return NULL;
255
256         /* for osp-on-ost, see lustre_start_osp() */
257         if (IS_MDT(lsi) && lcfg.cfg_instance)
258                 return NULL;
259
260         /* we have to use different llog for clients and mdts for cmd
261          * where only clients are notified if one of cmd server restarts */
262         LASSERT(strlen(fsname) < sizeof(logname) / 2);
263         strcpy(logname, fsname);
264         if (IS_SERVER(lsi)) { /* mdt */
265                 LASSERT(lcfg.cfg_instance == NULL);
266                 lcfg.cfg_instance = sb;
267                 strcat(logname, "-mdtir");
268         } else {
269                 LASSERT(lcfg.cfg_instance != NULL);
270                 strcat(logname, "-cliir");
271         }
272
273         cld = do_config_log_add(obd, logname, CONFIG_T_RECOVER, &lcfg, sb);
274         return cld;
275 }
276
277
278 /** Add this log to the list of active logs watched by an MGC.
279  * Active means we're watching for updates.
280  * We have one active log per "mount" - client instance or servername.
281  * Each instance may be at a different point in the log.
282  */
283 static int config_log_add(struct obd_device *obd, char *logname,
284                           struct config_llog_instance *cfg,
285                           struct super_block *sb)
286 {
287         struct lustre_sb_info *lsi = s2lsi(sb);
288         struct config_llog_data *cld;
289         struct config_llog_data *sptlrpc_cld;
290         char                 seclogname[32];
291         char                *ptr;
292
293         CDEBUG(D_MGC, "adding config log %s:%p\n", logname, cfg->cfg_instance);
294
295         /*
296          * for each regular log, the depended sptlrpc log name is
297          * <fsname>-sptlrpc. multiple regular logs may share one sptlrpc log.
298          */
299         ptr = strrchr(logname, '-');
300         if (ptr == NULL || ptr - logname > 8) {
301                 CERROR("logname %s is too long\n", logname);
302                 return -EINVAL;
303         }
304
305         memcpy(seclogname, logname, ptr - logname);
306         strcpy(seclogname + (ptr - logname), "-sptlrpc");
307
308         sptlrpc_cld = config_log_find(seclogname, NULL);
309         if (sptlrpc_cld == NULL) {
310                 sptlrpc_cld = do_config_log_add(obd, seclogname,
311                                                 CONFIG_T_SPTLRPC, NULL, NULL);
312                 if (IS_ERR(sptlrpc_cld)) {
313                         CERROR("can't create sptlrpc log: %s\n", seclogname);
314                         return PTR_ERR(sptlrpc_cld);
315                 }
316         }
317
318         cld = do_config_log_add(obd, logname, CONFIG_T_CONFIG, cfg, sb);
319         if (IS_ERR(cld)) {
320                 CERROR("can't create log: %s\n", logname);
321                 config_log_put(sptlrpc_cld);
322                 return PTR_ERR(cld);
323         }
324
325         cld->cld_sptlrpc = sptlrpc_cld;
326
327         LASSERT(lsi->lsi_lmd);
328         if (!(lsi->lsi_lmd->lmd_flags & LMD_FLG_NOIR)) {
329                 struct config_llog_data *recover_cld;
330                 *strrchr(seclogname, '-') = 0;
331                 recover_cld = config_recover_log_add(obd, seclogname, cfg, sb);
332                 if (IS_ERR(recover_cld)) {
333                         config_log_put(cld);
334                         return PTR_ERR(recover_cld);
335                 }
336                 cld->cld_recover = recover_cld;
337         }
338
339         return 0;
340 }
341
342 DEFINE_MUTEX(llog_process_lock);
343
344 /** Stop watching for updates on this log.
345  */
346 static int config_log_end(char *logname, struct config_llog_instance *cfg)
347 {
348         struct config_llog_data *cld;
349         struct config_llog_data *cld_sptlrpc = NULL;
350         struct config_llog_data *cld_recover = NULL;
351         int rc = 0;
352
353         cld = config_log_find(logname, cfg);
354         if (cld == NULL)
355                 return -ENOENT;
356
357         mutex_lock(&cld->cld_lock);
358         /*
359          * if cld_stopping is set, it means we didn't start the log thus
360          * not owning the start ref. this can happen after previous umount:
361          * the cld still hanging there waiting for lock cancel, and we
362          * remount again but failed in the middle and call log_end without
363          * calling start_log.
364          */
365         if (unlikely(cld->cld_stopping)) {
366                 mutex_unlock(&cld->cld_lock);
367                 /* drop the ref from the find */
368                 config_log_put(cld);
369                 return rc;
370         }
371
372         cld->cld_stopping = 1;
373
374         cld_recover = cld->cld_recover;
375         cld->cld_recover = NULL;
376         mutex_unlock(&cld->cld_lock);
377
378         if (cld_recover) {
379                 mutex_lock(&cld_recover->cld_lock);
380                 cld_recover->cld_stopping = 1;
381                 mutex_unlock(&cld_recover->cld_lock);
382                 config_log_put(cld_recover);
383         }
384
385         spin_lock(&config_list_lock);
386         cld_sptlrpc = cld->cld_sptlrpc;
387         cld->cld_sptlrpc = NULL;
388         spin_unlock(&config_list_lock);
389
390         if (cld_sptlrpc)
391                 config_log_put(cld_sptlrpc);
392
393         /* drop the ref from the find */
394         config_log_put(cld);
395         /* drop the start ref */
396         config_log_put(cld);
397
398         CDEBUG(D_MGC, "end config log %s (%d)\n", logname ? logname : "client",
399                rc);
400         return rc;
401 }
402
403 int lprocfs_mgc_rd_ir_state(struct seq_file *m, void *data)
404 {
405         struct obd_device       *obd = data;
406         struct obd_import       *imp = obd->u.cli.cl_import;
407         struct obd_connect_data *ocd = &imp->imp_connect_data;
408         struct config_llog_data *cld;
409
410         seq_printf(m, "imperative_recovery: %s\n",
411                       OCD_HAS_FLAG(ocd, IMP_RECOV) ? "ENABLED" : "DISABLED");
412         seq_printf(m, "client_state:\n");
413
414         spin_lock(&config_list_lock);
415         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
416                 if (cld->cld_recover == NULL)
417                         continue;
418                 seq_printf(m,  "    - { client: %s, nidtbl_version: %u }\n",
419                                cld->cld_logname,
420                                cld->cld_recover->cld_cfg.cfg_last_idx);
421         }
422         spin_unlock(&config_list_lock);
423
424         return 0;
425 }
426
427 /* reenqueue any lost locks */
428 #define RQ_RUNNING 0x1
429 #define RQ_NOW     0x2
430 #define RQ_LATER   0x4
431 #define RQ_STOP    0x8
432 static int                  rq_state = 0;
433 static wait_queue_head_t            rq_waitq;
434 static DECLARE_COMPLETION(rq_exit);
435
436 static void do_requeue(struct config_llog_data *cld)
437 {
438         LASSERT(atomic_read(&cld->cld_refcount) > 0);
439
440         /* Do not run mgc_process_log on a disconnected export or an
441            export which is being disconnected. Take the client
442            semaphore to make the check non-racy. */
443         down_read(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem);
444         if (cld->cld_mgcexp->exp_obd->u.cli.cl_conn_count != 0) {
445                 CDEBUG(D_MGC, "updating log %s\n", cld->cld_logname);
446                 mgc_process_log(cld->cld_mgcexp->exp_obd, cld);
447         } else {
448                 CDEBUG(D_MGC, "disconnecting, won't update log %s\n",
449                        cld->cld_logname);
450         }
451         up_read(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem);
452 }
453
454 /* this timeout represents how many seconds MGC should wait before
455  * requeue config and recover lock to the MGS. We need to randomize this
456  * in order to not flood the MGS.
457  */
458 #define MGC_TIMEOUT_MIN_SECONDS   5
459 #define MGC_TIMEOUT_RAND_CENTISEC 0x1ff /* ~500 */
460
461 static int mgc_requeue_thread(void *data)
462 {
463         int rc = 0;
464
465         CDEBUG(D_MGC, "Starting requeue thread\n");
466
467         /* Keep trying failed locks periodically */
468         spin_lock(&config_list_lock);
469         rq_state |= RQ_RUNNING;
470         while (1) {
471                 struct l_wait_info lwi;
472                 struct config_llog_data *cld, *cld_prev;
473                 int rand = cfs_rand() & MGC_TIMEOUT_RAND_CENTISEC;
474                 int stopped = !!(rq_state & RQ_STOP);
475                 int to;
476
477                 /* Any new or requeued lostlocks will change the state */
478                 rq_state &= ~(RQ_NOW | RQ_LATER);
479                 spin_unlock(&config_list_lock);
480
481                 /* Always wait a few seconds to allow the server who
482                    caused the lock revocation to finish its setup, plus some
483                    random so everyone doesn't try to reconnect at once. */
484                 to = MGC_TIMEOUT_MIN_SECONDS * HZ;
485                 to += rand * HZ / 100; /* rand is centi-seconds */
486                 lwi = LWI_TIMEOUT(to, NULL, NULL);
487                 l_wait_event(rq_waitq, rq_state & RQ_STOP, &lwi);
488
489                 /*
490                  * iterate & processing through the list. for each cld, process
491                  * its depending sptlrpc cld firstly (if any) and then itself.
492                  *
493                  * it's guaranteed any item in the list must have
494                  * reference > 0; and if cld_lostlock is set, at
495                  * least one reference is taken by the previous enqueue.
496                  */
497                 cld_prev = NULL;
498
499                 spin_lock(&config_list_lock);
500                 list_for_each_entry(cld, &config_llog_list,
501                                         cld_list_chain) {
502                         if (!cld->cld_lostlock)
503                                 continue;
504
505                         spin_unlock(&config_list_lock);
506
507                         LASSERT(atomic_read(&cld->cld_refcount) > 0);
508
509                         /* Whether we enqueued again or not in mgc_process_log,
510                          * we're done with the ref from the old enqueue */
511                         if (cld_prev)
512                                 config_log_put(cld_prev);
513                         cld_prev = cld;
514
515                         cld->cld_lostlock = 0;
516                         if (likely(!stopped))
517                                 do_requeue(cld);
518
519                         spin_lock(&config_list_lock);
520                 }
521                 spin_unlock(&config_list_lock);
522                 if (cld_prev)
523                         config_log_put(cld_prev);
524
525                 /* break after scanning the list so that we can drop
526                  * refcount to losing lock clds */
527                 if (unlikely(stopped)) {
528                         spin_lock(&config_list_lock);
529                         break;
530                 }
531
532                 /* Wait a bit to see if anyone else needs a requeue */
533                 lwi = (struct l_wait_info) { 0 };
534                 l_wait_event(rq_waitq, rq_state & (RQ_NOW | RQ_STOP),
535                              &lwi);
536                 spin_lock(&config_list_lock);
537         }
538         /* spinlock and while guarantee RQ_NOW and RQ_LATER are not set */
539         rq_state &= ~RQ_RUNNING;
540         spin_unlock(&config_list_lock);
541
542         complete(&rq_exit);
543
544         CDEBUG(D_MGC, "Ending requeue thread\n");
545         return rc;
546 }
547
548 /* Add a cld to the list to requeue.  Start the requeue thread if needed.
549    We are responsible for dropping the config log reference from here on out. */
550 static void mgc_requeue_add(struct config_llog_data *cld)
551 {
552         CDEBUG(D_INFO, "log %s: requeue (r=%d sp=%d st=%x)\n",
553                cld->cld_logname, atomic_read(&cld->cld_refcount),
554                cld->cld_stopping, rq_state);
555         LASSERT(atomic_read(&cld->cld_refcount) > 0);
556
557         mutex_lock(&cld->cld_lock);
558         if (cld->cld_stopping || cld->cld_lostlock) {
559                 mutex_unlock(&cld->cld_lock);
560                 return;
561         }
562         /* this refcount will be released in mgc_requeue_thread. */
563         config_log_get(cld);
564         cld->cld_lostlock = 1;
565         mutex_unlock(&cld->cld_lock);
566
567         /* Hold lock for rq_state */
568         spin_lock(&config_list_lock);
569         if (rq_state & RQ_STOP) {
570                 spin_unlock(&config_list_lock);
571                 cld->cld_lostlock = 0;
572                 config_log_put(cld);
573         } else {
574                 rq_state |= RQ_NOW;
575                 spin_unlock(&config_list_lock);
576                 wake_up(&rq_waitq);
577         }
578 }
579
580 /********************** class fns **********************/
581
582 static int mgc_fs_setup(struct obd_device *obd, struct super_block *sb,
583                         struct vfsmount *mnt)
584 {
585         struct lvfs_run_ctxt saved;
586         struct lustre_sb_info *lsi = s2lsi(sb);
587         struct client_obd *cli = &obd->u.cli;
588         struct dentry *dentry;
589         char *label;
590         int err = 0;
591
592         LASSERT(lsi);
593         LASSERT(lsi->lsi_srv_mnt == mnt);
594
595         /* The mgc fs exclusion sem. Only one fs can be setup at a time. */
596         down(&cli->cl_mgc_sem);
597
598         cfs_cleanup_group_info();
599
600         obd->obd_fsops = fsfilt_get_ops(lsi->lsi_fstype);
601         if (IS_ERR(obd->obd_fsops)) {
602                 up(&cli->cl_mgc_sem);
603                 CERROR("%s: No fstype %s: rc = %ld\n", lsi->lsi_fstype,
604                        obd->obd_name, PTR_ERR(obd->obd_fsops));
605                 return PTR_ERR(obd->obd_fsops);
606         }
607
608         cli->cl_mgc_vfsmnt = mnt;
609         err = fsfilt_setup(obd, mnt->mnt_sb);
610         if (err)
611                 GOTO(err_ops, err);
612
613         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
614         obd->obd_lvfs_ctxt.pwdmnt = mnt;
615         obd->obd_lvfs_ctxt.pwd = mnt->mnt_root;
616         obd->obd_lvfs_ctxt.fs = get_ds();
617
618         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
619         dentry = ll_lookup_one_len(MOUNT_CONFIGS_DIR, cfs_fs_pwd(current->fs),
620                                    strlen(MOUNT_CONFIGS_DIR));
621         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
622         if (IS_ERR(dentry)) {
623                 err = PTR_ERR(dentry);
624                 CERROR("cannot lookup %s directory: rc = %d\n",
625                        MOUNT_CONFIGS_DIR, err);
626                 GOTO(err_ops, err);
627         }
628         cli->cl_mgc_configs_dir = dentry;
629
630         /* We take an obd ref to insure that we can't get to mgc_cleanup
631            without calling mgc_fs_cleanup first. */
632         class_incref(obd, "mgc_fs", obd);
633
634         label = fsfilt_get_label(obd, mnt->mnt_sb);
635         if (label)
636                 CDEBUG(D_MGC, "MGC using disk labelled=%s\n", label);
637
638         /* We keep the cl_mgc_sem until mgc_fs_cleanup */
639         return 0;
640
641 err_ops:
642         fsfilt_put_ops(obd->obd_fsops);
643         obd->obd_fsops = NULL;
644         cli->cl_mgc_vfsmnt = NULL;
645         up(&cli->cl_mgc_sem);
646         return err;
647 }
648
649 static int mgc_fs_cleanup(struct obd_device *obd)
650 {
651         struct client_obd *cli = &obd->u.cli;
652         int rc = 0;
653
654         LASSERT(cli->cl_mgc_vfsmnt != NULL);
655
656         if (cli->cl_mgc_configs_dir != NULL) {
657                 struct lvfs_run_ctxt saved;
658                 push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
659                 l_dput(cli->cl_mgc_configs_dir);
660                 cli->cl_mgc_configs_dir = NULL;
661                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
662                 class_decref(obd, "mgc_fs", obd);
663         }
664
665         cli->cl_mgc_vfsmnt = NULL;
666         if (obd->obd_fsops)
667                 fsfilt_put_ops(obd->obd_fsops);
668
669         up(&cli->cl_mgc_sem);
670
671         return rc;
672 }
673
674 static atomic_t mgc_count = ATOMIC_INIT(0);
675 static int mgc_precleanup(struct obd_device *obd, enum obd_cleanup_stage stage)
676 {
677         int rc = 0;
678
679         switch (stage) {
680         case OBD_CLEANUP_EARLY:
681                 break;
682         case OBD_CLEANUP_EXPORTS:
683                 if (atomic_dec_and_test(&mgc_count)) {
684                         int running;
685                         /* stop requeue thread */
686                         spin_lock(&config_list_lock);
687                         running = rq_state & RQ_RUNNING;
688                         if (running)
689                                 rq_state |= RQ_STOP;
690                         spin_unlock(&config_list_lock);
691                         if (running) {
692                                 wake_up(&rq_waitq);
693                                 wait_for_completion(&rq_exit);
694                         }
695                 }
696                 obd_cleanup_client_import(obd);
697                 rc = obd_llog_finish(obd, 0);
698                 if (rc != 0)
699                         CERROR("failed to cleanup llogging subsystems\n");
700                 break;
701         }
702         return rc;
703 }
704
705 static int mgc_cleanup(struct obd_device *obd)
706 {
707         struct client_obd *cli = &obd->u.cli;
708         int rc;
709
710         LASSERT(cli->cl_mgc_vfsmnt == NULL);
711
712         /* COMPAT_146 - old config logs may have added profiles we don't
713            know about */
714         if (obd->obd_type->typ_refcnt <= 1)
715                 /* Only for the last mgc */
716                 class_del_profiles();
717
718         lprocfs_obd_cleanup(obd);
719         ptlrpcd_decref();
720
721         rc = client_obd_cleanup(obd);
722         return rc;
723 }
724
725 static int mgc_setup(struct obd_device *obd, struct lustre_cfg *lcfg)
726 {
727         struct lprocfs_static_vars lvars;
728         int rc;
729
730         ptlrpcd_addref();
731
732         rc = client_obd_setup(obd, lcfg);
733         if (rc)
734                 GOTO(err_decref, rc);
735
736         rc = obd_llog_init(obd, &obd->obd_olg, obd, NULL);
737         if (rc) {
738                 CERROR("failed to setup llogging subsystems\n");
739                 GOTO(err_cleanup, rc);
740         }
741
742         lprocfs_mgc_init_vars(&lvars);
743         lprocfs_obd_setup(obd, lvars.obd_vars);
744         sptlrpc_lprocfs_cliobd_attach(obd);
745
746         if (atomic_inc_return(&mgc_count) == 1) {
747                 rq_state = 0;
748                 init_waitqueue_head(&rq_waitq);
749
750                 /* start requeue thread */
751                 rc = PTR_ERR(kthread_run(mgc_requeue_thread, NULL,
752                                              "ll_cfg_requeue"));
753                 if (IS_ERR_VALUE(rc)) {
754                         CERROR("%s: Cannot start requeue thread (%d),"
755                                "no more log updates!\n",
756                                obd->obd_name, rc);
757                         GOTO(err_cleanup, rc);
758                 }
759                 /* rc is the task_struct pointer of mgc_requeue_thread. */
760                 rc = 0;
761         }
762
763         return rc;
764
765 err_cleanup:
766         client_obd_cleanup(obd);
767 err_decref:
768         ptlrpcd_decref();
769         return rc;
770 }
771
772 /* based on ll_mdc_blocking_ast */
773 static int mgc_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
774                             void *data, int flag)
775 {
776         struct lustre_handle lockh;
777         struct config_llog_data *cld = (struct config_llog_data *)data;
778         int rc = 0;
779
780         switch (flag) {
781         case LDLM_CB_BLOCKING:
782                 /* mgs wants the lock, give it up... */
783                 LDLM_DEBUG(lock, "MGC blocking CB");
784                 ldlm_lock2handle(lock, &lockh);
785                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
786                 break;
787         case LDLM_CB_CANCELING:
788                 /* We've given up the lock, prepare ourselves to update. */
789                 LDLM_DEBUG(lock, "MGC cancel CB");
790
791                 CDEBUG(D_MGC, "Lock res "DLDLMRES" (%.8s)\n",
792                        PLDLMRES(lock->l_resource),
793                        (char *)&lock->l_resource->lr_name.name[0]);
794
795                 if (!cld) {
796                         CDEBUG(D_INFO, "missing data, won't requeue\n");
797                         break;
798                 }
799
800                 /* held at mgc_process_log(). */
801                 LASSERT(atomic_read(&cld->cld_refcount) > 0);
802                 /* Are we done with this log? */
803                 if (cld->cld_stopping) {
804                         CDEBUG(D_MGC, "log %s: stopping, won't requeue\n",
805                                cld->cld_logname);
806                         config_log_put(cld);
807                         break;
808                 }
809                 /* Make sure not to re-enqueue when the mgc is stopping
810                    (we get called from client_disconnect_export) */
811                 if (!lock->l_conn_export ||
812                     !lock->l_conn_export->exp_obd->u.cli.cl_conn_count) {
813                         CDEBUG(D_MGC, "log %.8s: disconnecting, won't requeue\n",
814                                cld->cld_logname);
815                         config_log_put(cld);
816                         break;
817                 }
818
819                 /* Re-enqueue now */
820                 mgc_requeue_add(cld);
821                 config_log_put(cld);
822                 break;
823         default:
824                 LBUG();
825         }
826
827         return rc;
828 }
829
830 /* Not sure where this should go... */
831 #define  MGC_ENQUEUE_LIMIT 50
832 #define  MGC_TARGET_REG_LIMIT 10
833 #define  MGC_SEND_PARAM_LIMIT 10
834
835 /* Send parameter to MGS*/
836 static int mgc_set_mgs_param(struct obd_export *exp,
837                              struct mgs_send_param *msp)
838 {
839         struct ptlrpc_request *req;
840         struct mgs_send_param *req_msp, *rep_msp;
841         int rc;
842
843         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
844                                         &RQF_MGS_SET_INFO, LUSTRE_MGS_VERSION,
845                                         MGS_SET_INFO);
846         if (!req)
847                 return -ENOMEM;
848
849         req_msp = req_capsule_client_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
850         if (!req_msp) {
851                 ptlrpc_req_finished(req);
852                 return -ENOMEM;
853         }
854
855         memcpy(req_msp, msp, sizeof(*req_msp));
856         ptlrpc_request_set_replen(req);
857
858         /* Limit how long we will wait for the enqueue to complete */
859         req->rq_delay_limit = MGC_SEND_PARAM_LIMIT;
860         rc = ptlrpc_queue_wait(req);
861         if (!rc) {
862                 rep_msp = req_capsule_server_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
863                 memcpy(msp, rep_msp, sizeof(*rep_msp));
864         }
865
866         ptlrpc_req_finished(req);
867
868         return rc;
869 }
870
871 /* Take a config lock so we can get cancel notifications */
872 static int mgc_enqueue(struct obd_export *exp, struct lov_stripe_md *lsm,
873                        __u32 type, ldlm_policy_data_t *policy, __u32 mode,
874                        __u64 *flags, void *bl_cb, void *cp_cb, void *gl_cb,
875                        void *data, __u32 lvb_len, void *lvb_swabber,
876                        struct lustre_handle *lockh)
877 {
878         struct config_llog_data *cld = (struct config_llog_data *)data;
879         struct ldlm_enqueue_info einfo = {
880                 .ei_type        = type,
881                 .ei_mode        = mode,
882                 .ei_cb_bl       = mgc_blocking_ast,
883                 .ei_cb_cp       = ldlm_completion_ast,
884         };
885         struct ptlrpc_request *req;
886         int short_limit = cld_is_sptlrpc(cld);
887         int rc;
888
889         CDEBUG(D_MGC, "Enqueue for %s (res "LPX64")\n", cld->cld_logname,
890                cld->cld_resid.name[0]);
891
892         /* We need a callback for every lockholder, so don't try to
893            ldlm_lock_match (see rev 1.1.2.11.2.47) */
894         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
895                                         &RQF_LDLM_ENQUEUE, LUSTRE_DLM_VERSION,
896                                         LDLM_ENQUEUE);
897         if (req == NULL)
898                 return -ENOMEM;
899
900         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER, 0);
901         ptlrpc_request_set_replen(req);
902
903         /* check if this is server or client */
904         if (cld->cld_cfg.cfg_sb) {
905                 struct lustre_sb_info *lsi = s2lsi(cld->cld_cfg.cfg_sb);
906                 if (lsi && IS_SERVER(lsi))
907                         short_limit = 1;
908         }
909         /* Limit how long we will wait for the enqueue to complete */
910         req->rq_delay_limit = short_limit ? 5 : MGC_ENQUEUE_LIMIT;
911         rc = ldlm_cli_enqueue(exp, &req, &einfo, &cld->cld_resid, NULL, flags,
912                               NULL, 0, LVB_T_NONE, lockh, 0);
913         /* A failed enqueue should still call the mgc_blocking_ast,
914            where it will be requeued if needed ("grant failed"). */
915         ptlrpc_req_finished(req);
916         return rc;
917 }
918
919 static int mgc_cancel(struct obd_export *exp, struct lov_stripe_md *md,
920                       __u32 mode, struct lustre_handle *lockh)
921 {
922         ldlm_lock_decref(lockh, mode);
923
924         return 0;
925 }
926
927 static void mgc_notify_active(struct obd_device *unused)
928 {
929         /* wakeup mgc_requeue_thread to requeue mgc lock */
930         spin_lock(&config_list_lock);
931         rq_state |= RQ_NOW;
932         spin_unlock(&config_list_lock);
933         wake_up(&rq_waitq);
934
935         /* TODO: Help the MGS rebuild nidtbl. -jay */
936 }
937
938 /* Send target_reg message to MGS */
939 static int mgc_target_register(struct obd_export *exp,
940                                struct mgs_target_info *mti)
941 {
942         struct ptlrpc_request  *req;
943         struct mgs_target_info *req_mti, *rep_mti;
944         int                  rc;
945
946         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
947                                         &RQF_MGS_TARGET_REG, LUSTRE_MGS_VERSION,
948                                         MGS_TARGET_REG);
949         if (req == NULL)
950                 return -ENOMEM;
951
952         req_mti = req_capsule_client_get(&req->rq_pill, &RMF_MGS_TARGET_INFO);
953         if (!req_mti) {
954                 ptlrpc_req_finished(req);
955                 return -ENOMEM;
956         }
957
958         memcpy(req_mti, mti, sizeof(*req_mti));
959         ptlrpc_request_set_replen(req);
960         CDEBUG(D_MGC, "register %s\n", mti->mti_svname);
961         /* Limit how long we will wait for the enqueue to complete */
962         req->rq_delay_limit = MGC_TARGET_REG_LIMIT;
963
964         rc = ptlrpc_queue_wait(req);
965         if (!rc) {
966                 rep_mti = req_capsule_server_get(&req->rq_pill,
967                                                  &RMF_MGS_TARGET_INFO);
968                 memcpy(mti, rep_mti, sizeof(*rep_mti));
969                 CDEBUG(D_MGC, "register %s got index = %d\n",
970                        mti->mti_svname, mti->mti_stripe_index);
971         }
972         ptlrpc_req_finished(req);
973
974         return rc;
975 }
976
977 int mgc_set_info_async(const struct lu_env *env, struct obd_export *exp,
978                        obd_count keylen, void *key, obd_count vallen,
979                        void *val, struct ptlrpc_request_set *set)
980 {
981         int rc = -EINVAL;
982
983         /* Turn off initial_recov after we try all backup servers once */
984         if (KEY_IS(KEY_INIT_RECOV_BACKUP)) {
985                 struct obd_import *imp = class_exp2cliimp(exp);
986                 int value;
987                 if (vallen != sizeof(int))
988                         return -EINVAL;
989                 value = *(int *)val;
990                 CDEBUG(D_MGC, "InitRecov %s %d/d%d:i%d:r%d:or%d:%s\n",
991                        imp->imp_obd->obd_name, value,
992                        imp->imp_deactive, imp->imp_invalid,
993                        imp->imp_replayable, imp->imp_obd->obd_replayable,
994                        ptlrpc_import_state_name(imp->imp_state));
995                 /* Resurrect if we previously died */
996                 if ((imp->imp_state != LUSTRE_IMP_FULL &&
997                      imp->imp_state != LUSTRE_IMP_NEW) || value > 1)
998                         ptlrpc_reconnect_import(imp);
999                 return 0;
1000         }
1001         /* FIXME move this to mgc_process_config */
1002         if (KEY_IS(KEY_REGISTER_TARGET)) {
1003                 struct mgs_target_info *mti;
1004                 if (vallen != sizeof(struct mgs_target_info))
1005                         return -EINVAL;
1006                 mti = (struct mgs_target_info *)val;
1007                 CDEBUG(D_MGC, "register_target %s %#x\n",
1008                        mti->mti_svname, mti->mti_flags);
1009                 rc =  mgc_target_register(exp, mti);
1010                 return rc;
1011         }
1012         if (KEY_IS(KEY_SET_FS)) {
1013                 struct super_block *sb = (struct super_block *)val;
1014                 struct lustre_sb_info *lsi;
1015                 if (vallen != sizeof(struct super_block))
1016                         return -EINVAL;
1017                 lsi = s2lsi(sb);
1018                 rc = mgc_fs_setup(exp->exp_obd, sb, lsi->lsi_srv_mnt);
1019                 if (rc) {
1020                         CERROR("set_fs got %d\n", rc);
1021                 }
1022                 return rc;
1023         }
1024         if (KEY_IS(KEY_CLEAR_FS)) {
1025                 if (vallen != 0)
1026                         return -EINVAL;
1027                 rc = mgc_fs_cleanup(exp->exp_obd);
1028                 if (rc) {
1029                         CERROR("clear_fs got %d\n", rc);
1030                 }
1031                 return rc;
1032         }
1033         if (KEY_IS(KEY_SET_INFO)) {
1034                 struct mgs_send_param *msp;
1035
1036                 msp = (struct mgs_send_param *)val;
1037                 rc =  mgc_set_mgs_param(exp, msp);
1038                 return rc;
1039         }
1040         if (KEY_IS(KEY_MGSSEC)) {
1041                 struct client_obd     *cli = &exp->exp_obd->u.cli;
1042                 struct sptlrpc_flavor  flvr;
1043
1044                 /*
1045                  * empty string means using current flavor, if which haven't
1046                  * been set yet, set it as null.
1047                  *
1048                  * if flavor has been set previously, check the asking flavor
1049                  * must match the existing one.
1050                  */
1051                 if (vallen == 0) {
1052                         if (cli->cl_flvr_mgc.sf_rpc != SPTLRPC_FLVR_INVALID)
1053                                 return 0;
1054                         val = "null";
1055                         vallen = 4;
1056                 }
1057
1058                 rc = sptlrpc_parse_flavor(val, &flvr);
1059                 if (rc) {
1060                         CERROR("invalid sptlrpc flavor %s to MGS\n",
1061                                (char *) val);
1062                         return rc;
1063                 }
1064
1065                 /*
1066                  * caller already hold a mutex
1067                  */
1068                 if (cli->cl_flvr_mgc.sf_rpc == SPTLRPC_FLVR_INVALID) {
1069                         cli->cl_flvr_mgc = flvr;
1070                 } else if (memcmp(&cli->cl_flvr_mgc, &flvr,
1071                                   sizeof(flvr)) != 0) {
1072                         char    str[20];
1073
1074                         sptlrpc_flavor2name(&cli->cl_flvr_mgc,
1075                                             str, sizeof(str));
1076                         LCONSOLE_ERROR("asking sptlrpc flavor %s to MGS but "
1077                                        "currently %s is in use\n",
1078                                        (char *) val, str);
1079                         rc = -EPERM;
1080                 }
1081                 return rc;
1082         }
1083
1084         return rc;
1085 }
1086
1087 static int mgc_get_info(const struct lu_env *env, struct obd_export *exp,
1088                         __u32 keylen, void *key, __u32 *vallen, void *val,
1089                         struct lov_stripe_md *unused)
1090 {
1091         int rc = -EINVAL;
1092
1093         if (KEY_IS(KEY_CONN_DATA)) {
1094                 struct obd_import *imp = class_exp2cliimp(exp);
1095                 struct obd_connect_data *data = val;
1096
1097                 if (*vallen == sizeof(*data)) {
1098                         *data = imp->imp_connect_data;
1099                         rc = 0;
1100                 }
1101         }
1102
1103         return rc;
1104 }
1105
1106 static int mgc_import_event(struct obd_device *obd,
1107                             struct obd_import *imp,
1108                             enum obd_import_event event)
1109 {
1110         int rc = 0;
1111
1112         LASSERT(imp->imp_obd == obd);
1113         CDEBUG(D_MGC, "import event %#x\n", event);
1114
1115         switch (event) {
1116         case IMP_EVENT_DISCON:
1117                 /* MGC imports should not wait for recovery */
1118                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1119                         ptlrpc_pinger_ir_down();
1120                 break;
1121         case IMP_EVENT_INACTIVE:
1122                 break;
1123         case IMP_EVENT_INVALIDATE: {
1124                 struct ldlm_namespace *ns = obd->obd_namespace;
1125                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
1126                 break;
1127         }
1128         case IMP_EVENT_ACTIVE:
1129                 CDEBUG(D_INFO, "%s: Reactivating import\n", obd->obd_name);
1130                 /* Clearing obd_no_recov allows us to continue pinging */
1131                 obd->obd_no_recov = 0;
1132                 mgc_notify_active(obd);
1133                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1134                         ptlrpc_pinger_ir_up();
1135                 break;
1136         case IMP_EVENT_OCD:
1137                 break;
1138         case IMP_EVENT_DEACTIVATE:
1139         case IMP_EVENT_ACTIVATE:
1140                 break;
1141         default:
1142                 CERROR("Unknown import event %#x\n", event);
1143                 LBUG();
1144         }
1145         return rc;
1146 }
1147
1148 static int mgc_llog_init(struct obd_device *obd, struct obd_llog_group *olg,
1149                          struct obd_device *tgt, int *index)
1150 {
1151         struct llog_ctxt *ctxt;
1152         int rc;
1153
1154         LASSERT(olg == &obd->obd_olg);
1155
1156
1157         rc = llog_setup(NULL, obd, olg, LLOG_CONFIG_REPL_CTXT, tgt,
1158                         &llog_client_ops);
1159         if (rc)
1160                 GOTO(out, rc);
1161
1162         ctxt = llog_group_get_ctxt(olg, LLOG_CONFIG_REPL_CTXT);
1163         if (!ctxt)
1164                 GOTO(out, rc = -ENODEV);
1165
1166         llog_initiator_connect(ctxt);
1167         llog_ctxt_put(ctxt);
1168
1169         return 0;
1170 out:
1171         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
1172         if (ctxt)
1173                 llog_cleanup(NULL, ctxt);
1174         return rc;
1175 }
1176
1177 static int mgc_llog_finish(struct obd_device *obd, int count)
1178 {
1179         struct llog_ctxt *ctxt;
1180
1181         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
1182         if (ctxt)
1183                 llog_cleanup(NULL, ctxt);
1184
1185         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
1186         if (ctxt)
1187                 llog_cleanup(NULL, ctxt);
1188         return 0;
1189 }
1190
1191 enum {
1192         CONFIG_READ_NRPAGES_INIT = 1 << (20 - PAGE_CACHE_SHIFT),
1193         CONFIG_READ_NRPAGES      = 4
1194 };
1195
1196 static int mgc_apply_recover_logs(struct obd_device *mgc,
1197                                   struct config_llog_data *cld,
1198                                   __u64 max_version,
1199                                   void *data, int datalen, bool mne_swab)
1200 {
1201         struct config_llog_instance *cfg = &cld->cld_cfg;
1202         struct lustre_sb_info       *lsi = s2lsi(cfg->cfg_sb);
1203         struct mgs_nidtbl_entry *entry;
1204         struct lustre_cfg       *lcfg;
1205         struct lustre_cfg_bufs   bufs;
1206         u64   prev_version = 0;
1207         char *inst;
1208         char *buf;
1209         int   bufsz;
1210         int   pos;
1211         int   rc  = 0;
1212         int   off = 0;
1213
1214         LASSERT(cfg->cfg_instance != NULL);
1215         LASSERT(cfg->cfg_sb == cfg->cfg_instance);
1216
1217         OBD_ALLOC(inst, PAGE_CACHE_SIZE);
1218         if (inst == NULL)
1219                 return -ENOMEM;
1220
1221         if (!IS_SERVER(lsi)) {
1222                 pos = snprintf(inst, PAGE_CACHE_SIZE, "%p", cfg->cfg_instance);
1223                 if (pos >= PAGE_CACHE_SIZE) {
1224                         OBD_FREE(inst, PAGE_CACHE_SIZE);
1225                         return -E2BIG;
1226                 }
1227         } else {
1228                 LASSERT(IS_MDT(lsi));
1229                 rc = server_name2svname(lsi->lsi_svname, inst, NULL,
1230                                         PAGE_CACHE_SIZE);
1231                 if (rc) {
1232                         OBD_FREE(inst, PAGE_CACHE_SIZE);
1233                         return -EINVAL;
1234                 }
1235                 pos = strlen(inst);
1236         }
1237
1238         ++pos;
1239         buf   = inst + pos;
1240         bufsz = PAGE_CACHE_SIZE - pos;
1241
1242         while (datalen > 0) {
1243                 int   entry_len = sizeof(*entry);
1244                 int   is_ost;
1245                 struct obd_device *obd;
1246                 char *obdname;
1247                 char *cname;
1248                 char *params;
1249                 char *uuid;
1250
1251                 rc = -EINVAL;
1252                 if (datalen < sizeof(*entry))
1253                         break;
1254
1255                 entry = (typeof(entry))(data + off);
1256
1257                 /* sanity check */
1258                 if (entry->mne_nid_type != 0) /* only support type 0 for ipv4 */
1259                         break;
1260                 if (entry->mne_nid_count == 0) /* at least one nid entry */
1261                         break;
1262                 if (entry->mne_nid_size != sizeof(lnet_nid_t))
1263                         break;
1264
1265                 entry_len += entry->mne_nid_count * entry->mne_nid_size;
1266                 if (datalen < entry_len) /* must have entry_len at least */
1267                         break;
1268
1269                 /* Keep this swab for normal mixed endian handling. LU-1644 */
1270                 if (mne_swab)
1271                         lustre_swab_mgs_nidtbl_entry(entry);
1272                 if (entry->mne_length > PAGE_CACHE_SIZE) {
1273                         CERROR("MNE too large (%u)\n", entry->mne_length);
1274                         break;
1275                 }
1276
1277                 if (entry->mne_length < entry_len)
1278                         break;
1279
1280                 off     += entry->mne_length;
1281                 datalen -= entry->mne_length;
1282                 if (datalen < 0)
1283                         break;
1284
1285                 if (entry->mne_version > max_version) {
1286                         CERROR("entry index(%lld) is over max_index(%lld)\n",
1287                                entry->mne_version, max_version);
1288                         break;
1289                 }
1290
1291                 if (prev_version >= entry->mne_version) {
1292                         CERROR("index unsorted, prev %lld, now %lld\n",
1293                                prev_version, entry->mne_version);
1294                         break;
1295                 }
1296                 prev_version = entry->mne_version;
1297
1298                 /*
1299                  * Write a string with format "nid::instance" to
1300                  * lustre/<osc|mdc>/<target>-<osc|mdc>-<instance>/import.
1301                  */
1302
1303                 is_ost = entry->mne_type == LDD_F_SV_TYPE_OST;
1304                 memset(buf, 0, bufsz);
1305                 obdname = buf;
1306                 pos = 0;
1307
1308                 /* lustre-OST0001-osc-<instance #> */
1309                 strcpy(obdname, cld->cld_logname);
1310                 cname = strrchr(obdname, '-');
1311                 if (cname == NULL) {
1312                         CERROR("mgc %s: invalid logname %s\n",
1313                                mgc->obd_name, obdname);
1314                         break;
1315                 }
1316
1317                 pos = cname - obdname;
1318                 obdname[pos] = 0;
1319                 pos += sprintf(obdname + pos, "-%s%04x",
1320                                   is_ost ? "OST" : "MDT", entry->mne_index);
1321
1322                 cname = is_ost ? "osc" : "mdc",
1323                 pos += sprintf(obdname + pos, "-%s-%s", cname, inst);
1324                 lustre_cfg_bufs_reset(&bufs, obdname);
1325
1326                 /* find the obd by obdname */
1327                 obd = class_name2obd(obdname);
1328                 if (obd == NULL) {
1329                         CDEBUG(D_INFO, "mgc %s: cannot find obdname %s\n",
1330                                mgc->obd_name, obdname);
1331                         rc = 0;
1332                         /* this is a safe race, when the ost is starting up...*/
1333                         continue;
1334                 }
1335
1336                 /* osc.import = "connection=<Conn UUID>::<target instance>" */
1337                 ++pos;
1338                 params = buf + pos;
1339                 pos += sprintf(params, "%s.import=%s", cname, "connection=");
1340                 uuid = buf + pos;
1341
1342                 down_read(&obd->u.cli.cl_sem);
1343                 if (obd->u.cli.cl_import == NULL) {
1344                         /* client does not connect to the OST yet */
1345                         up_read(&obd->u.cli.cl_sem);
1346                         rc = 0;
1347                         continue;
1348                 }
1349
1350                 /* TODO: iterate all nids to find one */
1351                 /* find uuid by nid */
1352                 rc = client_import_find_conn(obd->u.cli.cl_import,
1353                                              entry->u.nids[0],
1354                                              (struct obd_uuid *)uuid);
1355                 up_read(&obd->u.cli.cl_sem);
1356                 if (rc < 0) {
1357                         CERROR("mgc: cannot find uuid by nid %s\n",
1358                                libcfs_nid2str(entry->u.nids[0]));
1359                         break;
1360                 }
1361
1362                 CDEBUG(D_INFO, "Find uuid %s by nid %s\n",
1363                        uuid, libcfs_nid2str(entry->u.nids[0]));
1364
1365                 pos += strlen(uuid);
1366                 pos += sprintf(buf + pos, "::%u", entry->mne_instance);
1367                 LASSERT(pos < bufsz);
1368
1369                 lustre_cfg_bufs_set_string(&bufs, 1, params);
1370
1371                 rc = -ENOMEM;
1372                 lcfg = lustre_cfg_new(LCFG_PARAM, &bufs);
1373                 if (lcfg == NULL) {
1374                         CERROR("mgc: cannot allocate memory\n");
1375                         break;
1376                 }
1377
1378                 CDEBUG(D_INFO, "ir apply logs "LPD64"/"LPD64" for %s -> %s\n",
1379                        prev_version, max_version, obdname, params);
1380
1381                 rc = class_process_config(lcfg);
1382                 lustre_cfg_free(lcfg);
1383                 if (rc)
1384                         CDEBUG(D_INFO, "process config for %s error %d\n",
1385                                obdname, rc);
1386
1387                 /* continue, even one with error */
1388         }
1389
1390         OBD_FREE(inst, PAGE_CACHE_SIZE);
1391         return rc;
1392 }
1393
1394 /**
1395  * This function is called if this client was notified for target restarting
1396  * by the MGS. A CONFIG_READ RPC is going to send to fetch recovery logs.
1397  */
1398 static int mgc_process_recover_log(struct obd_device *obd,
1399                                    struct config_llog_data *cld)
1400 {
1401         struct ptlrpc_request *req = NULL;
1402         struct config_llog_instance *cfg = &cld->cld_cfg;
1403         struct mgs_config_body *body;
1404         struct mgs_config_res  *res;
1405         struct ptlrpc_bulk_desc *desc;
1406         struct page **pages;
1407         int nrpages;
1408         bool eof = true;
1409         bool mne_swab = false;
1410         int i;
1411         int ealen;
1412         int rc;
1413
1414         /* allocate buffer for bulk transfer.
1415          * if this is the first time for this mgs to read logs,
1416          * CONFIG_READ_NRPAGES_INIT will be used since it will read all logs
1417          * once; otherwise, it only reads increment of logs, this should be
1418          * small and CONFIG_READ_NRPAGES will be used.
1419          */
1420         nrpages = CONFIG_READ_NRPAGES;
1421         if (cfg->cfg_last_idx == 0) /* the first time */
1422                 nrpages = CONFIG_READ_NRPAGES_INIT;
1423
1424         OBD_ALLOC(pages, sizeof(*pages) * nrpages);
1425         if (pages == NULL)
1426                 GOTO(out, rc = -ENOMEM);
1427
1428         for (i = 0; i < nrpages; i++) {
1429                 pages[i] = alloc_page(GFP_IOFS);
1430                 if (pages[i] == NULL)
1431                         GOTO(out, rc = -ENOMEM);
1432         }
1433
1434 again:
1435         LASSERT(cld_is_recover(cld));
1436         LASSERT(mutex_is_locked(&cld->cld_lock));
1437         req = ptlrpc_request_alloc(class_exp2cliimp(cld->cld_mgcexp),
1438                                    &RQF_MGS_CONFIG_READ);
1439         if (req == NULL)
1440                 GOTO(out, rc = -ENOMEM);
1441
1442         rc = ptlrpc_request_pack(req, LUSTRE_MGS_VERSION, MGS_CONFIG_READ);
1443         if (rc)
1444                 GOTO(out, rc);
1445
1446         /* pack request */
1447         body = req_capsule_client_get(&req->rq_pill, &RMF_MGS_CONFIG_BODY);
1448         LASSERT(body != NULL);
1449         LASSERT(sizeof(body->mcb_name) > strlen(cld->cld_logname));
1450         if (strlcpy(body->mcb_name, cld->cld_logname, sizeof(body->mcb_name))
1451             >= sizeof(body->mcb_name))
1452                 GOTO(out, rc = -E2BIG);
1453         body->mcb_offset = cfg->cfg_last_idx + 1;
1454         body->mcb_type   = cld->cld_type;
1455         body->mcb_bits   = PAGE_CACHE_SHIFT;
1456         body->mcb_units  = nrpages;
1457
1458         /* allocate bulk transfer descriptor */
1459         desc = ptlrpc_prep_bulk_imp(req, nrpages, 1, BULK_PUT_SINK,
1460                                     MGS_BULK_PORTAL);
1461         if (desc == NULL)
1462                 GOTO(out, rc = -ENOMEM);
1463
1464         for (i = 0; i < nrpages; i++)
1465                 ptlrpc_prep_bulk_page_pin(desc, pages[i], 0, PAGE_CACHE_SIZE);
1466
1467         ptlrpc_request_set_replen(req);
1468         rc = ptlrpc_queue_wait(req);
1469         if (rc)
1470                 GOTO(out, rc);
1471
1472         res = req_capsule_server_get(&req->rq_pill, &RMF_MGS_CONFIG_RES);
1473         if (res->mcr_size < res->mcr_offset)
1474                 GOTO(out, rc = -EINVAL);
1475
1476         /* always update the index even though it might have errors with
1477          * handling the recover logs */
1478         cfg->cfg_last_idx = res->mcr_offset;
1479         eof = res->mcr_offset == res->mcr_size;
1480
1481         CDEBUG(D_INFO, "Latest version "LPD64", more %d.\n",
1482                res->mcr_offset, eof == false);
1483
1484         ealen = sptlrpc_cli_unwrap_bulk_read(req, req->rq_bulk, 0);
1485         if (ealen < 0)
1486                 GOTO(out, rc = ealen);
1487
1488         if (ealen > nrpages << PAGE_CACHE_SHIFT)
1489                 GOTO(out, rc = -EINVAL);
1490
1491         if (ealen == 0) { /* no logs transferred */
1492                 if (!eof)
1493                         rc = -EINVAL;
1494                 GOTO(out, rc);
1495         }
1496
1497         mne_swab = !!ptlrpc_rep_need_swab(req);
1498 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 50, 0)
1499         /* This import flag means the server did an extra swab of IR MNE
1500          * records (fixed in LU-1252), reverse it here if needed. LU-1644 */
1501         if (unlikely(req->rq_import->imp_need_mne_swab))
1502                 mne_swab = !mne_swab;
1503 #else
1504 #warning "LU-1644: Remove old OBD_CONNECT_MNE_SWAB fixup and imp_need_mne_swab"
1505 #endif
1506
1507         for (i = 0; i < nrpages && ealen > 0; i++) {
1508                 int rc2;
1509                 void *ptr;
1510
1511                 ptr = kmap(pages[i]);
1512                 rc2 = mgc_apply_recover_logs(obd, cld, res->mcr_offset, ptr,
1513                                              min_t(int, ealen, PAGE_CACHE_SIZE),
1514                                              mne_swab);
1515                 kunmap(pages[i]);
1516                 if (rc2 < 0) {
1517                         CWARN("Process recover log %s error %d\n",
1518                               cld->cld_logname, rc2);
1519                         break;
1520                 }
1521
1522                 ealen -= PAGE_CACHE_SIZE;
1523         }
1524
1525 out:
1526         if (req)
1527                 ptlrpc_req_finished(req);
1528
1529         if (rc == 0 && !eof)
1530                 goto again;
1531
1532         if (pages) {
1533                 for (i = 0; i < nrpages; i++) {
1534                         if (pages[i] == NULL)
1535                                 break;
1536                         __free_page(pages[i]);
1537                 }
1538                 OBD_FREE(pages, sizeof(*pages) * nrpages);
1539         }
1540         return rc;
1541 }
1542
1543
1544 /* local_only means it cannot get remote llogs */
1545 static int mgc_process_cfg_log(struct obd_device *mgc,
1546                                struct config_llog_data *cld,
1547                                int local_only)
1548 {
1549         struct llog_ctxt *ctxt, *lctxt = NULL;
1550         struct lvfs_run_ctxt *saved_ctxt;
1551         struct lustre_sb_info *lsi = NULL;
1552         int rc = 0, must_pop = 0;
1553         bool sptlrpc_started = false;
1554
1555         LASSERT(cld);
1556         LASSERT(mutex_is_locked(&cld->cld_lock));
1557
1558         /*
1559          * local copy of sptlrpc log is controlled elsewhere, don't try to
1560          * read it up here.
1561          */
1562         if (cld_is_sptlrpc(cld) && local_only)
1563                 return 0;
1564
1565         if (cld->cld_cfg.cfg_sb)
1566                 lsi = s2lsi(cld->cld_cfg.cfg_sb);
1567
1568         ctxt = llog_get_context(mgc, LLOG_CONFIG_REPL_CTXT);
1569         if (!ctxt) {
1570                 CERROR("missing llog context\n");
1571                 return -EINVAL;
1572         }
1573
1574         OBD_ALLOC_PTR(saved_ctxt);
1575         if (saved_ctxt == NULL)
1576                 return -ENOMEM;
1577
1578         lctxt = llog_get_context(mgc, LLOG_CONFIG_ORIG_CTXT);
1579
1580                 if (local_only) { /* no local log at client side */
1581                 GOTO(out_pop, rc = -EIO);
1582         }
1583
1584         if (cld_is_sptlrpc(cld)) {
1585                 sptlrpc_conf_log_update_begin(cld->cld_logname);
1586                 sptlrpc_started = true;
1587         }
1588
1589         /* logname and instance info should be the same, so use our
1590            copy of the instance for the update.  The cfg_last_idx will
1591            be updated here. */
1592         rc = class_config_parse_llog(NULL, ctxt, cld->cld_logname,
1593                                      &cld->cld_cfg);
1594
1595 out_pop:
1596         llog_ctxt_put(ctxt);
1597         if (lctxt)
1598                 llog_ctxt_put(lctxt);
1599         if (must_pop)
1600                 pop_ctxt(saved_ctxt, &mgc->obd_lvfs_ctxt, NULL);
1601
1602         OBD_FREE_PTR(saved_ctxt);
1603         /*
1604          * update settings on existing OBDs. doing it inside
1605          * of llog_process_lock so no device is attaching/detaching
1606          * in parallel.
1607          * the logname must be <fsname>-sptlrpc
1608          */
1609         if (sptlrpc_started) {
1610                 LASSERT(cld_is_sptlrpc(cld));
1611                 sptlrpc_conf_log_update_end(cld->cld_logname);
1612                 class_notify_sptlrpc_conf(cld->cld_logname,
1613                                           strlen(cld->cld_logname) -
1614                                           strlen("-sptlrpc"));
1615         }
1616
1617         return rc;
1618 }
1619
1620 /** Get a config log from the MGS and process it.
1621  * This func is called for both clients and servers.
1622  * Copy the log locally before parsing it if appropriate (non-MGS server)
1623  */
1624 int mgc_process_log(struct obd_device *mgc, struct config_llog_data *cld)
1625 {
1626         struct lustre_handle lockh = { 0 };
1627         __u64 flags = LDLM_FL_NO_LRU;
1628         int rc = 0, rcl;
1629
1630         LASSERT(cld);
1631
1632         /* I don't want multiple processes running process_log at once --
1633            sounds like badness.  It actually might be fine, as long as
1634            we're not trying to update from the same log
1635            simultaneously (in which case we should use a per-log sem.) */
1636         mutex_lock(&cld->cld_lock);
1637         if (cld->cld_stopping) {
1638                 mutex_unlock(&cld->cld_lock);
1639                 return 0;
1640         }
1641
1642         OBD_FAIL_TIMEOUT(OBD_FAIL_MGC_PAUSE_PROCESS_LOG, 20);
1643
1644         CDEBUG(D_MGC, "Process log %s:%p from %d\n", cld->cld_logname,
1645                cld->cld_cfg.cfg_instance, cld->cld_cfg.cfg_last_idx + 1);
1646
1647         /* Get the cfg lock on the llog */
1648         rcl = mgc_enqueue(mgc->u.cli.cl_mgc_mgsexp, NULL, LDLM_PLAIN, NULL,
1649                           LCK_CR, &flags, NULL, NULL, NULL,
1650                           cld, 0, NULL, &lockh);
1651         if (rcl == 0) {
1652                 /* Get the cld, it will be released in mgc_blocking_ast. */
1653                 config_log_get(cld);
1654                 rc = ldlm_lock_set_data(&lockh, (void *)cld);
1655                 LASSERT(rc == 0);
1656         } else {
1657                 CDEBUG(D_MGC, "Can't get cfg lock: %d\n", rcl);
1658
1659                 /* mark cld_lostlock so that it will requeue
1660                  * after MGC becomes available. */
1661                 cld->cld_lostlock = 1;
1662                 /* Get extra reference, it will be put in requeue thread */
1663                 config_log_get(cld);
1664         }
1665
1666
1667         if (cld_is_recover(cld)) {
1668                 rc = 0; /* this is not a fatal error for recover log */
1669                 if (rcl == 0)
1670                         rc = mgc_process_recover_log(mgc, cld);
1671         } else {
1672                 rc = mgc_process_cfg_log(mgc, cld, rcl != 0);
1673         }
1674
1675         CDEBUG(D_MGC, "%s: configuration from log '%s' %sed (%d).\n",
1676                mgc->obd_name, cld->cld_logname, rc ? "fail" : "succeed", rc);
1677
1678         mutex_unlock(&cld->cld_lock);
1679
1680         /* Now drop the lock so MGS can revoke it */
1681         if (!rcl) {
1682                 rcl = mgc_cancel(mgc->u.cli.cl_mgc_mgsexp, NULL,
1683                                  LCK_CR, &lockh);
1684                 if (rcl)
1685                         CERROR("Can't drop cfg lock: %d\n", rcl);
1686         }
1687
1688         return rc;
1689 }
1690
1691
1692 /** Called from lustre_process_log.
1693  * LCFG_LOG_START gets the config log from the MGS, processes it to start
1694  * any services, and adds it to the list logs to watch (follow).
1695  */
1696 static int mgc_process_config(struct obd_device *obd, obd_count len, void *buf)
1697 {
1698         struct lustre_cfg *lcfg = buf;
1699         struct config_llog_instance *cfg = NULL;
1700         char *logname;
1701         int rc = 0;
1702
1703         switch(lcfg->lcfg_command) {
1704         case LCFG_LOV_ADD_OBD: {
1705                 /* Overloading this cfg command: register a new target */
1706                 struct mgs_target_info *mti;
1707
1708                 if (LUSTRE_CFG_BUFLEN(lcfg, 1) !=
1709                     sizeof(struct mgs_target_info))
1710                         GOTO(out, rc = -EINVAL);
1711
1712                 mti = (struct mgs_target_info *)lustre_cfg_buf(lcfg, 1);
1713                 CDEBUG(D_MGC, "add_target %s %#x\n",
1714                        mti->mti_svname, mti->mti_flags);
1715                 rc = mgc_target_register(obd->u.cli.cl_mgc_mgsexp, mti);
1716                 break;
1717         }
1718         case LCFG_LOV_DEL_OBD:
1719                 /* Unregister has no meaning at the moment. */
1720                 CERROR("lov_del_obd unimplemented\n");
1721                 rc = -ENOSYS;
1722                 break;
1723         case LCFG_SPTLRPC_CONF: {
1724                 rc = sptlrpc_process_config(lcfg);
1725                 break;
1726         }
1727         case LCFG_LOG_START: {
1728                 struct config_llog_data *cld;
1729                 struct super_block *sb;
1730
1731                 logname = lustre_cfg_string(lcfg, 1);
1732                 cfg = (struct config_llog_instance *)lustre_cfg_buf(lcfg, 2);
1733                 sb = *(struct super_block **)lustre_cfg_buf(lcfg, 3);
1734
1735                 CDEBUG(D_MGC, "parse_log %s from %d\n", logname,
1736                        cfg->cfg_last_idx);
1737
1738                 /* We're only called through here on the initial mount */
1739                 rc = config_log_add(obd, logname, cfg, sb);
1740                 if (rc)
1741                         break;
1742                 cld = config_log_find(logname, cfg);
1743                 if (cld == NULL) {
1744                         rc = -ENOENT;
1745                         break;
1746                 }
1747
1748                 /* COMPAT_146 */
1749                 /* FIXME only set this for old logs!  Right now this forces
1750                    us to always skip the "inside markers" check */
1751                 cld->cld_cfg.cfg_flags |= CFG_F_COMPAT146;
1752
1753                 rc = mgc_process_log(obd, cld);
1754                 if (rc == 0 && cld->cld_recover != NULL) {
1755                         if (OCD_HAS_FLAG(&obd->u.cli.cl_import->
1756                                          imp_connect_data, IMP_RECOV)) {
1757                                 rc = mgc_process_log(obd, cld->cld_recover);
1758                         } else {
1759                                 struct config_llog_data *cir = cld->cld_recover;
1760                                 cld->cld_recover = NULL;
1761                                 config_log_put(cir);
1762                         }
1763                         if (rc)
1764                                 CERROR("Cannot process recover llog %d\n", rc);
1765                 }
1766                 config_log_put(cld);
1767
1768                 break;
1769         }
1770         case LCFG_LOG_END: {
1771                 logname = lustre_cfg_string(lcfg, 1);
1772
1773                 if (lcfg->lcfg_bufcount >= 2)
1774                         cfg = (struct config_llog_instance *)lustre_cfg_buf(
1775                                 lcfg, 2);
1776                 rc = config_log_end(logname, cfg);
1777                 break;
1778         }
1779         default: {
1780                 CERROR("Unknown command: %d\n", lcfg->lcfg_command);
1781                 GOTO(out, rc = -EINVAL);
1782
1783         }
1784         }
1785 out:
1786         return rc;
1787 }
1788
1789 struct obd_ops mgc_obd_ops = {
1790         .o_owner        = THIS_MODULE,
1791         .o_setup        = mgc_setup,
1792         .o_precleanup   = mgc_precleanup,
1793         .o_cleanup      = mgc_cleanup,
1794         .o_add_conn     = client_import_add_conn,
1795         .o_del_conn     = client_import_del_conn,
1796         .o_connect      = client_connect_import,
1797         .o_disconnect   = client_disconnect_export,
1798         //.o_enqueue      = mgc_enqueue,
1799         .o_cancel       = mgc_cancel,
1800         //.o_iocontrol    = mgc_iocontrol,
1801         .o_set_info_async = mgc_set_info_async,
1802         .o_get_info       = mgc_get_info,
1803         .o_import_event = mgc_import_event,
1804         .o_llog_init    = mgc_llog_init,
1805         .o_llog_finish  = mgc_llog_finish,
1806         .o_process_config = mgc_process_config,
1807 };
1808
1809 int __init mgc_init(void)
1810 {
1811         return class_register_type(&mgc_obd_ops, NULL, NULL,
1812                                    LUSTRE_MGC_NAME, NULL);
1813 }
1814
1815 static void /*__exit*/ mgc_exit(void)
1816 {
1817         class_unregister_type(LUSTRE_MGC_NAME);
1818 }
1819
1820 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
1821 MODULE_DESCRIPTION("Lustre Management Client");
1822 MODULE_LICENSE("GPL");
1823
1824 module_init(mgc_init);
1825 module_exit(mgc_exit);