Whamcloud - gitweb
LU-8408 mgc: handle config_llog_data::cld_refcount properly
[fs/lustre-release.git] / 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, 2015, 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/kthread.h>
46
47 #include <dt_object.h>
48 #include <lprocfs_status.h>
49 #include <lustre_dlm.h>
50 #include <lustre_disk.h>
51 #include <lustre_log.h>
52 #include <lustre_nodemap.h>
53 #include <lustre_swab.h>
54 #include <obd_class.h>
55
56 #include "mgc_internal.h"
57
58 static int mgc_name2resid(char *name, int len, struct ldlm_res_id *res_id,
59                           int type)
60 {
61         __u64 resname = 0;
62
63         if (len > sizeof(resname)) {
64                 CERROR("name too long: %s\n", name);
65                 return -EINVAL;
66         }
67         if (len <= 0) {
68                 CERROR("missing name: %s\n", name);
69                 return -EINVAL;
70         }
71         memcpy(&resname, name, len);
72
73         /* Always use the same endianness for the resid */
74         memset(res_id, 0, sizeof(*res_id));
75         res_id->name[0] = cpu_to_le64(resname);
76         /* XXX: unfortunately, sptlprc and config llog share one lock */
77         switch(type) {
78         case CONFIG_T_CONFIG:
79         case CONFIG_T_SPTLRPC:
80                 resname = 0;
81                 break;
82         case CONFIG_T_RECOVER:
83         case CONFIG_T_PARAMS:
84         case CONFIG_T_NODEMAP:
85                 resname = type;
86                 break;
87         default:
88                 LBUG();
89         }
90         res_id->name[1] = cpu_to_le64(resname);
91         CDEBUG(D_MGC, "log %s to resid %#llx/%#llx (%.8s)\n", name,
92                res_id->name[0], res_id->name[1], (char *)&res_id->name[0]);
93         return 0;
94 }
95
96 int mgc_fsname2resid(char *fsname, struct ldlm_res_id *res_id, int type)
97 {
98         /* fsname is at most 8 chars long, maybe contain "-".
99          * e.g. "lustre", "SUN-000" */
100         return mgc_name2resid(fsname, strlen(fsname), res_id, type);
101 }
102 EXPORT_SYMBOL(mgc_fsname2resid);
103
104 static int mgc_logname2resid(char *logname, struct ldlm_res_id *res_id,
105                              int type)
106 {
107         char *name_end;
108         int len;
109
110         /* logname consists of "fsname-nodetype".
111          * e.g. "lustre-MDT0001", "SUN-000-client"
112          * there is an exception: llog "params" */
113         name_end = strrchr(logname, '-');
114         if (!name_end)
115                 len = strlen(logname);
116         else
117                 len = name_end - logname;
118         return mgc_name2resid(logname, len, res_id, type);
119 }
120
121 /********************** config llog list **********************/
122 static struct list_head config_llog_list = LIST_HEAD_INIT(config_llog_list);
123 static DEFINE_SPINLOCK(config_list_lock);
124
125 /* Take a reference to a config log */
126 static int config_log_get(struct config_llog_data *cld)
127 {
128         ENTRY;
129         atomic_inc(&cld->cld_refcount);
130         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
131                 atomic_read(&cld->cld_refcount));
132         RETURN(0);
133 }
134
135 /* Drop a reference to a config log.  When no longer referenced,
136    we can free the config log data */
137 static void config_log_put(struct config_llog_data *cld)
138 {
139         ENTRY;
140
141         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
142                 atomic_read(&cld->cld_refcount));
143         LASSERT(atomic_read(&cld->cld_refcount) > 0);
144
145         /* spinlock to make sure no item with 0 refcount in the list */
146         if (atomic_dec_and_lock(&cld->cld_refcount, &config_list_lock)) {
147                 list_del(&cld->cld_list_chain);
148                 spin_unlock(&config_list_lock);
149
150                 CDEBUG(D_MGC, "dropping config log %s\n", cld->cld_logname);
151
152                 if (cld->cld_recover)
153                         config_log_put(cld->cld_recover);
154                 if (cld->cld_params)
155                         config_log_put(cld->cld_params);
156                 if (cld->cld_nodemap)
157                         config_log_put(cld->cld_nodemap);
158                 if (cld->cld_sptlrpc)
159                         config_log_put(cld->cld_sptlrpc);
160                 if (cld_is_sptlrpc(cld))
161                         sptlrpc_conf_log_stop(cld->cld_logname);
162
163                 class_export_put(cld->cld_mgcexp);
164                 OBD_FREE(cld, sizeof(*cld) + strlen(cld->cld_logname) + 1);
165         }
166
167         EXIT;
168 }
169
170 /* Find a config log by name */
171 static
172 struct config_llog_data *config_log_find(char *logname,
173                                          struct config_llog_instance *cfg)
174 {
175         struct config_llog_data *cld;
176         struct config_llog_data *found = NULL;
177         void *                   instance;
178         ENTRY;
179
180         LASSERT(logname != NULL);
181
182         instance = cfg ? cfg->cfg_instance : NULL;
183         spin_lock(&config_list_lock);
184         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
185                 /* check if instance equals */
186                 if (instance != cld->cld_cfg.cfg_instance)
187                         continue;
188
189                 /* instance may be NULL, should check name */
190                 if (strcmp(logname, cld->cld_logname) == 0) {
191                         found = cld;
192                         config_log_get(found);
193                         break;
194                 }
195         }
196         spin_unlock(&config_list_lock);
197         RETURN(found);
198 }
199
200 static
201 struct config_llog_data *do_config_log_add(struct obd_device *obd,
202                                            char *logname,
203                                            int type,
204                                            struct config_llog_instance *cfg,
205                                            struct super_block *sb)
206 {
207         struct config_llog_data *cld;
208         int rc;
209
210         ENTRY;
211
212         CDEBUG(D_MGC, "do adding config log %s:%p\n", logname,
213                cfg ? cfg->cfg_instance : NULL);
214
215         OBD_ALLOC(cld, sizeof(*cld) + strlen(logname) + 1);
216         if (!cld)
217                 RETURN(ERR_PTR(-ENOMEM));
218
219         rc = mgc_logname2resid(logname, &cld->cld_resid, type);
220         if (rc) {
221                 OBD_FREE(cld, sizeof(*cld) + strlen(cld->cld_logname) + 1);
222                 RETURN(ERR_PTR(rc));
223         }
224
225         strcpy(cld->cld_logname, logname);
226         if (cfg)
227                 cld->cld_cfg = *cfg;
228         else
229                 cld->cld_cfg.cfg_callback = class_config_llog_handler;
230         mutex_init(&cld->cld_lock);
231         cld->cld_cfg.cfg_last_idx = 0;
232         cld->cld_cfg.cfg_flags = 0;
233         cld->cld_cfg.cfg_sb = sb;
234         cld->cld_type = type;
235         atomic_set(&cld->cld_refcount, 1);
236
237         /* Keep the mgc around until we are done */
238         cld->cld_mgcexp = class_export_get(obd->obd_self_export);
239
240         if (cld_is_sptlrpc(cld)) {
241                 sptlrpc_conf_log_start(logname);
242                 cld->cld_cfg.cfg_obdname = obd->obd_name;
243         }
244
245         spin_lock(&config_list_lock);
246         list_add(&cld->cld_list_chain, &config_llog_list);
247         spin_unlock(&config_list_lock);
248
249         if (cld_is_sptlrpc(cld) || cld_is_nodemap(cld)) {
250                 rc = mgc_process_log(obd, cld);
251                 if (rc && rc != -ENOENT)
252                         CERROR("%s: failed processing log, type %d: rc = %d\n",
253                                obd->obd_name, type, rc);
254         }
255
256         RETURN(cld);
257 }
258
259 static struct config_llog_data *config_recover_log_add(struct obd_device *obd,
260         char *fsname,
261         struct config_llog_instance *cfg,
262         struct super_block *sb)
263 {
264         struct config_llog_instance lcfg = *cfg;
265         struct lustre_sb_info *lsi = s2lsi(sb);
266         struct config_llog_data *cld;
267         char logname[32];
268
269         if (IS_OST(lsi))
270                 return NULL;
271
272         /* for osp-on-ost, see lustre_start_osp() */
273         if (IS_MDT(lsi) && lcfg.cfg_instance)
274                 return NULL;
275
276         /* we have to use different llog for clients and mdts for cmd
277          * where only clients are notified if one of cmd server restarts */
278         LASSERT(strlen(fsname) < sizeof(logname) / 2);
279         strcpy(logname, fsname);
280         if (IS_SERVER(lsi)) { /* mdt */
281                 LASSERT(lcfg.cfg_instance == NULL);
282                 lcfg.cfg_instance = sb;
283                 strcat(logname, "-mdtir");
284         } else {
285                 LASSERT(lcfg.cfg_instance != NULL);
286                 strcat(logname, "-cliir");
287         }
288
289         cld = do_config_log_add(obd, logname, CONFIG_T_RECOVER, &lcfg, sb);
290         return cld;
291 }
292
293 static struct config_llog_data *config_params_log_add(struct obd_device *obd,
294         struct config_llog_instance *cfg, struct super_block *sb)
295 {
296         struct config_llog_instance     lcfg = *cfg;
297         struct config_llog_data         *cld;
298
299         lcfg.cfg_instance = sb;
300
301         cld = do_config_log_add(obd, PARAMS_FILENAME, CONFIG_T_PARAMS,
302                                 &lcfg, sb);
303
304         return cld;
305 }
306
307 /** Add this log to the list of active logs watched by an MGC.
308  * Active means we're watching for updates.
309  * We have one active log per "mount" - client instance or servername.
310  * Each instance may be at a different point in the log.
311  */
312 static struct config_llog_data *
313 config_log_add(struct obd_device *obd, char *logname,
314                struct config_llog_instance *cfg, struct super_block *sb)
315 {
316         struct lustre_sb_info *lsi = s2lsi(sb);
317         struct config_llog_data *cld;
318         struct config_llog_data *sptlrpc_cld;
319         struct config_llog_data *params_cld;
320         struct config_llog_data *nodemap_cld;
321         char seclogname[32];
322         char *ptr;
323         int rc;
324         bool locked = false;
325         ENTRY;
326
327         CDEBUG(D_MGC, "adding config log %s:%p\n", logname, cfg->cfg_instance);
328
329         /*
330          * for each regular log, the depended sptlrpc log name is
331          * <fsname>-sptlrpc. multiple regular logs may share one sptlrpc log.
332          */
333         ptr = strrchr(logname, '-');
334         if (ptr == NULL || ptr - logname > 8) {
335                 CERROR("logname %s is too long\n", logname);
336                 RETURN(ERR_PTR(-EINVAL));
337         }
338
339         memcpy(seclogname, logname, ptr - logname);
340         strcpy(seclogname + (ptr - logname), "-sptlrpc");
341
342         sptlrpc_cld = config_log_find(seclogname, NULL);
343         if (sptlrpc_cld == NULL) {
344                 sptlrpc_cld = do_config_log_add(obd, seclogname,
345                                                 CONFIG_T_SPTLRPC, NULL, NULL);
346                 if (IS_ERR(sptlrpc_cld)) {
347                         CERROR("can't create sptlrpc log: %s\n", seclogname);
348                         GOTO(out, rc = PTR_ERR(sptlrpc_cld));
349                 }
350         }
351
352         nodemap_cld = config_log_find(LUSTRE_NODEMAP_NAME, NULL);
353         if (!nodemap_cld && IS_SERVER(lsi) && !IS_MGS(lsi)) {
354                 nodemap_cld = do_config_log_add(obd, LUSTRE_NODEMAP_NAME,
355                                                 CONFIG_T_NODEMAP, NULL, NULL);
356                 if (IS_ERR(nodemap_cld)) {
357                         rc = PTR_ERR(nodemap_cld);
358                         CERROR("%s: cannot create nodemap log: rc = %d\n",
359                                obd->obd_name, rc);
360                         GOTO(out_sptlrpc, rc);
361                 }
362         }
363
364         params_cld = config_params_log_add(obd, cfg, sb);
365         if (IS_ERR(params_cld)) {
366                 rc = PTR_ERR(params_cld);
367                 CERROR("%s: can't create params log: rc = %d\n",
368                        obd->obd_name, rc);
369                 GOTO(out_nodemap, rc);
370         }
371
372         cld = do_config_log_add(obd, logname, CONFIG_T_CONFIG, cfg, sb);
373         if (IS_ERR(cld)) {
374                 CERROR("can't create log: %s\n", logname);
375                 GOTO(out_params, rc = PTR_ERR(cld));
376         }
377
378         LASSERT(lsi->lsi_lmd);
379         if (!(lsi->lsi_lmd->lmd_flags & LMD_FLG_NOIR)) {
380                 struct config_llog_data *recover_cld;
381
382                 ptr = strrchr(seclogname, '-');
383                 if (ptr != NULL) {
384                         *ptr = 0;
385                 } else {
386                         CERROR("%s: sptlrpc log name not correct, %s: "
387                                "rc = %d\n", obd->obd_name, seclogname, -EINVAL);
388                         GOTO(out_cld, rc = -EINVAL);
389                 }
390
391                 recover_cld = config_recover_log_add(obd, seclogname, cfg, sb);
392                 if (IS_ERR(recover_cld))
393                         GOTO(out_cld, rc = PTR_ERR(recover_cld));
394
395                 mutex_lock(&cld->cld_lock);
396                 locked = true;
397                 cld->cld_recover = recover_cld;
398         }
399
400         if (!locked)
401                 mutex_lock(&cld->cld_lock);
402         cld->cld_params = params_cld;
403         cld->cld_nodemap = nodemap_cld;
404         cld->cld_sptlrpc = sptlrpc_cld;
405         mutex_unlock(&cld->cld_lock);
406
407         RETURN(cld);
408
409 out_cld:
410         config_log_put(cld);
411
412 out_params:
413         config_log_put(params_cld);
414
415 out_nodemap:
416         config_log_put(nodemap_cld);
417
418 out_sptlrpc:
419         config_log_put(sptlrpc_cld);
420
421 out:
422         return ERR_PTR(rc);
423 }
424
425 DEFINE_MUTEX(llog_process_lock);
426
427 static inline void config_mark_cld_stop(struct config_llog_data *cld)
428 {
429         mutex_lock(&cld->cld_lock);
430         spin_lock(&config_list_lock);
431         cld->cld_stopping = 1;
432         spin_unlock(&config_list_lock);
433         mutex_unlock(&cld->cld_lock);
434 }
435
436 /** Stop watching for updates on this log.
437  */
438 static int config_log_end(char *logname, struct config_llog_instance *cfg)
439 {
440         struct config_llog_data *cld;
441         struct config_llog_data *cld_sptlrpc = NULL;
442         struct config_llog_data *cld_params = NULL;
443         struct config_llog_data *cld_recover = NULL;
444         struct config_llog_data *cld_nodemap = NULL;
445         int rc = 0;
446
447         ENTRY;
448
449         cld = config_log_find(logname, cfg);
450         if (cld == NULL)
451                 RETURN(-ENOENT);
452
453         mutex_lock(&cld->cld_lock);
454         /*
455          * if cld_stopping is set, it means we didn't start the log thus
456          * not owning the start ref. this can happen after previous umount:
457          * the cld still hanging there waiting for lock cancel, and we
458          * remount again but failed in the middle and call log_end without
459          * calling start_log.
460          */
461         if (unlikely(cld->cld_stopping)) {
462                 mutex_unlock(&cld->cld_lock);
463                 /* drop the ref from the find */
464                 config_log_put(cld);
465                 RETURN(rc);
466         }
467
468         spin_lock(&config_list_lock);
469         cld->cld_stopping = 1;
470         spin_unlock(&config_list_lock);
471
472         cld_recover = cld->cld_recover;
473         cld->cld_recover = NULL;
474         cld_params = cld->cld_params;
475         cld->cld_params = NULL;
476         cld_nodemap = cld->cld_nodemap;
477         cld->cld_nodemap = NULL;
478         cld_sptlrpc = cld->cld_sptlrpc;
479         cld->cld_sptlrpc = NULL;
480         mutex_unlock(&cld->cld_lock);
481
482         if (cld_recover) {
483                 config_mark_cld_stop(cld_recover);
484                 config_log_put(cld_recover);
485         }
486
487         if (cld_params) {
488                 config_mark_cld_stop(cld_params);
489                 config_log_put(cld_params);
490         }
491
492         /* don't set cld_stopping on nm lock as other targets may be active */
493         if (cld_nodemap)
494                 config_log_put(cld_nodemap);
495
496         if (cld_sptlrpc)
497                 config_log_put(cld_sptlrpc);
498
499         /* drop the ref from the find */
500         config_log_put(cld);
501         /* drop the start ref */
502         config_log_put(cld);
503
504         CDEBUG(D_MGC, "end config log %s (%d)\n", logname ? logname : "client",
505                rc);
506         RETURN(rc);
507 }
508
509 #ifdef CONFIG_PROC_FS
510 int lprocfs_mgc_rd_ir_state(struct seq_file *m, void *data)
511 {
512         struct obd_device       *obd = data;
513         struct obd_import       *imp;
514         struct obd_connect_data *ocd;
515         struct config_llog_data *cld;
516         ENTRY;
517
518         LASSERT(obd != NULL);
519         LPROCFS_CLIMP_CHECK(obd);
520         imp = obd->u.cli.cl_import;
521         ocd = &imp->imp_connect_data;
522
523         seq_printf(m, "imperative_recovery: %s\n",
524                    OCD_HAS_FLAG(ocd, IMP_RECOV) ? "ENABLED" : "DISABLED");
525         seq_printf(m, "client_state:\n");
526
527         spin_lock(&config_list_lock);
528         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
529                 if (cld->cld_recover == NULL)
530                         continue;
531                 seq_printf(m,  "    - { client: %s, nidtbl_version: %u }\n",
532                            cld->cld_logname,
533                            cld->cld_recover->cld_cfg.cfg_last_idx);
534         }
535         spin_unlock(&config_list_lock);
536
537         LPROCFS_CLIMP_EXIT(obd);
538         RETURN(0);
539 }
540 #endif
541
542 /* reenqueue any lost locks */
543 #define RQ_RUNNING      0x1
544 #define RQ_NOW          0x2
545 #define RQ_LATER        0x4
546 #define RQ_STOP         0x8
547 #define RQ_PRECLEANUP   0x10
548 static int                    rq_state = 0;
549 static wait_queue_head_t      rq_waitq;
550 static DECLARE_COMPLETION(rq_exit);
551 static DECLARE_COMPLETION(rq_start);
552
553 static void do_requeue(struct config_llog_data *cld)
554 {
555         int rc = 0;
556         ENTRY;
557
558         LASSERT(atomic_read(&cld->cld_refcount) > 0);
559
560         /*
561          * Do not run mgc_process_log on a disconnected export or an
562          * export which is being disconnected. Take the client
563          * semaphore to make the check non-racy.
564          */
565         down_read_nested(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem,
566                          OBD_CLI_SEM_MGC);
567         if (cld->cld_mgcexp->exp_obd->u.cli.cl_conn_count != 0) {
568                 CDEBUG(D_MGC, "updating log %s\n", cld->cld_logname);
569                 rc = mgc_process_log(cld->cld_mgcexp->exp_obd, cld);
570                 if (rc && rc != -ENOENT)
571                         CERROR("failed processing log: %d\n", rc);
572         } else {
573                 CDEBUG(D_MGC, "disconnecting, won't update log %s\n",
574                        cld->cld_logname);
575         }
576         up_read(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem);
577
578         EXIT;
579 }
580
581 /* this timeout represents how many seconds MGC should wait before
582  * requeue config and recover lock to the MGS. We need to randomize this
583  * in order to not flood the MGS.
584  */
585 #define MGC_TIMEOUT_MIN_SECONDS   5
586 #define MGC_TIMEOUT_RAND_CENTISEC 0x1ff /* ~500 */
587
588 static int mgc_requeue_thread(void *data)
589 {
590         int rc = 0;
591         bool first = true;
592         ENTRY;
593
594         CDEBUG(D_MGC, "Starting requeue thread\n");
595
596         /* Keep trying failed locks periodically */
597         spin_lock(&config_list_lock);
598         rq_state |= RQ_RUNNING;
599         while (!(rq_state & RQ_STOP)) {
600                 struct l_wait_info lwi;
601                 struct config_llog_data *cld, *cld_prev;
602                 int rand = cfs_rand() & MGC_TIMEOUT_RAND_CENTISEC;
603                 int to;
604
605                 /* Any new or requeued lostlocks will change the state */
606                 rq_state &= ~(RQ_NOW | RQ_LATER);
607                 spin_unlock(&config_list_lock);
608
609                 if (first) {
610                         first = false;
611                         complete(&rq_start);
612                 }
613
614                 /* Always wait a few seconds to allow the server who
615                    caused the lock revocation to finish its setup, plus some
616                    random so everyone doesn't try to reconnect at once. */
617                 to = msecs_to_jiffies(MGC_TIMEOUT_MIN_SECONDS * MSEC_PER_SEC);
618                 /* rand is centi-seconds */
619                 to += msecs_to_jiffies(rand * MSEC_PER_SEC / 100);
620                 lwi = LWI_TIMEOUT(to, NULL, NULL);
621                 l_wait_event(rq_waitq, rq_state & (RQ_STOP | RQ_PRECLEANUP),
622                              &lwi);
623
624                 /*
625                  * iterate & processing through the list. for each cld, process
626                  * its depending sptlrpc cld firstly (if any) and then itself.
627                  *
628                  * it's guaranteed any item in the list must have
629                  * reference > 0; and if cld_lostlock is set, at
630                  * least one reference is taken by the previous enqueue.
631                  */
632                 cld_prev = NULL;
633
634                 spin_lock(&config_list_lock);
635                 rq_state &= ~RQ_PRECLEANUP;
636                 list_for_each_entry(cld, &config_llog_list,
637                                     cld_list_chain) {
638                         if (!cld->cld_lostlock || cld->cld_stopping)
639                                 continue;
640
641                         /* hold reference to avoid being freed during
642                          * subsequent processing. */
643                         config_log_get(cld);
644                         cld->cld_lostlock = 0;
645                         spin_unlock(&config_list_lock);
646
647                         if (cld_prev)
648                                 config_log_put(cld_prev);
649                         cld_prev = cld;
650
651                         if (likely(!(rq_state & RQ_STOP))) {
652                                 do_requeue(cld);
653                                 spin_lock(&config_list_lock);
654                         } else {
655                                 spin_lock(&config_list_lock);
656                                 break;
657                         }
658                 }
659                 spin_unlock(&config_list_lock);
660                 if (cld_prev)
661                         config_log_put(cld_prev);
662
663                 /* Wait a bit to see if anyone else needs a requeue */
664                 lwi = (struct l_wait_info) { 0 };
665                 l_wait_event(rq_waitq, rq_state & (RQ_NOW | RQ_STOP),
666                              &lwi);
667                 spin_lock(&config_list_lock);
668         }
669
670         /* spinlock and while guarantee RQ_NOW and RQ_LATER are not set */
671         rq_state &= ~RQ_RUNNING;
672         spin_unlock(&config_list_lock);
673
674         complete(&rq_exit);
675
676         CDEBUG(D_MGC, "Ending requeue thread\n");
677         RETURN(rc);
678 }
679
680 /* Add a cld to the list to requeue.  Start the requeue thread if needed.
681    We are responsible for dropping the config log reference from here on out. */
682 static void mgc_requeue_add(struct config_llog_data *cld)
683 {
684         bool wakeup = false;
685         ENTRY;
686
687         CDEBUG(D_INFO, "log %s: requeue (r=%d sp=%d st=%x)\n",
688                 cld->cld_logname, atomic_read(&cld->cld_refcount),
689                 cld->cld_stopping, rq_state);
690         LASSERT(atomic_read(&cld->cld_refcount) > 0);
691
692         mutex_lock(&cld->cld_lock);
693         spin_lock(&config_list_lock);
694         if (!(rq_state & RQ_STOP) && !cld->cld_stopping && !cld->cld_lostlock) {
695                 cld->cld_lostlock = 1;
696                 rq_state |= RQ_NOW;
697                 wakeup = true;
698         }
699         spin_unlock(&config_list_lock);
700         mutex_unlock(&cld->cld_lock);
701         if (wakeup)
702                 wake_up(&rq_waitq);
703
704         EXIT;
705 }
706
707 /********************** class fns **********************/
708 static int mgc_local_llog_init(const struct lu_env *env,
709                                struct obd_device *obd,
710                                struct obd_device *disk)
711 {
712         struct llog_ctxt        *ctxt;
713         int                      rc;
714
715         ENTRY;
716
717         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_CONFIG_ORIG_CTXT, disk,
718                         &llog_osd_ops);
719         if (rc)
720                 RETURN(rc);
721
722         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
723         LASSERT(ctxt);
724         ctxt->loc_dir = obd->u.cli.cl_mgc_configs_dir;
725         llog_ctxt_put(ctxt);
726
727         RETURN(0);
728 }
729
730 static int mgc_local_llog_fini(const struct lu_env *env,
731                                struct obd_device *obd)
732 {
733         struct llog_ctxt *ctxt;
734
735         ENTRY;
736
737         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
738         llog_cleanup(env, ctxt);
739
740         RETURN(0);
741 }
742
743 static int mgc_fs_setup(const struct lu_env *env, struct obd_device *obd,
744                         struct super_block *sb)
745 {
746         struct lustre_sb_info   *lsi = s2lsi(sb);
747         struct client_obd       *cli = &obd->u.cli;
748         struct lu_fid            rfid, fid;
749         struct dt_object        *root, *dto;
750         int                      rc = 0;
751
752         ENTRY;
753
754         LASSERT(lsi);
755         LASSERT(lsi->lsi_dt_dev);
756
757         /* The mgc fs exclusion mutex. Only one fs can be setup at a time. */
758         mutex_lock(&cli->cl_mgc_mutex);
759
760         /* Setup the configs dir */
761         fid.f_seq = FID_SEQ_LOCAL_NAME;
762         fid.f_oid = 1;
763         fid.f_ver = 0;
764         rc = local_oid_storage_init(env, lsi->lsi_dt_dev, &fid,
765                                     &cli->cl_mgc_los);
766         if (rc)
767                 RETURN(rc);
768
769         rc = dt_root_get(env, lsi->lsi_dt_dev, &rfid);
770         if (rc)
771                 GOTO(out_los, rc);
772
773         root = dt_locate_at(env, lsi->lsi_dt_dev, &rfid,
774                             &cli->cl_mgc_los->los_dev->dd_lu_dev, NULL);
775         if (unlikely(IS_ERR(root)))
776                 GOTO(out_los, rc = PTR_ERR(root));
777
778         dto = local_file_find_or_create(env, cli->cl_mgc_los, root,
779                                         MOUNT_CONFIGS_DIR,
780                                         S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO);
781         lu_object_put_nocache(env, &root->do_lu);
782         if (IS_ERR(dto))
783                 GOTO(out_los, rc = PTR_ERR(dto));
784
785         cli->cl_mgc_configs_dir = dto;
786
787         LASSERT(lsi->lsi_osd_exp->exp_obd->obd_lvfs_ctxt.dt);
788         rc = mgc_local_llog_init(env, obd, lsi->lsi_osd_exp->exp_obd);
789         if (rc)
790                 GOTO(out_llog, rc);
791
792         /* We take an obd ref to insure that we can't get to mgc_cleanup
793          * without calling mgc_fs_cleanup first. */
794         class_incref(obd, "mgc_fs", obd);
795
796         /* We keep the cl_mgc_sem until mgc_fs_cleanup */
797         EXIT;
798 out_llog:
799         if (rc) {
800                 lu_object_put(env, &cli->cl_mgc_configs_dir->do_lu);
801                 cli->cl_mgc_configs_dir = NULL;
802         }
803 out_los:
804         if (rc < 0) {
805                 local_oid_storage_fini(env, cli->cl_mgc_los);
806                 cli->cl_mgc_los = NULL;
807                 mutex_unlock(&cli->cl_mgc_mutex);
808         }
809         return rc;
810 }
811
812 static int mgc_fs_cleanup(const struct lu_env *env, struct obd_device *obd)
813 {
814         struct client_obd       *cli = &obd->u.cli;
815         ENTRY;
816
817         LASSERT(cli->cl_mgc_los != NULL);
818
819         mgc_local_llog_fini(env, obd);
820
821         lu_object_put_nocache(env, &cli->cl_mgc_configs_dir->do_lu);
822         cli->cl_mgc_configs_dir = NULL;
823
824         local_oid_storage_fini(env, cli->cl_mgc_los);
825         cli->cl_mgc_los = NULL;
826
827         class_decref(obd, "mgc_fs", obd);
828         mutex_unlock(&cli->cl_mgc_mutex);
829
830         RETURN(0);
831 }
832
833 static int mgc_llog_init(const struct lu_env *env, struct obd_device *obd)
834 {
835         struct llog_ctxt        *ctxt;
836         int                      rc;
837
838         ENTRY;
839
840         /* setup only remote ctxt, the local disk context is switched per each
841          * filesystem during mgc_fs_setup() */
842         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_CONFIG_REPL_CTXT, obd,
843                         &llog_client_ops);
844         if (rc)
845                 RETURN(rc);
846
847         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
848         LASSERT(ctxt);
849
850         llog_initiator_connect(ctxt);
851         llog_ctxt_put(ctxt);
852
853         RETURN(0);
854 }
855
856 static int mgc_llog_fini(const struct lu_env *env, struct obd_device *obd)
857 {
858         struct llog_ctxt *ctxt;
859
860         ENTRY;
861
862         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
863         if (ctxt)
864                 llog_cleanup(env, ctxt);
865
866         RETURN(0);
867 }
868
869
870 static atomic_t mgc_count = ATOMIC_INIT(0);
871 static int mgc_precleanup(struct obd_device *obd)
872 {
873         int     rc = 0;
874         int     temp;
875         ENTRY;
876
877         if (atomic_dec_and_test(&mgc_count)) {
878                 LASSERT(rq_state & RQ_RUNNING);
879                 /* stop requeue thread */
880                 temp = RQ_STOP;
881         } else {
882                 /* wakeup requeue thread to clean our cld */
883                 temp = RQ_NOW | RQ_PRECLEANUP;
884         }
885
886         spin_lock(&config_list_lock);
887         rq_state |= temp;
888         spin_unlock(&config_list_lock);
889         wake_up(&rq_waitq);
890
891         if (temp & RQ_STOP)
892                 wait_for_completion(&rq_exit);
893         obd_cleanup_client_import(obd);
894
895         rc = mgc_llog_fini(NULL, obd);
896         if (rc != 0)
897                 CERROR("failed to cleanup llogging subsystems\n");
898
899         RETURN(rc);
900 }
901
902 static int mgc_cleanup(struct obd_device *obd)
903 {
904         int rc;
905         ENTRY;
906
907         /* COMPAT_146 - old config logs may have added profiles we don't
908            know about */
909         if (obd->obd_type->typ_refcnt <= 1)
910                 /* Only for the last mgc */
911                 class_del_profiles();
912
913         lprocfs_obd_cleanup(obd);
914         ptlrpcd_decref();
915
916         rc = client_obd_cleanup(obd);
917         RETURN(rc);
918 }
919
920 static int mgc_setup(struct obd_device *obd, struct lustre_cfg *lcfg)
921 {
922         struct task_struct      *task;
923         int                      rc;
924         ENTRY;
925
926         rc = ptlrpcd_addref();
927         if (rc < 0)
928                 RETURN(rc);
929
930         rc = client_obd_setup(obd, lcfg);
931         if (rc)
932                 GOTO(err_decref, rc);
933
934         rc = mgc_llog_init(NULL, obd);
935         if (rc) {
936                 CERROR("failed to setup llogging subsystems\n");
937                 GOTO(err_cleanup, rc);
938         }
939
940 #ifdef CONFIG_PROC_FS
941         obd->obd_vars = lprocfs_mgc_obd_vars;
942         lprocfs_obd_setup(obd);
943 #endif
944         sptlrpc_lprocfs_cliobd_attach(obd);
945
946         if (atomic_inc_return(&mgc_count) == 1) {
947                 rq_state = 0;
948                 init_waitqueue_head(&rq_waitq);
949
950                 /* start requeue thread */
951                 task = kthread_run(mgc_requeue_thread, NULL, "ll_cfg_requeue");
952                 if (IS_ERR(task)) {
953                         rc = PTR_ERR(task);
954                         CERROR("%s: cannot start requeue thread: rc = %d; "
955                                "no more log updates\n",
956                                obd->obd_name, rc);
957                         GOTO(err_cleanup, rc);
958                 }
959                 /* rc is the task_struct pointer of mgc_requeue_thread. */
960                 rc = 0;
961                 wait_for_completion(&rq_start);
962         }
963
964         RETURN(rc);
965
966 err_cleanup:
967         client_obd_cleanup(obd);
968 err_decref:
969         ptlrpcd_decref();
970         RETURN(rc);
971 }
972
973 /* based on ll_mdc_blocking_ast */
974 static int mgc_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
975                             void *data, int flag)
976 {
977         struct lustre_handle lockh;
978         struct config_llog_data *cld = (struct config_llog_data *)data;
979         int rc = 0;
980         ENTRY;
981
982         switch (flag) {
983         case LDLM_CB_BLOCKING:
984                 /* mgs wants the lock, give it up... */
985                 LDLM_DEBUG(lock, "MGC blocking CB");
986                 ldlm_lock2handle(lock, &lockh);
987                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
988                 break;
989         case LDLM_CB_CANCELING:
990                 /* We've given up the lock, prepare ourselves to update. */
991                 LDLM_DEBUG(lock, "MGC cancel CB");
992
993                 CDEBUG(D_MGC, "Lock res "DLDLMRES" (%.8s)\n",
994                        PLDLMRES(lock->l_resource),
995                        (char *)&lock->l_resource->lr_name.name[0]);
996
997                 if (!cld) {
998                         CDEBUG(D_INFO, "missing data, won't requeue\n");
999                         break;
1000                 }
1001
1002                 /* held at mgc_process_log(). */
1003                 LASSERT(atomic_read(&cld->cld_refcount) > 0);
1004
1005                 lock->l_ast_data = NULL;
1006                 /* Are we done with this log? */
1007                 if (cld->cld_stopping) {
1008                         CDEBUG(D_MGC, "log %s: stopping, won't requeue\n",
1009                                 cld->cld_logname);
1010                         config_log_put(cld);
1011                         break;
1012                 }
1013                 /* Make sure not to re-enqueue when the mgc is stopping
1014                    (we get called from client_disconnect_export) */
1015                 if (lock->l_conn_export == NULL ||
1016                     lock->l_conn_export->exp_obd->u.cli.cl_conn_count == 0) {
1017                         CDEBUG(D_MGC, "log %.8s: disconnecting, won't requeue\n",
1018                                 cld->cld_logname);
1019                         config_log_put(cld);
1020                         break;
1021                 }
1022
1023                 /* Re-enqueue now */
1024                 mgc_requeue_add(cld);
1025                 config_log_put(cld);
1026                 break;
1027         default:
1028                 LBUG();
1029         }
1030
1031         RETURN(rc);
1032 }
1033
1034 /* Not sure where this should go... */
1035 /* This is the timeout value for MGS_CONNECT request plus a ping interval, such
1036  * that we can have a chance to try the secondary MGS if any. */
1037 #define  MGC_ENQUEUE_LIMIT (INITIAL_CONNECT_TIMEOUT + (AT_OFF ? 0 : at_min) \
1038                                 + PING_INTERVAL)
1039 #define  MGC_TARGET_REG_LIMIT 10
1040 #define  MGC_SEND_PARAM_LIMIT 10
1041
1042 /* Send parameter to MGS*/
1043 static int mgc_set_mgs_param(struct obd_export *exp,
1044                              struct mgs_send_param *msp)
1045 {
1046         struct ptlrpc_request *req;
1047         struct mgs_send_param *req_msp, *rep_msp;
1048         int rc;
1049         ENTRY;
1050
1051         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1052                                         &RQF_MGS_SET_INFO, LUSTRE_MGS_VERSION,
1053                                         MGS_SET_INFO);
1054         if (!req)
1055                 RETURN(-ENOMEM);
1056
1057         req_msp = req_capsule_client_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
1058         if (!req_msp) {
1059                 ptlrpc_req_finished(req);
1060                 RETURN(-ENOMEM);
1061         }
1062
1063         memcpy(req_msp, msp, sizeof(*req_msp));
1064         ptlrpc_request_set_replen(req);
1065
1066         /* Limit how long we will wait for the enqueue to complete */
1067         req->rq_delay_limit = MGC_SEND_PARAM_LIMIT;
1068         rc = ptlrpc_queue_wait(req);
1069         if (!rc) {
1070                 rep_msp = req_capsule_server_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
1071                 memcpy(msp, rep_msp, sizeof(*rep_msp));
1072         }
1073
1074         ptlrpc_req_finished(req);
1075
1076         RETURN(rc);
1077 }
1078
1079 /* Take a config lock so we can get cancel notifications */
1080 static int mgc_enqueue(struct obd_export *exp, enum ldlm_type type,
1081                        union ldlm_policy_data *policy, enum ldlm_mode mode,
1082                        __u64 *flags, void *bl_cb, void *cp_cb, void *gl_cb,
1083                        void *data, __u32 lvb_len, void *lvb_swabber,
1084                        struct lustre_handle *lockh)
1085 {
1086         struct config_llog_data *cld = (struct config_llog_data *)data;
1087         struct ldlm_enqueue_info einfo = {
1088                 .ei_type        = type,
1089                 .ei_mode        = mode,
1090                 .ei_cb_bl       = mgc_blocking_ast,
1091                 .ei_cb_cp       = ldlm_completion_ast,
1092         };
1093         struct ptlrpc_request *req;
1094         int short_limit = cld_is_sptlrpc(cld);
1095         int rc;
1096         ENTRY;
1097
1098         CDEBUG(D_MGC, "Enqueue for %s (res %#llx)\n", cld->cld_logname,
1099                cld->cld_resid.name[0]);
1100
1101         /* We need a callback for every lockholder, so don't try to
1102            ldlm_lock_match (see rev 1.1.2.11.2.47) */
1103         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1104                                         &RQF_LDLM_ENQUEUE, LUSTRE_DLM_VERSION,
1105                                         LDLM_ENQUEUE);
1106         if (req == NULL)
1107                 RETURN(-ENOMEM);
1108
1109         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER, 0);
1110         ptlrpc_request_set_replen(req);
1111
1112         /* check if this is server or client */
1113         if (cld->cld_cfg.cfg_sb) {
1114                 struct lustre_sb_info *lsi = s2lsi(cld->cld_cfg.cfg_sb);
1115                 if (lsi && IS_SERVER(lsi))
1116                         short_limit = 1;
1117         }
1118         /* Limit how long we will wait for the enqueue to complete */
1119         req->rq_delay_limit = short_limit ? 5 : MGC_ENQUEUE_LIMIT;
1120         rc = ldlm_cli_enqueue(exp, &req, &einfo, &cld->cld_resid, NULL, flags,
1121                               NULL, 0, LVB_T_NONE, lockh, 0);
1122         /* A failed enqueue should still call the mgc_blocking_ast,
1123            where it will be requeued if needed ("grant failed"). */
1124         ptlrpc_req_finished(req);
1125         RETURN(rc);
1126 }
1127
1128 static int mgc_cancel(struct obd_export *exp, enum ldlm_mode mode,
1129                       struct lustre_handle *lockh)
1130 {
1131         ENTRY;
1132
1133         ldlm_lock_decref(lockh, mode);
1134
1135         RETURN(0);
1136 }
1137
1138 static void mgc_notify_active(struct obd_device *unused)
1139 {
1140         /* wakeup mgc_requeue_thread to requeue mgc lock */
1141         spin_lock(&config_list_lock);
1142         rq_state |= RQ_NOW;
1143         spin_unlock(&config_list_lock);
1144         wake_up(&rq_waitq);
1145
1146         /* TODO: Help the MGS rebuild nidtbl. -jay */
1147 }
1148
1149 /* Send target_reg message to MGS */
1150 static int mgc_target_register(struct obd_export *exp,
1151                                struct mgs_target_info *mti)
1152 {
1153         struct ptlrpc_request  *req;
1154         struct mgs_target_info *req_mti, *rep_mti;
1155         int                     rc;
1156         ENTRY;
1157
1158         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1159                                         &RQF_MGS_TARGET_REG, LUSTRE_MGS_VERSION,
1160                                         MGS_TARGET_REG);
1161         if (req == NULL)
1162                 RETURN(-ENOMEM);
1163
1164         req_mti = req_capsule_client_get(&req->rq_pill, &RMF_MGS_TARGET_INFO);
1165         if (!req_mti) {
1166                 ptlrpc_req_finished(req);
1167                 RETURN(-ENOMEM);
1168         }
1169
1170         memcpy(req_mti, mti, sizeof(*req_mti));
1171         ptlrpc_request_set_replen(req);
1172         CDEBUG(D_MGC, "register %s\n", mti->mti_svname);
1173         /* Limit how long we will wait for the enqueue to complete */
1174         req->rq_delay_limit = MGC_TARGET_REG_LIMIT;
1175
1176         rc = ptlrpc_queue_wait(req);
1177         if (!rc) {
1178                 rep_mti = req_capsule_server_get(&req->rq_pill,
1179                                                  &RMF_MGS_TARGET_INFO);
1180                 memcpy(mti, rep_mti, sizeof(*rep_mti));
1181                 CDEBUG(D_MGC, "register %s got index = %d\n",
1182                        mti->mti_svname, mti->mti_stripe_index);
1183         }
1184         ptlrpc_req_finished(req);
1185
1186         RETURN(rc);
1187 }
1188
1189 static int mgc_set_info_async(const struct lu_env *env, struct obd_export *exp,
1190                               u32 keylen, void *key,
1191                               u32 vallen, void *val,
1192                               struct ptlrpc_request_set *set)
1193 {
1194         int rc = -EINVAL;
1195         ENTRY;
1196
1197         /* Turn off initial_recov after we try all backup servers once */
1198         if (KEY_IS(KEY_INIT_RECOV_BACKUP)) {
1199                 struct obd_import *imp = class_exp2cliimp(exp);
1200                 int value;
1201                 if (vallen != sizeof(int))
1202                         RETURN(-EINVAL);
1203                 value = *(int *)val;
1204                 CDEBUG(D_MGC, "InitRecov %s %d/d%d:i%d:r%d:or%d:%s\n",
1205                        imp->imp_obd->obd_name, value,
1206                        imp->imp_deactive, imp->imp_invalid,
1207                        imp->imp_replayable, imp->imp_obd->obd_replayable,
1208                        ptlrpc_import_state_name(imp->imp_state));
1209                 /* Resurrect if we previously died */
1210                 if ((imp->imp_state != LUSTRE_IMP_FULL &&
1211                      imp->imp_state != LUSTRE_IMP_NEW) || value > 1)
1212                         ptlrpc_reconnect_import(imp);
1213                 RETURN(0);
1214         }
1215         /* FIXME move this to mgc_process_config */
1216         if (KEY_IS(KEY_REGISTER_TARGET)) {
1217                 struct mgs_target_info *mti;
1218                 if (vallen != sizeof(struct mgs_target_info))
1219                         RETURN(-EINVAL);
1220                 mti = (struct mgs_target_info *)val;
1221                 CDEBUG(D_MGC, "register_target %s %#x\n",
1222                        mti->mti_svname, mti->mti_flags);
1223                 rc =  mgc_target_register(exp, mti);
1224                 RETURN(rc);
1225         }
1226         if (KEY_IS(KEY_SET_FS)) {
1227                 struct super_block *sb = (struct super_block *)val;
1228
1229                 if (vallen != sizeof(struct super_block))
1230                         RETURN(-EINVAL);
1231
1232                 rc = mgc_fs_setup(env, exp->exp_obd, sb);
1233                 RETURN(rc);
1234         }
1235         if (KEY_IS(KEY_CLEAR_FS)) {
1236                 if (vallen != 0)
1237                         RETURN(-EINVAL);
1238                 rc = mgc_fs_cleanup(env, exp->exp_obd);
1239                 RETURN(rc);
1240         }
1241         if (KEY_IS(KEY_SET_INFO)) {
1242                 struct mgs_send_param *msp;
1243
1244                 msp = (struct mgs_send_param *)val;
1245                 rc =  mgc_set_mgs_param(exp, msp);
1246                 RETURN(rc);
1247         }
1248         if (KEY_IS(KEY_MGSSEC)) {
1249                 struct client_obd     *cli = &exp->exp_obd->u.cli;
1250                 struct sptlrpc_flavor  flvr;
1251
1252                 /*
1253                  * empty string means using current flavor, if which haven't
1254                  * been set yet, set it as null.
1255                  *
1256                  * if flavor has been set previously, check the asking flavor
1257                  * must match the existing one.
1258                  */
1259                 if (vallen == 0) {
1260                         if (cli->cl_flvr_mgc.sf_rpc != SPTLRPC_FLVR_INVALID)
1261                                 RETURN(0);
1262                         val = "null";
1263                         vallen = 4;
1264                 }
1265
1266                 rc = sptlrpc_parse_flavor(val, &flvr);
1267                 if (rc) {
1268                         CERROR("invalid sptlrpc flavor %s to MGS\n",
1269                                (char *) val);
1270                         RETURN(rc);
1271                 }
1272
1273                 /*
1274                  * caller already hold a mutex
1275                  */
1276                 if (cli->cl_flvr_mgc.sf_rpc == SPTLRPC_FLVR_INVALID) {
1277                         cli->cl_flvr_mgc = flvr;
1278                 } else if (memcmp(&cli->cl_flvr_mgc, &flvr,
1279                                   sizeof(flvr)) != 0) {
1280                         char    str[20];
1281
1282                         sptlrpc_flavor2name(&cli->cl_flvr_mgc,
1283                                             str, sizeof(str));
1284                         LCONSOLE_ERROR("asking sptlrpc flavor %s to MGS but "
1285                                        "currently %s is in use\n",
1286                                        (char *) val, str);
1287                         rc = -EPERM;
1288                 }
1289                 RETURN(rc);
1290         }
1291
1292         RETURN(rc);
1293 }
1294
1295 static int mgc_get_info(const struct lu_env *env, struct obd_export *exp,
1296                         __u32 keylen, void *key, __u32 *vallen, void *val)
1297 {
1298         int rc = -EINVAL;
1299
1300         if (KEY_IS(KEY_CONN_DATA)) {
1301                 struct obd_import *imp = class_exp2cliimp(exp);
1302                 struct obd_connect_data *data = val;
1303
1304                 if (*vallen == sizeof(*data)) {
1305                         *data = imp->imp_connect_data;
1306                         rc = 0;
1307                 }
1308         }
1309
1310         return rc;
1311 }
1312
1313 static int mgc_import_event(struct obd_device *obd,
1314                             struct obd_import *imp,
1315                             enum obd_import_event event)
1316 {
1317         int rc = 0;
1318
1319         LASSERT(imp->imp_obd == obd);
1320         CDEBUG(D_MGC, "import event %#x\n", event);
1321
1322         switch (event) {
1323         case IMP_EVENT_DISCON:
1324                 /* MGC imports should not wait for recovery */
1325                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1326                         ptlrpc_pinger_ir_down();
1327                 break;
1328         case IMP_EVENT_INACTIVE:
1329                 break;
1330         case IMP_EVENT_INVALIDATE: {
1331                 struct ldlm_namespace *ns = obd->obd_namespace;
1332                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
1333                 break;
1334         }
1335         case IMP_EVENT_ACTIVE:
1336                 CDEBUG(D_INFO, "%s: Reactivating import\n", obd->obd_name);
1337                 /* Clearing obd_no_recov allows us to continue pinging */
1338                 obd->obd_no_recov = 0;
1339                 mgc_notify_active(obd);
1340                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1341                         ptlrpc_pinger_ir_up();
1342                 break;
1343         case IMP_EVENT_OCD:
1344                 break;
1345         case IMP_EVENT_DEACTIVATE:
1346         case IMP_EVENT_ACTIVATE:
1347                 break;
1348         default:
1349                 CERROR("Unknown import event %#x\n", event);
1350                 LBUG();
1351         }
1352         RETURN(rc);
1353 }
1354
1355 enum {
1356         CONFIG_READ_NRPAGES_INIT = 1 << (20 - PAGE_CACHE_SHIFT),
1357         CONFIG_READ_NRPAGES      = 4
1358 };
1359
1360 static int mgc_apply_recover_logs(struct obd_device *mgc,
1361                                   struct config_llog_data *cld,
1362                                   __u64 max_version,
1363                                   void *data, int datalen, bool mne_swab)
1364 {
1365         struct config_llog_instance *cfg = &cld->cld_cfg;
1366         struct lustre_sb_info       *lsi = s2lsi(cfg->cfg_sb);
1367         struct mgs_nidtbl_entry *entry;
1368         struct lustre_cfg       *lcfg;
1369         struct lustre_cfg_bufs   bufs;
1370         u64   prev_version = 0;
1371         char *inst;
1372         char *buf;
1373         int   bufsz;
1374         int   pos;
1375         int   rc  = 0;
1376         int   off = 0;
1377         ENTRY;
1378
1379         LASSERT(cfg->cfg_instance != NULL);
1380         LASSERT(cfg->cfg_sb == cfg->cfg_instance);
1381
1382         OBD_ALLOC(inst, PAGE_CACHE_SIZE);
1383         if (inst == NULL)
1384                 RETURN(-ENOMEM);
1385
1386         if (!IS_SERVER(lsi)) {
1387                 pos = snprintf(inst, PAGE_CACHE_SIZE, "%p", cfg->cfg_instance);
1388                 if (pos >= PAGE_CACHE_SIZE) {
1389                         OBD_FREE(inst, PAGE_CACHE_SIZE);
1390                         return -E2BIG;
1391                 }
1392         } else {
1393                 LASSERT(IS_MDT(lsi));
1394                 rc = server_name2svname(lsi->lsi_svname, inst, NULL,
1395                                         PAGE_CACHE_SIZE);
1396                 if (rc) {
1397                         OBD_FREE(inst, PAGE_CACHE_SIZE);
1398                         RETURN(-EINVAL);
1399                 }
1400                 pos = strlen(inst);
1401         }
1402
1403         ++pos;
1404         buf   = inst + pos;
1405         bufsz = PAGE_CACHE_SIZE - pos;
1406
1407         while (datalen > 0) {
1408                 int   entry_len = sizeof(*entry);
1409                 int   is_ost, i;
1410                 struct obd_device *obd;
1411                 char *obdname;
1412                 char *cname;
1413                 char *params;
1414                 char *uuid;
1415
1416                 rc = -EINVAL;
1417                 if (datalen < sizeof(*entry))
1418                         break;
1419
1420                 entry = (typeof(entry))(data + off);
1421
1422                 /* sanity check */
1423                 if (entry->mne_nid_type != 0) /* only support type 0 for ipv4 */
1424                         break;
1425                 if (entry->mne_nid_count == 0) /* at least one nid entry */
1426                         break;
1427                 if (entry->mne_nid_size != sizeof(lnet_nid_t))
1428                         break;
1429
1430                 entry_len += entry->mne_nid_count * entry->mne_nid_size;
1431                 if (datalen < entry_len) /* must have entry_len at least */
1432                         break;
1433
1434                 /* Keep this swab for normal mixed endian handling. LU-1644 */
1435                 if (mne_swab)
1436                         lustre_swab_mgs_nidtbl_entry(entry);
1437                 if (entry->mne_length > PAGE_CACHE_SIZE) {
1438                         CERROR("MNE too large (%u)\n", entry->mne_length);
1439                         break;
1440                 }
1441
1442                 if (entry->mne_length < entry_len)
1443                         break;
1444
1445                 off     += entry->mne_length;
1446                 datalen -= entry->mne_length;
1447                 if (datalen < 0)
1448                         break;
1449
1450                 if (entry->mne_version > max_version) {
1451                         CERROR("entry index(%lld) is over max_index(%lld)\n",
1452                                entry->mne_version, max_version);
1453                         break;
1454                 }
1455
1456                 if (prev_version >= entry->mne_version) {
1457                         CERROR("index unsorted, prev %lld, now %lld\n",
1458                                prev_version, entry->mne_version);
1459                         break;
1460                 }
1461                 prev_version = entry->mne_version;
1462
1463                 /*
1464                  * Write a string with format "nid::instance" to
1465                  * lustre/<osc|mdc>/<target>-<osc|mdc>-<instance>/import.
1466                  */
1467
1468                 is_ost = entry->mne_type == LDD_F_SV_TYPE_OST;
1469                 memset(buf, 0, bufsz);
1470                 obdname = buf;
1471                 pos = 0;
1472
1473                 /* lustre-OST0001-osc-<instance #> */
1474                 strcpy(obdname, cld->cld_logname);
1475                 cname = strrchr(obdname, '-');
1476                 if (cname == NULL) {
1477                         CERROR("mgc %s: invalid logname %s\n",
1478                                mgc->obd_name, obdname);
1479                         break;
1480                 }
1481
1482                 pos = cname - obdname;
1483                 obdname[pos] = 0;
1484                 pos += sprintf(obdname + pos, "-%s%04x",
1485                                   is_ost ? "OST" : "MDT", entry->mne_index);
1486
1487                 cname = is_ost ? "osc" : "mdc",
1488                 pos += sprintf(obdname + pos, "-%s-%s", cname, inst);
1489                 lustre_cfg_bufs_reset(&bufs, obdname);
1490
1491                 /* find the obd by obdname */
1492                 obd = class_name2obd(obdname);
1493                 if (obd == NULL) {
1494                         CDEBUG(D_INFO, "mgc %s: cannot find obdname %s\n",
1495                                mgc->obd_name, obdname);
1496                         rc = 0;
1497                         /* this is a safe race, when the ost is starting up...*/
1498                         continue;
1499                 }
1500
1501                 /* osc.import = "connection=<Conn UUID>::<target instance>" */
1502                 ++pos;
1503                 params = buf + pos;
1504                 pos += sprintf(params, "%s.import=%s", cname, "connection=");
1505                 uuid = buf + pos;
1506
1507                 down_read(&obd->u.cli.cl_sem);
1508                 if (obd->u.cli.cl_import == NULL) {
1509                         /* client does not connect to the OST yet */
1510                         up_read(&obd->u.cli.cl_sem);
1511                         rc = 0;
1512                         continue;
1513                 }
1514
1515                 /* iterate all nids to find one */
1516                 /* find uuid by nid */
1517                 rc = -ENOENT;
1518                 for (i = 0; i < entry->mne_nid_count; i++) {
1519                         rc = client_import_find_conn(obd->u.cli.cl_import,
1520                                                      entry->u.nids[i],
1521                                                      (struct obd_uuid *)uuid);
1522                         if (rc == 0)
1523                                 break;
1524                 }
1525
1526                 up_read(&obd->u.cli.cl_sem);
1527                 if (rc < 0) {
1528                         CERROR("mgc: cannot find uuid by nid %s\n",
1529                                libcfs_nid2str(entry->u.nids[0]));
1530                         break;
1531                 }
1532
1533                 CDEBUG(D_INFO, "Find uuid %s by nid %s\n",
1534                        uuid, libcfs_nid2str(entry->u.nids[0]));
1535
1536                 pos += strlen(uuid);
1537                 pos += sprintf(buf + pos, "::%u", entry->mne_instance);
1538                 LASSERT(pos < bufsz);
1539
1540                 lustre_cfg_bufs_set_string(&bufs, 1, params);
1541
1542                 lcfg = lustre_cfg_new(LCFG_PARAM, &bufs);
1543                 if (lcfg == NULL) {
1544                         rc = -ENOMEM;
1545                         break;
1546                 }
1547
1548                 CDEBUG(D_INFO, "ir apply logs %lld/%lld for %s -> %s\n",
1549                        prev_version, max_version, obdname, params);
1550
1551                 rc = class_process_config(lcfg);
1552                 lustre_cfg_free(lcfg);
1553                 if (rc)
1554                         CDEBUG(D_INFO, "process config for %s error %d\n",
1555                                obdname, rc);
1556
1557                 /* continue, even one with error */
1558         }
1559
1560         OBD_FREE(inst, PAGE_CACHE_SIZE);
1561         RETURN(rc);
1562 }
1563
1564 /**
1565  * This function is called if this client was notified for target restarting
1566  * by the MGS. A CONFIG_READ RPC is going to send to fetch recovery or
1567  * nodemap logs.
1568  */
1569 static int mgc_process_recover_nodemap_log(struct obd_device *obd,
1570                                            struct config_llog_data *cld)
1571 {
1572         struct ptlrpc_connection *mgc_conn;
1573         struct ptlrpc_request *req = NULL;
1574         struct config_llog_instance *cfg = &cld->cld_cfg;
1575         struct mgs_config_body *body;
1576         struct mgs_config_res *res;
1577         struct nodemap_config *new_config = NULL;
1578         struct lu_nodemap *recent_nodemap = NULL;
1579         struct ptlrpc_bulk_desc *desc;
1580         struct page **pages = NULL;
1581         __u64 config_read_offset = 0;
1582         int nrpages = 0;
1583         bool eof = true;
1584         bool mne_swab = false;
1585         int i;
1586         int ealen;
1587         int rc;
1588         ENTRY;
1589
1590         mgc_conn = class_exp2cliimp(cld->cld_mgcexp)->imp_connection;
1591
1592         /* don't need to get local config */
1593         if (cld_is_nodemap(cld) &&
1594             (LNET_NETTYP(LNET_NIDNET(mgc_conn->c_peer.nid)) == LOLND))
1595                 GOTO(out, rc = 0);
1596
1597         /* allocate buffer for bulk transfer.
1598          * if this is the first time for this mgs to read logs,
1599          * CONFIG_READ_NRPAGES_INIT will be used since it will read all logs
1600          * once; otherwise, it only reads increment of logs, this should be
1601          * small and CONFIG_READ_NRPAGES will be used.
1602          */
1603         nrpages = CONFIG_READ_NRPAGES;
1604         if (cfg->cfg_last_idx == 0 || cld_is_nodemap(cld))
1605                 nrpages = CONFIG_READ_NRPAGES_INIT;
1606
1607         OBD_ALLOC(pages, sizeof(*pages) * nrpages);
1608         if (pages == NULL)
1609                 GOTO(out, rc = -ENOMEM);
1610
1611         for (i = 0; i < nrpages; i++) {
1612                 pages[i] = alloc_page(GFP_KERNEL);
1613                 if (pages[i] == NULL)
1614                         GOTO(out, rc = -ENOMEM);
1615         }
1616
1617 again:
1618 #ifdef HAVE_SERVER_SUPPORT
1619         if (cld_is_nodemap(cld) && config_read_offset == 0) {
1620                 new_config = nodemap_config_alloc();
1621                 if (IS_ERR(new_config)) {
1622                         rc = PTR_ERR(new_config);
1623                         new_config = NULL;
1624                         GOTO(out, rc);
1625                 }
1626         }
1627 #endif
1628         LASSERT(cld_is_recover(cld) || cld_is_nodemap(cld));
1629         LASSERT(mutex_is_locked(&cld->cld_lock));
1630         req = ptlrpc_request_alloc(class_exp2cliimp(cld->cld_mgcexp),
1631                                    &RQF_MGS_CONFIG_READ);
1632         if (req == NULL)
1633                 GOTO(out, rc = -ENOMEM);
1634
1635         rc = ptlrpc_request_pack(req, LUSTRE_MGS_VERSION, MGS_CONFIG_READ);
1636         if (rc)
1637                 GOTO(out, rc);
1638
1639         /* pack request */
1640         body = req_capsule_client_get(&req->rq_pill, &RMF_MGS_CONFIG_BODY);
1641         LASSERT(body != NULL);
1642         LASSERT(sizeof(body->mcb_name) > strlen(cld->cld_logname));
1643         if (strlcpy(body->mcb_name, cld->cld_logname, sizeof(body->mcb_name))
1644             >= sizeof(body->mcb_name))
1645                 GOTO(out, rc = -E2BIG);
1646         if (cld_is_nodemap(cld))
1647                 body->mcb_offset = config_read_offset;
1648         else
1649                 body->mcb_offset = cfg->cfg_last_idx + 1;
1650         body->mcb_type   = cld->cld_type;
1651         body->mcb_bits   = PAGE_CACHE_SHIFT;
1652         body->mcb_units  = nrpages;
1653
1654         /* allocate bulk transfer descriptor */
1655         desc = ptlrpc_prep_bulk_imp(req, nrpages, 1,
1656                                     PTLRPC_BULK_PUT_SINK | PTLRPC_BULK_BUF_KIOV,
1657                                     MGS_BULK_PORTAL,
1658                                     &ptlrpc_bulk_kiov_pin_ops);
1659         if (desc == NULL)
1660                 GOTO(out, rc = -ENOMEM);
1661
1662         for (i = 0; i < nrpages; i++)
1663                 desc->bd_frag_ops->add_kiov_frag(desc, pages[i], 0,
1664                                                  PAGE_CACHE_SIZE);
1665
1666         ptlrpc_request_set_replen(req);
1667         rc = ptlrpc_queue_wait(req);
1668         if (rc)
1669                 GOTO(out, rc);
1670
1671         res = req_capsule_server_get(&req->rq_pill, &RMF_MGS_CONFIG_RES);
1672         if (!res)
1673                 GOTO(out, rc = -EPROTO);
1674
1675         if (cld_is_nodemap(cld)) {
1676                 config_read_offset = res->mcr_offset;
1677                 eof = config_read_offset == II_END_OFF;
1678         } else {
1679                 if (res->mcr_size < res->mcr_offset)
1680                         GOTO(out, rc = -EINVAL);
1681
1682                 /* always update the index even though it might have errors with
1683                  * handling the recover logs
1684                  */
1685                 cfg->cfg_last_idx = res->mcr_offset;
1686                 eof = res->mcr_offset == res->mcr_size;
1687
1688                 CDEBUG(D_INFO, "Latest version %lld, more %d.\n",
1689                        res->mcr_offset, eof == false);
1690         }
1691
1692         ealen = sptlrpc_cli_unwrap_bulk_read(req, req->rq_bulk, 0);
1693         if (ealen < 0)
1694                 GOTO(out, rc = ealen);
1695
1696         if (ealen > nrpages << PAGE_CACHE_SHIFT)
1697                 GOTO(out, rc = -EINVAL);
1698
1699         if (ealen == 0) { /* no logs transferred */
1700 #ifdef HAVE_SERVER_SUPPORT
1701                 /* config changed since first read RPC */
1702                 if (cld_is_nodemap(cld) && config_read_offset == 0) {
1703                         recent_nodemap = NULL;
1704                         nodemap_config_dealloc(new_config);
1705                         new_config = NULL;
1706
1707                         CDEBUG(D_INFO, "nodemap config changed in transit, retrying\n");
1708
1709                         /* setting eof to false, we request config again */
1710                         eof = false;
1711                         GOTO(out, rc = 0);
1712                 }
1713 #endif
1714                 if (!eof)
1715                         rc = -EINVAL;
1716                 GOTO(out, rc);
1717         }
1718
1719         mne_swab = !!ptlrpc_rep_need_swab(req);
1720 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
1721         /* This import flag means the server did an extra swab of IR MNE
1722          * records (fixed in LU-1252), reverse it here if needed. LU-1644 */
1723         if (unlikely(req->rq_import->imp_need_mne_swab))
1724                 mne_swab = !mne_swab;
1725 #endif
1726
1727         /* When a nodemap config is received, we build a new nodemap config,
1728          * with new nodemap structs. We keep track of the most recently added
1729          * nodemap since the config is read ordered by nodemap_id, and so it
1730          * is likely that the next record will be related. Because access to
1731          * the nodemaps is single threaded until the nodemap_config is active,
1732          * we don't need to reference count with recent_nodemap, though
1733          * recent_nodemap should be set to NULL when the nodemap_config
1734          * is either destroyed or set active.
1735          */
1736         for (i = 0; i < nrpages && ealen > 0; i++) {
1737                 int rc2;
1738                 union lu_page   *ptr;
1739
1740                 ptr = kmap(pages[i]);
1741                 if (cld_is_nodemap(cld))
1742                         rc2 = nodemap_process_idx_pages(new_config, ptr,
1743                                                        &recent_nodemap);
1744                 else
1745                         rc2 = mgc_apply_recover_logs(obd, cld, res->mcr_offset,
1746                                                      ptr,
1747                                                      min_t(int, ealen,
1748                                                            PAGE_CACHE_SIZE),
1749                                                      mne_swab);
1750                 kunmap(pages[i]);
1751                 if (rc2 < 0) {
1752                         CWARN("%s: error processing %s log %s: rc = %d\n",
1753                               obd->obd_name,
1754                               cld_is_nodemap(cld) ? "nodemap" : "recovery",
1755                               cld->cld_logname,
1756                               rc2);
1757                         break;
1758                 }
1759
1760                 ealen -= PAGE_CACHE_SIZE;
1761         }
1762
1763 out:
1764         if (req) {
1765                 ptlrpc_req_finished(req);
1766                 req = NULL;
1767         }
1768
1769         if (rc == 0 && !eof)
1770                 goto again;
1771
1772 #ifdef HAVE_SERVER_SUPPORT
1773         if (new_config != NULL) {
1774                 /* recent_nodemap cannot be used after set_active/dealloc */
1775                 if (rc == 0)
1776                         nodemap_config_set_active_mgc(new_config);
1777                 else
1778                         nodemap_config_dealloc(new_config);
1779         }
1780 #endif
1781
1782         if (pages) {
1783                 for (i = 0; i < nrpages; i++) {
1784                         if (pages[i] == NULL)
1785                                 break;
1786                         __free_page(pages[i]);
1787                 }
1788                 OBD_FREE(pages, sizeof(*pages) * nrpages);
1789         }
1790         return rc;
1791 }
1792
1793 /* Copy a remote log locally */
1794 static int mgc_llog_local_copy(const struct lu_env *env,
1795                                struct obd_device *obd,
1796                                struct llog_ctxt *rctxt,
1797                                struct llog_ctxt *lctxt, char *logname)
1798 {
1799         char    *temp_log;
1800         int      rc;
1801
1802         ENTRY;
1803
1804         /*
1805          * - copy it to backup using llog_backup()
1806          * - copy remote llog to logname using llog_backup()
1807          * - if failed then move bakup to logname again
1808          */
1809
1810         OBD_ALLOC(temp_log, strlen(logname) + 2);
1811         if (!temp_log)
1812                 RETURN(-ENOMEM);
1813         sprintf(temp_log, "%sT", logname);
1814
1815         /* make a copy of local llog at first */
1816         rc = llog_backup(env, obd, lctxt, lctxt, logname, temp_log);
1817         if (rc < 0 && rc != -ENOENT)
1818                 GOTO(out, rc);
1819         /* copy remote llog to the local copy */
1820         rc = llog_backup(env, obd, rctxt, lctxt, logname, logname);
1821         if (rc == -ENOENT) {
1822                 /* no remote llog, delete local one too */
1823                 llog_erase(env, lctxt, NULL, logname);
1824         } else if (rc < 0) {
1825                 /* error during backup, get local one back from the copy */
1826                 llog_backup(env, obd, lctxt, lctxt, temp_log, logname);
1827 out:
1828                 CERROR("%s: failed to copy remote log %s: rc = %d\n",
1829                        obd->obd_name, logname, rc);
1830         }
1831         llog_erase(env, lctxt, NULL, temp_log);
1832         OBD_FREE(temp_log, strlen(logname) + 2);
1833         return rc;
1834 }
1835
1836 /* local_only means it cannot get remote llogs */
1837 static int mgc_process_cfg_log(struct obd_device *mgc,
1838                                struct config_llog_data *cld, int local_only)
1839 {
1840         struct llog_ctxt        *ctxt, *lctxt = NULL;
1841         struct client_obd       *cli = &mgc->u.cli;
1842         struct lustre_sb_info   *lsi = NULL;
1843         int                      rc = 0;
1844         bool                     sptlrpc_started = false;
1845         struct lu_env           *env;
1846
1847         ENTRY;
1848
1849         LASSERT(cld);
1850         LASSERT(mutex_is_locked(&cld->cld_lock));
1851
1852         /*
1853          * local copy of sptlrpc log is controlled elsewhere, don't try to
1854          * read it up here.
1855          */
1856         if (cld_is_sptlrpc(cld) && local_only)
1857                 RETURN(0);
1858
1859         if (cld->cld_cfg.cfg_sb)
1860                 lsi = s2lsi(cld->cld_cfg.cfg_sb);
1861
1862         OBD_ALLOC_PTR(env);
1863         if (env == NULL)
1864                 RETURN(-ENOMEM);
1865
1866         rc = lu_env_init(env, LCT_MG_THREAD);
1867         if (rc)
1868                 GOTO(out_free, rc);
1869
1870         ctxt = llog_get_context(mgc, LLOG_CONFIG_REPL_CTXT);
1871         LASSERT(ctxt);
1872
1873         lctxt = llog_get_context(mgc, LLOG_CONFIG_ORIG_CTXT);
1874
1875         /* Copy the setup log locally if we can. Don't mess around if we're
1876          * running an MGS though (logs are already local). */
1877         if (lctxt && lsi && IS_SERVER(lsi) && !IS_MGS(lsi) &&
1878             cli->cl_mgc_configs_dir != NULL &&
1879             lu2dt_dev(cli->cl_mgc_configs_dir->do_lu.lo_dev) ==
1880             lsi->lsi_dt_dev) {
1881                 if (!local_only)
1882                         /* Only try to copy log if we have the lock. */
1883                         rc = mgc_llog_local_copy(env, mgc, ctxt, lctxt,
1884                                                  cld->cld_logname);
1885                 if (local_only || rc) {
1886                         if (strcmp(cld->cld_logname, PARAMS_FILENAME) != 0 &&
1887                             llog_is_empty(env, lctxt, cld->cld_logname)) {
1888                                 LCONSOLE_ERROR_MSG(0x13a, "Failed to get MGS "
1889                                                    "log %s and no local copy."
1890                                                    "\n", cld->cld_logname);
1891                                 GOTO(out_pop, rc = -ENOENT);
1892                         }
1893                         CDEBUG(D_MGC, "Failed to get MGS log %s, using local "
1894                                "copy for now, will try to update later.\n",
1895                                cld->cld_logname);
1896                         rc = 0;
1897                 }
1898                 /* Now, whether we copied or not, start using the local llog.
1899                  * If we failed to copy, we'll start using whatever the old
1900                  * log has. */
1901                 llog_ctxt_put(ctxt);
1902                 ctxt = lctxt;
1903                 lctxt = NULL;
1904         } else {
1905                 if (local_only) /* no local log at client side */
1906                         GOTO(out_pop, rc = -EIO);
1907         }
1908
1909         if (cld_is_sptlrpc(cld)) {
1910                 sptlrpc_conf_log_update_begin(cld->cld_logname);
1911                 sptlrpc_started = true;
1912         }
1913
1914         /* logname and instance info should be the same, so use our
1915          * copy of the instance for the update.  The cfg_last_idx will
1916          * be updated here. */
1917         rc = class_config_parse_llog(env, ctxt, cld->cld_logname,
1918                                      &cld->cld_cfg);
1919         EXIT;
1920
1921 out_pop:
1922         __llog_ctxt_put(env, ctxt);
1923         if (lctxt)
1924                 __llog_ctxt_put(env, lctxt);
1925
1926         /*
1927          * update settings on existing OBDs. doing it inside
1928          * of llog_process_lock so no device is attaching/detaching
1929          * in parallel.
1930          * the logname must be <fsname>-sptlrpc
1931          */
1932         if (sptlrpc_started) {
1933                 LASSERT(cld_is_sptlrpc(cld));
1934                 sptlrpc_conf_log_update_end(cld->cld_logname);
1935                 class_notify_sptlrpc_conf(cld->cld_logname,
1936                                           strlen(cld->cld_logname) -
1937                                           strlen("-sptlrpc"));
1938         }
1939
1940         lu_env_fini(env);
1941 out_free:
1942         OBD_FREE_PTR(env);
1943         return rc;
1944 }
1945
1946 static bool mgc_import_in_recovery(struct obd_import *imp)
1947 {
1948         bool in_recovery = true;
1949
1950         spin_lock(&imp->imp_lock);
1951         if (imp->imp_state == LUSTRE_IMP_FULL ||
1952             imp->imp_state == LUSTRE_IMP_CLOSED)
1953                 in_recovery = false;
1954         spin_unlock(&imp->imp_lock);
1955
1956         return in_recovery;
1957 }
1958
1959 /**
1960  * Get a configuration log from the MGS and process it.
1961  *
1962  * This function is called for both clients and servers to process the
1963  * configuration log from the MGS.  The MGC enqueues a DLM lock on the
1964  * log from the MGS, and if the lock gets revoked the MGC will be notified
1965  * by the lock cancellation callback that the config log has changed,
1966  * and will enqueue another MGS lock on it, and then continue processing
1967  * the new additions to the end of the log.
1968  *
1969  * Since the MGC import is not replayable, if the import is being evicted
1970  * (rcl == -ESHUTDOWN, \see ptlrpc_import_delay_req()), retry to process
1971  * the log until recovery is finished or the import is closed.
1972  *
1973  * Make a local copy of the log before parsing it if appropriate (non-MGS
1974  * server) so that the server can start even when the MGS is down.
1975  *
1976  * There shouldn't be multiple processes running process_log at once --
1977  * sounds like badness.  It actually might be fine, as long as they're not
1978  * trying to update from the same log simultaneously, in which case we
1979  * should use a per-log semaphore instead of cld_lock.
1980  *
1981  * \param[in] mgc       MGC device by which to fetch the configuration log
1982  * \param[in] cld       log processing state (stored in lock callback data)
1983  *
1984  * \retval              0 on success
1985  * \retval              negative errno on failure
1986  */
1987 int mgc_process_log(struct obd_device *mgc, struct config_llog_data *cld)
1988 {
1989         struct lustre_handle lockh = { 0 };
1990         __u64 flags = LDLM_FL_NO_LRU;
1991         int rc = 0, rcl;
1992         bool retry = false;
1993         ENTRY;
1994
1995         LASSERT(cld != NULL);
1996
1997         /* I don't want multiple processes running process_log at once --
1998            sounds like badness.  It actually might be fine, as long as
1999            we're not trying to update from the same log
2000            simultaneously (in which case we should use a per-log sem.) */
2001 restart:
2002         mutex_lock(&cld->cld_lock);
2003         if (cld->cld_stopping) {
2004                 mutex_unlock(&cld->cld_lock);
2005                 RETURN(0);
2006         }
2007
2008         OBD_FAIL_TIMEOUT(OBD_FAIL_MGC_PAUSE_PROCESS_LOG, 20);
2009
2010         CDEBUG(D_MGC, "Process log %s:%p from %d\n", cld->cld_logname,
2011                cld->cld_cfg.cfg_instance, cld->cld_cfg.cfg_last_idx + 1);
2012
2013         /* Get the cfg lock on the llog */
2014         rcl = mgc_enqueue(mgc->u.cli.cl_mgc_mgsexp, LDLM_PLAIN, NULL,
2015                           LCK_CR, &flags, NULL, NULL, NULL,
2016                           cld, 0, NULL, &lockh);
2017         if (rcl == 0) {
2018                 /* Get the cld, it will be released in mgc_blocking_ast. */
2019                 config_log_get(cld);
2020                 rc = ldlm_lock_set_data(&lockh, (void *)cld);
2021                 LASSERT(rc == 0);
2022         } else {
2023                 CDEBUG(D_MGC, "Can't get cfg lock: %d\n", rcl);
2024
2025                 if (rcl == -ESHUTDOWN &&
2026                     atomic_read(&mgc->u.cli.cl_mgc_refcount) > 0 && !retry) {
2027                         struct obd_import *imp;
2028                         struct l_wait_info lwi;
2029                         int secs = cfs_time_seconds(obd_timeout);
2030
2031                         mutex_unlock(&cld->cld_lock);
2032                         imp = class_exp2cliimp(mgc->u.cli.cl_mgc_mgsexp);
2033
2034                         /* Let's force the pinger, and wait the import to be
2035                          * connected, note: since mgc import is non-replayable,
2036                          * and even the import state is disconnected, it does
2037                          * not mean the "recovery" is stopped, so we will keep
2038                          * waitting until timeout or the import state is
2039                          * FULL or closed */
2040                         ptlrpc_pinger_force(imp);
2041
2042                         lwi = LWI_TIMEOUT(secs, NULL, NULL);
2043                         l_wait_event(imp->imp_recovery_waitq,
2044                                      !mgc_import_in_recovery(imp), &lwi);
2045
2046                         if (imp->imp_state == LUSTRE_IMP_FULL) {
2047                                 retry = true;
2048                                 goto restart;
2049                         } else {
2050                                 mutex_lock(&cld->cld_lock);
2051                                 spin_lock(&config_list_lock);
2052                                 cld->cld_lostlock = 1;
2053                                 spin_unlock(&config_list_lock);
2054                         }
2055                 } else {
2056                         /* mark cld_lostlock so that it will requeue
2057                          * after MGC becomes available. */
2058                         spin_lock(&config_list_lock);
2059                         cld->cld_lostlock = 1;
2060                         spin_unlock(&config_list_lock);
2061                 }
2062         }
2063
2064         if (cld_is_recover(cld) || cld_is_nodemap(cld)) {
2065                 if (!rcl)
2066                         rc = mgc_process_recover_nodemap_log(mgc, cld);
2067                 else if (cld_is_nodemap(cld))
2068                         rc = rcl;
2069
2070                 if (cld_is_recover(cld) && rc) {
2071                         if (!rcl) {
2072                                 CERROR("%s: recover log %s failed, not fatal: rc = %d\n",
2073                                        mgc->obd_name, cld->cld_logname, rc);
2074                                 spin_lock(&config_list_lock);
2075                                 cld->cld_lostlock = 1;
2076                                 spin_unlock(&config_list_lock);
2077                         }
2078                         rc = 0; /* this is not a fatal error for recover log */
2079                 }
2080         } else {
2081                 rc = mgc_process_cfg_log(mgc, cld, rcl != 0);
2082         }
2083
2084         CDEBUG(D_MGC, "%s: configuration from log '%s' %sed (%d).\n",
2085                mgc->obd_name, cld->cld_logname, rc ? "fail" : "succeed", rc);
2086
2087         mutex_unlock(&cld->cld_lock);
2088
2089         /* Now drop the lock so MGS can revoke it */
2090         if (!rcl) {
2091                 rcl = mgc_cancel(mgc->u.cli.cl_mgc_mgsexp, LCK_CR, &lockh);
2092                 if (rcl)
2093                         CERROR("Can't drop cfg lock: %d\n", rcl);
2094         }
2095
2096         RETURN(rc);
2097 }
2098
2099
2100 /** Called from lustre_process_log.
2101  * LCFG_LOG_START gets the config log from the MGS, processes it to start
2102  * any services, and adds it to the list logs to watch (follow).
2103  */
2104 static int mgc_process_config(struct obd_device *obd, size_t len, void *buf)
2105 {
2106         struct lustre_cfg *lcfg = buf;
2107         struct config_llog_instance *cfg = NULL;
2108         char *logname;
2109         int rc = 0;
2110         ENTRY;
2111
2112         switch(lcfg->lcfg_command) {
2113         case LCFG_LOV_ADD_OBD: {
2114                 /* Overloading this cfg command: register a new target */
2115                 struct mgs_target_info *mti;
2116
2117                 if (LUSTRE_CFG_BUFLEN(lcfg, 1) !=
2118                     sizeof(struct mgs_target_info))
2119                         GOTO(out, rc = -EINVAL);
2120
2121                 mti = (struct mgs_target_info *)lustre_cfg_buf(lcfg, 1);
2122                 CDEBUG(D_MGC, "add_target %s %#x\n",
2123                        mti->mti_svname, mti->mti_flags);
2124                 rc = mgc_target_register(obd->u.cli.cl_mgc_mgsexp, mti);
2125                 break;
2126         }
2127         case LCFG_LOV_DEL_OBD:
2128                 /* Unregister has no meaning at the moment. */
2129                 CERROR("lov_del_obd unimplemented\n");
2130                 rc = -ENOSYS;
2131                 break;
2132         case LCFG_SPTLRPC_CONF: {
2133                 rc = sptlrpc_process_config(lcfg);
2134                 break;
2135         }
2136         case LCFG_LOG_START: {
2137                 struct config_llog_data *cld;
2138                 struct super_block *sb;
2139
2140                 logname = lustre_cfg_string(lcfg, 1);
2141                 cfg = (struct config_llog_instance *)lustre_cfg_buf(lcfg, 2);
2142                 sb = *(struct super_block **)lustre_cfg_buf(lcfg, 3);
2143
2144                 CDEBUG(D_MGC, "parse_log %s from %d\n", logname,
2145                        cfg->cfg_last_idx);
2146
2147                 /* We're only called through here on the initial mount */
2148                 cld = config_log_add(obd, logname, cfg, sb);
2149                 if (IS_ERR(cld)) {
2150                         rc = PTR_ERR(cld);
2151                         break;
2152                 }
2153
2154                 /* COMPAT_146 */
2155                 /* FIXME only set this for old logs!  Right now this forces
2156                    us to always skip the "inside markers" check */
2157                 cld->cld_cfg.cfg_flags |= CFG_F_COMPAT146;
2158
2159                 rc = mgc_process_log(obd, cld);
2160                 if (rc == 0 && cld->cld_recover != NULL) {
2161                         if (OCD_HAS_FLAG(&obd->u.cli.cl_import->
2162                                          imp_connect_data, IMP_RECOV)) {
2163                                 rc = mgc_process_log(obd, cld->cld_recover);
2164                         } else {
2165                                 struct config_llog_data *cir;
2166
2167                                 mutex_lock(&cld->cld_lock);
2168                                 cir = cld->cld_recover;
2169                                 cld->cld_recover = NULL;
2170                                 mutex_unlock(&cld->cld_lock);
2171                                 config_log_put(cir);
2172                         }
2173
2174                         if (rc)
2175                                 CERROR("Cannot process recover llog %d\n", rc);
2176                 }
2177
2178                 if (rc == 0 && cld->cld_params != NULL) {
2179                         rc = mgc_process_log(obd, cld->cld_params);
2180                         if (rc == -ENOENT) {
2181                                 CDEBUG(D_MGC, "There is no params "
2182                                               "config file yet\n");
2183                                 rc = 0;
2184                         }
2185                         /* params log is optional */
2186                         if (rc)
2187                                 CERROR("%s: can't process params llog: rc = %d\n",
2188                                        obd->obd_name, rc);
2189                 }
2190
2191                 break;
2192         }
2193         case LCFG_LOG_END: {
2194                 logname = lustre_cfg_string(lcfg, 1);
2195
2196                 if (lcfg->lcfg_bufcount >= 2)
2197                         cfg = (struct config_llog_instance *)lustre_cfg_buf(
2198                                 lcfg, 2);
2199                 rc = config_log_end(logname, cfg);
2200                 break;
2201         }
2202         default: {
2203                 CERROR("Unknown command: %d\n", lcfg->lcfg_command);
2204                 GOTO(out, rc = -EINVAL);
2205
2206         }
2207         }
2208 out:
2209         RETURN(rc);
2210 }
2211
2212 static struct obd_ops mgc_obd_ops = {
2213         .o_owner        = THIS_MODULE,
2214         .o_setup        = mgc_setup,
2215         .o_precleanup   = mgc_precleanup,
2216         .o_cleanup      = mgc_cleanup,
2217         .o_add_conn     = client_import_add_conn,
2218         .o_del_conn     = client_import_del_conn,
2219         .o_connect      = client_connect_import,
2220         .o_disconnect   = client_disconnect_export,
2221         .o_set_info_async = mgc_set_info_async,
2222         .o_get_info       = mgc_get_info,
2223         .o_import_event = mgc_import_event,
2224         .o_process_config = mgc_process_config,
2225 };
2226
2227 static int __init mgc_init(void)
2228 {
2229         return class_register_type(&mgc_obd_ops, NULL, true, NULL,
2230                                    LUSTRE_MGC_NAME, NULL);
2231 }
2232
2233 static void __exit mgc_exit(void)
2234 {
2235         class_unregister_type(LUSTRE_MGC_NAME);
2236 }
2237
2238 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
2239 MODULE_DESCRIPTION("Lustre Management Client");
2240 MODULE_VERSION(LUSTRE_VERSION_STRING);
2241 MODULE_LICENSE("GPL");
2242
2243 module_init(mgc_init);
2244 module_exit(mgc_exit);