Whamcloud - gitweb
3e88d496cbad48fb469de50f5d43ea2dbb65aebb
[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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2016, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/mgc/mgc_request.c
33  *
34  * Author: Nathan Rutman <nathan@clusterfs.com>
35  */
36
37 #define DEBUG_SUBSYSTEM S_MGC
38 #define D_MGC D_CONFIG /*|D_WARNING*/
39
40 #include <linux/module.h>
41 #include <linux/kthread.h>
42
43 #include <dt_object.h>
44 #include <lprocfs_status.h>
45 #include <lustre_dlm.h>
46 #include <lustre_disk.h>
47 #include <lustre_log.h>
48 #include <lustre_nodemap.h>
49 #include <lustre_swab.h>
50 #include <obd_class.h>
51
52 #include "mgc_internal.h"
53
54 static int mgc_name2resid(char *name, int len, struct ldlm_res_id *res_id,
55                           int type)
56 {
57         __u64 resname = 0;
58
59         if (len > sizeof(resname)) {
60                 CERROR("name too long: %s\n", name);
61                 return -EINVAL;
62         }
63         if (len <= 0) {
64                 CERROR("missing name: %s\n", name);
65                 return -EINVAL;
66         }
67         memcpy(&resname, name, len);
68
69         /* Always use the same endianness for the resid */
70         memset(res_id, 0, sizeof(*res_id));
71         res_id->name[0] = cpu_to_le64(resname);
72         /* XXX: unfortunately, sptlprc and config llog share one lock */
73         switch(type) {
74         case CONFIG_T_CONFIG:
75         case CONFIG_T_SPTLRPC:
76                 resname = 0;
77                 break;
78         case CONFIG_T_RECOVER:
79         case CONFIG_T_PARAMS:
80         case CONFIG_T_NODEMAP:
81                 resname = type;
82                 break;
83         default:
84                 LBUG();
85         }
86         res_id->name[1] = cpu_to_le64(resname);
87         CDEBUG(D_MGC, "log %s to resid %#llx/%#llx (%.8s)\n", name,
88                res_id->name[0], res_id->name[1], (char *)&res_id->name[0]);
89         return 0;
90 }
91
92 int mgc_fsname2resid(char *fsname, struct ldlm_res_id *res_id, int type)
93 {
94         /* fsname is at most 8 chars long, maybe contain "-".
95          * e.g. "lustre", "SUN-000" */
96         return mgc_name2resid(fsname, strlen(fsname), res_id, type);
97 }
98 EXPORT_SYMBOL(mgc_fsname2resid);
99
100 static int mgc_logname2resid(char *logname, struct ldlm_res_id *res_id,
101                              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          * there is an exception: llog "params" */
109         name_end = strrchr(logname, '-');
110         if (!name_end)
111                 len = strlen(logname);
112         else
113                 len = name_end - logname;
114         return mgc_name2resid(logname, len, res_id, type);
115 }
116
117 /********************** config llog list **********************/
118 static struct list_head config_llog_list = LIST_HEAD_INIT(config_llog_list);
119 static DEFINE_SPINLOCK(config_list_lock);
120
121 /* Take a reference to a config log */
122 static int config_log_get(struct config_llog_data *cld)
123 {
124         ENTRY;
125         atomic_inc(&cld->cld_refcount);
126         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
127                 atomic_read(&cld->cld_refcount));
128         RETURN(0);
129 }
130
131 /* Drop a reference to a config log.  When no longer referenced,
132    we can free the config log data */
133 static void config_log_put(struct config_llog_data *cld)
134 {
135         ENTRY;
136
137         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
138                 atomic_read(&cld->cld_refcount));
139         LASSERT(atomic_read(&cld->cld_refcount) > 0);
140
141         /* spinlock to make sure no item with 0 refcount in the list */
142         if (atomic_dec_and_lock(&cld->cld_refcount, &config_list_lock)) {
143                 list_del(&cld->cld_list_chain);
144                 spin_unlock(&config_list_lock);
145
146                 CDEBUG(D_MGC, "dropping config log %s\n", cld->cld_logname);
147
148                 if (cld->cld_recover)
149                         config_log_put(cld->cld_recover);
150                 if (cld->cld_params)
151                         config_log_put(cld->cld_params);
152                 if (cld->cld_nodemap)
153                         config_log_put(cld->cld_nodemap);
154                 if (cld->cld_sptlrpc)
155                         config_log_put(cld->cld_sptlrpc);
156                 if (cld_is_sptlrpc(cld))
157                         sptlrpc_conf_log_stop(cld->cld_logname);
158
159                 class_export_put(cld->cld_mgcexp);
160                 OBD_FREE(cld, sizeof(*cld) + strlen(cld->cld_logname) + 1);
161         }
162
163         EXIT;
164 }
165
166 /* Find a config log by name */
167 static
168 struct config_llog_data *config_log_find(char *logname,
169                                          struct config_llog_instance *cfg)
170 {
171         struct config_llog_data *cld;
172         struct config_llog_data *found = NULL;
173         void *                   instance;
174         ENTRY;
175
176         LASSERT(logname != NULL);
177
178         instance = cfg ? cfg->cfg_instance : NULL;
179         spin_lock(&config_list_lock);
180         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
181                 /* check if instance equals */
182                 if (instance != cld->cld_cfg.cfg_instance)
183                         continue;
184
185                 /* instance may be NULL, should check name */
186                 if (strcmp(logname, cld->cld_logname) == 0) {
187                         found = cld;
188                         config_log_get(found);
189                         break;
190                 }
191         }
192         spin_unlock(&config_list_lock);
193         RETURN(found);
194 }
195
196 static
197 struct config_llog_data *do_config_log_add(struct obd_device *obd,
198                                            char *logname,
199                                            int type,
200                                            struct config_llog_instance *cfg,
201                                            struct super_block *sb)
202 {
203         struct config_llog_data *cld;
204         int rc;
205
206         ENTRY;
207
208         CDEBUG(D_MGC, "do adding config log %s:%p\n", logname,
209                cfg ? cfg->cfg_instance : NULL);
210
211         OBD_ALLOC(cld, sizeof(*cld) + strlen(logname) + 1);
212         if (!cld)
213                 RETURN(ERR_PTR(-ENOMEM));
214
215         rc = mgc_logname2resid(logname, &cld->cld_resid, type);
216         if (rc) {
217                 OBD_FREE(cld, sizeof(*cld) + strlen(cld->cld_logname) + 1);
218                 RETURN(ERR_PTR(rc));
219         }
220
221         strcpy(cld->cld_logname, logname);
222         if (cfg)
223                 cld->cld_cfg = *cfg;
224         else
225                 cld->cld_cfg.cfg_callback = class_config_llog_handler;
226         mutex_init(&cld->cld_lock);
227         cld->cld_cfg.cfg_last_idx = 0;
228         cld->cld_cfg.cfg_flags = 0;
229         cld->cld_cfg.cfg_sb = sb;
230         cld->cld_type = type;
231         atomic_set(&cld->cld_refcount, 1);
232
233         /* Keep the mgc around until we are done */
234         cld->cld_mgcexp = class_export_get(obd->obd_self_export);
235
236         if (cld_is_sptlrpc(cld)) {
237                 sptlrpc_conf_log_start(logname);
238                 cld->cld_cfg.cfg_obdname = obd->obd_name;
239         }
240
241         spin_lock(&config_list_lock);
242         list_add(&cld->cld_list_chain, &config_llog_list);
243         spin_unlock(&config_list_lock);
244
245         if (cld_is_sptlrpc(cld) || cld_is_nodemap(cld)) {
246                 rc = mgc_process_log(obd, cld);
247                 if (rc && rc != -ENOENT)
248                         CERROR("%s: failed processing log, type %d: rc = %d\n",
249                                obd->obd_name, type, rc);
250         }
251
252         RETURN(cld);
253 }
254
255 static struct config_llog_data *config_recover_log_add(struct obd_device *obd,
256         char *fsname,
257         struct config_llog_instance *cfg,
258         struct super_block *sb)
259 {
260         struct config_llog_instance lcfg = *cfg;
261         struct lustre_sb_info *lsi = s2lsi(sb);
262         struct config_llog_data *cld;
263         char logname[32];
264
265         if (IS_OST(lsi))
266                 return NULL;
267
268         /* for osp-on-ost, see lustre_start_osp() */
269         if (IS_MDT(lsi) && lcfg.cfg_instance)
270                 return NULL;
271
272         /* we have to use different llog for clients and mdts for cmd
273          * where only clients are notified if one of cmd server restarts */
274         LASSERT(strlen(fsname) < sizeof(logname) / 2);
275         strcpy(logname, fsname);
276         if (IS_SERVER(lsi)) { /* mdt */
277                 LASSERT(lcfg.cfg_instance == NULL);
278                 lcfg.cfg_instance = sb;
279                 strcat(logname, "-mdtir");
280         } else {
281                 LASSERT(lcfg.cfg_instance != NULL);
282                 strcat(logname, "-cliir");
283         }
284
285         cld = do_config_log_add(obd, logname, CONFIG_T_RECOVER, &lcfg, sb);
286         return cld;
287 }
288
289 static struct config_llog_data *config_log_find_or_add(struct obd_device *obd,
290                                 char *logname, struct super_block *sb, int type,
291                                 struct config_llog_instance *cfg)
292 {
293         struct config_llog_instance     lcfg = *cfg;
294         struct config_llog_data         *cld;
295
296         lcfg.cfg_instance = sb != NULL ? (void *)sb : (void *)obd;
297         cld = config_log_find(logname, &lcfg);
298         if (unlikely(cld != NULL))
299                 return cld;
300
301         return do_config_log_add(obd, logname, type, &lcfg, sb);
302 }
303
304 /** Add this log to the list of active logs watched by an MGC.
305  * Active means we're watching for updates.
306  * We have one active log per "mount" - client instance or servername.
307  * Each instance may be at a different point in the log.
308  */
309 static struct config_llog_data *
310 config_log_add(struct obd_device *obd, char *logname,
311                struct config_llog_instance *cfg, struct super_block *sb)
312 {
313         struct lustre_sb_info *lsi = s2lsi(sb);
314         struct config_llog_data *cld;
315         struct config_llog_data *sptlrpc_cld = NULL;
316         struct config_llog_data *params_cld = NULL;
317         struct config_llog_data *nodemap_cld = NULL;
318         char seclogname[32];
319         char *ptr;
320         int rc;
321         bool locked = false;
322         ENTRY;
323
324         CDEBUG(D_MGC, "adding config log %s:%p\n", logname, cfg->cfg_instance);
325
326         /*
327          * for each regular log, the depended sptlrpc log name is
328          * <fsname>-sptlrpc. multiple regular logs may share one sptlrpc log.
329          */
330         ptr = strrchr(logname, '-');
331         if (ptr == NULL || ptr - logname > 8) {
332                 CERROR("logname %s is too long\n", logname);
333                 RETURN(ERR_PTR(-EINVAL));
334         }
335
336         memcpy(seclogname, logname, ptr - logname);
337         strcpy(seclogname + (ptr - logname), "-sptlrpc");
338
339         if (cfg->cfg_sub_clds & CONFIG_T_SPTLRPC) {
340                 sptlrpc_cld = config_log_find_or_add(obd, seclogname, NULL,
341                                                      CONFIG_T_SPTLRPC, cfg);
342                 if (IS_ERR(sptlrpc_cld)) {
343                         CERROR("can't create sptlrpc log: %s\n", seclogname);
344                         GOTO(out, rc = PTR_ERR(sptlrpc_cld));
345                 }
346         }
347
348         if (!IS_MGS(lsi) && cfg->cfg_sub_clds & CONFIG_T_NODEMAP) {
349                 nodemap_cld = config_log_find_or_add(obd, LUSTRE_NODEMAP_NAME,
350                                                      NULL, CONFIG_T_NODEMAP,
351                                                      cfg);
352                 if (IS_ERR(nodemap_cld)) {
353                         rc = PTR_ERR(nodemap_cld);
354                         CERROR("%s: cannot create nodemap log: rc = %d\n",
355                                obd->obd_name, rc);
356                         GOTO(out_sptlrpc, rc);
357                 }
358         }
359
360         if (cfg->cfg_sub_clds & CONFIG_T_PARAMS) {
361                 params_cld = config_log_find_or_add(obd, PARAMS_FILENAME, sb,
362                                                     CONFIG_T_PARAMS, cfg);
363                 if (IS_ERR(params_cld)) {
364                         rc = PTR_ERR(params_cld);
365                         CERROR("%s: can't create params log: rc = %d\n",
366                                obd->obd_name, rc);
367                         GOTO(out_nodemap, rc);
368                 }
369         }
370
371         cld = do_config_log_add(obd, logname, CONFIG_T_CONFIG, cfg, sb);
372         if (IS_ERR(cld)) {
373                 CERROR("can't create log: %s\n", logname);
374                 GOTO(out_params, rc = PTR_ERR(cld));
375         }
376
377         LASSERT(lsi->lsi_lmd);
378         if (!(lsi->lsi_lmd->lmd_flags & LMD_FLG_NOIR) &&
379             cfg->cfg_sub_clds & CONFIG_T_RECOVER) {
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 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 13, 53, 0)
1043 /* Send parameter to MGS*/
1044 static int mgc_set_mgs_param(struct obd_export *exp,
1045                              struct mgs_send_param *msp)
1046 {
1047         struct ptlrpc_request *req;
1048         struct mgs_send_param *req_msp, *rep_msp;
1049         int rc;
1050         ENTRY;
1051
1052         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1053                                         &RQF_MGS_SET_INFO, LUSTRE_MGS_VERSION,
1054                                         MGS_SET_INFO);
1055         if (!req)
1056                 RETURN(-ENOMEM);
1057
1058         req_msp = req_capsule_client_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
1059         if (!req_msp) {
1060                 ptlrpc_req_finished(req);
1061                 RETURN(-ENOMEM);
1062         }
1063
1064         memcpy(req_msp, msp, sizeof(*req_msp));
1065         ptlrpc_request_set_replen(req);
1066
1067         /* Limit how long we will wait for the enqueue to complete */
1068         req->rq_delay_limit = MGC_SEND_PARAM_LIMIT;
1069         rc = ptlrpc_queue_wait(req);
1070         if (!rc) {
1071                 rep_msp = req_capsule_server_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
1072                 memcpy(msp, rep_msp, sizeof(*rep_msp));
1073         }
1074
1075         ptlrpc_req_finished(req);
1076
1077         RETURN(rc);
1078 }
1079 #endif
1080
1081 /* Take a config lock so we can get cancel notifications */
1082 static int mgc_enqueue(struct obd_export *exp, enum ldlm_type type,
1083                        union ldlm_policy_data *policy, enum ldlm_mode mode,
1084                        __u64 *flags, void *bl_cb, void *cp_cb, void *gl_cb,
1085                        void *data, __u32 lvb_len, void *lvb_swabber,
1086                        struct lustre_handle *lockh)
1087 {
1088         struct config_llog_data *cld = (struct config_llog_data *)data;
1089         struct ldlm_enqueue_info einfo = {
1090                 .ei_type        = type,
1091                 .ei_mode        = mode,
1092                 .ei_cb_bl       = mgc_blocking_ast,
1093                 .ei_cb_cp       = ldlm_completion_ast,
1094         };
1095         struct ptlrpc_request *req;
1096         int short_limit = cld_is_sptlrpc(cld);
1097         int rc;
1098         ENTRY;
1099
1100         CDEBUG(D_MGC, "Enqueue for %s (res %#llx)\n", cld->cld_logname,
1101                cld->cld_resid.name[0]);
1102
1103         /* We need a callback for every lockholder, so don't try to
1104            ldlm_lock_match (see rev 1.1.2.11.2.47) */
1105         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1106                                         &RQF_LDLM_ENQUEUE, LUSTRE_DLM_VERSION,
1107                                         LDLM_ENQUEUE);
1108         if (req == NULL)
1109                 RETURN(-ENOMEM);
1110
1111         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER, 0);
1112         ptlrpc_request_set_replen(req);
1113
1114         /* check if this is server or client */
1115         if (cld->cld_cfg.cfg_sb) {
1116                 struct lustre_sb_info *lsi = s2lsi(cld->cld_cfg.cfg_sb);
1117                 if (lsi && IS_SERVER(lsi))
1118                         short_limit = 1;
1119         }
1120         /* Limit how long we will wait for the enqueue to complete */
1121         req->rq_delay_limit = short_limit ? 5 : MGC_ENQUEUE_LIMIT;
1122         rc = ldlm_cli_enqueue(exp, &req, &einfo, &cld->cld_resid, NULL, flags,
1123                               NULL, 0, LVB_T_NONE, lockh, 0);
1124         /* A failed enqueue should still call the mgc_blocking_ast,
1125            where it will be requeued if needed ("grant failed"). */
1126         ptlrpc_req_finished(req);
1127         RETURN(rc);
1128 }
1129
1130 static int mgc_cancel(struct obd_export *exp, enum ldlm_mode mode,
1131                       struct lustre_handle *lockh)
1132 {
1133         ENTRY;
1134
1135         ldlm_lock_decref(lockh, mode);
1136
1137         RETURN(0);
1138 }
1139
1140 static void mgc_notify_active(struct obd_device *unused)
1141 {
1142         /* wakeup mgc_requeue_thread to requeue mgc lock */
1143         spin_lock(&config_list_lock);
1144         rq_state |= RQ_NOW;
1145         spin_unlock(&config_list_lock);
1146         wake_up(&rq_waitq);
1147
1148         /* TODO: Help the MGS rebuild nidtbl. -jay */
1149 }
1150
1151 /* Send target_reg message to MGS */
1152 static int mgc_target_register(struct obd_export *exp,
1153                                struct mgs_target_info *mti)
1154 {
1155         struct ptlrpc_request  *req;
1156         struct mgs_target_info *req_mti, *rep_mti;
1157         int                     rc;
1158         ENTRY;
1159
1160         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1161                                         &RQF_MGS_TARGET_REG, LUSTRE_MGS_VERSION,
1162                                         MGS_TARGET_REG);
1163         if (req == NULL)
1164                 RETURN(-ENOMEM);
1165
1166         req_mti = req_capsule_client_get(&req->rq_pill, &RMF_MGS_TARGET_INFO);
1167         if (!req_mti) {
1168                 ptlrpc_req_finished(req);
1169                 RETURN(-ENOMEM);
1170         }
1171
1172         memcpy(req_mti, mti, sizeof(*req_mti));
1173         ptlrpc_request_set_replen(req);
1174         CDEBUG(D_MGC, "register %s\n", mti->mti_svname);
1175         /* Limit how long we will wait for the enqueue to complete */
1176         req->rq_delay_limit = MGC_TARGET_REG_LIMIT;
1177
1178         rc = ptlrpc_queue_wait(req);
1179         if (!rc) {
1180                 rep_mti = req_capsule_server_get(&req->rq_pill,
1181                                                  &RMF_MGS_TARGET_INFO);
1182                 memcpy(mti, rep_mti, sizeof(*rep_mti));
1183                 CDEBUG(D_MGC, "register %s got index = %d\n",
1184                        mti->mti_svname, mti->mti_stripe_index);
1185         }
1186         ptlrpc_req_finished(req);
1187
1188         RETURN(rc);
1189 }
1190
1191 static int mgc_set_info_async(const struct lu_env *env, struct obd_export *exp,
1192                               u32 keylen, void *key,
1193                               u32 vallen, void *val,
1194                               struct ptlrpc_request_set *set)
1195 {
1196         int rc = -EINVAL;
1197         ENTRY;
1198
1199         /* Turn off initial_recov after we try all backup servers once */
1200         if (KEY_IS(KEY_INIT_RECOV_BACKUP)) {
1201                 struct obd_import *imp = class_exp2cliimp(exp);
1202                 int value;
1203                 if (vallen != sizeof(int))
1204                         RETURN(-EINVAL);
1205                 value = *(int *)val;
1206                 CDEBUG(D_MGC, "InitRecov %s %d/d%d:i%d:r%d:or%d:%s\n",
1207                        imp->imp_obd->obd_name, value,
1208                        imp->imp_deactive, imp->imp_invalid,
1209                        imp->imp_replayable, imp->imp_obd->obd_replayable,
1210                        ptlrpc_import_state_name(imp->imp_state));
1211                 /* Resurrect if we previously died */
1212                 if ((imp->imp_state != LUSTRE_IMP_FULL &&
1213                      imp->imp_state != LUSTRE_IMP_NEW) || value > 1)
1214                         ptlrpc_reconnect_import(imp);
1215                 RETURN(0);
1216         }
1217         /* FIXME move this to mgc_process_config */
1218         if (KEY_IS(KEY_REGISTER_TARGET)) {
1219                 struct mgs_target_info *mti;
1220                 if (vallen != sizeof(struct mgs_target_info))
1221                         RETURN(-EINVAL);
1222                 mti = (struct mgs_target_info *)val;
1223                 CDEBUG(D_MGC, "register_target %s %#x\n",
1224                        mti->mti_svname, mti->mti_flags);
1225                 rc =  mgc_target_register(exp, mti);
1226                 RETURN(rc);
1227         }
1228         if (KEY_IS(KEY_SET_FS)) {
1229                 struct super_block *sb = (struct super_block *)val;
1230
1231                 if (vallen != sizeof(struct super_block))
1232                         RETURN(-EINVAL);
1233
1234                 rc = mgc_fs_setup(env, exp->exp_obd, sb);
1235                 RETURN(rc);
1236         }
1237         if (KEY_IS(KEY_CLEAR_FS)) {
1238                 if (vallen != 0)
1239                         RETURN(-EINVAL);
1240                 rc = mgc_fs_cleanup(env, exp->exp_obd);
1241                 RETURN(rc);
1242         }
1243 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 13, 53, 0)
1244         if (KEY_IS(KEY_SET_INFO)) {
1245                 struct mgs_send_param *msp;
1246
1247                 msp = (struct mgs_send_param *)val;
1248                 rc =  mgc_set_mgs_param(exp, msp);
1249                 RETURN(rc);
1250         }
1251 #endif
1252         if (KEY_IS(KEY_MGSSEC)) {
1253                 struct client_obd     *cli = &exp->exp_obd->u.cli;
1254                 struct sptlrpc_flavor  flvr;
1255
1256                 /*
1257                  * empty string means using current flavor, if which haven't
1258                  * been set yet, set it as null.
1259                  *
1260                  * if flavor has been set previously, check the asking flavor
1261                  * must match the existing one.
1262                  */
1263                 if (vallen == 0) {
1264                         if (cli->cl_flvr_mgc.sf_rpc != SPTLRPC_FLVR_INVALID)
1265                                 RETURN(0);
1266                         val = "null";
1267                         vallen = 4;
1268                 }
1269
1270                 rc = sptlrpc_parse_flavor(val, &flvr);
1271                 if (rc) {
1272                         CERROR("invalid sptlrpc flavor %s to MGS\n",
1273                                (char *) val);
1274                         RETURN(rc);
1275                 }
1276
1277                 /*
1278                  * caller already hold a mutex
1279                  */
1280                 if (cli->cl_flvr_mgc.sf_rpc == SPTLRPC_FLVR_INVALID) {
1281                         cli->cl_flvr_mgc = flvr;
1282                 } else if (memcmp(&cli->cl_flvr_mgc, &flvr,
1283                                   sizeof(flvr)) != 0) {
1284                         char    str[20];
1285
1286                         sptlrpc_flavor2name(&cli->cl_flvr_mgc,
1287                                             str, sizeof(str));
1288                         LCONSOLE_ERROR("asking sptlrpc flavor %s to MGS but "
1289                                        "currently %s is in use\n",
1290                                        (char *) val, str);
1291                         rc = -EPERM;
1292                 }
1293                 RETURN(rc);
1294         }
1295
1296         RETURN(rc);
1297 }
1298
1299 static int mgc_get_info(const struct lu_env *env, struct obd_export *exp,
1300                         __u32 keylen, void *key, __u32 *vallen, void *val)
1301 {
1302         int rc = -EINVAL;
1303
1304         if (KEY_IS(KEY_CONN_DATA)) {
1305                 struct obd_import *imp = class_exp2cliimp(exp);
1306                 struct obd_connect_data *data = val;
1307
1308                 if (*vallen == sizeof(*data)) {
1309                         *data = imp->imp_connect_data;
1310                         rc = 0;
1311                 }
1312         }
1313
1314         return rc;
1315 }
1316
1317 static int mgc_import_event(struct obd_device *obd,
1318                             struct obd_import *imp,
1319                             enum obd_import_event event)
1320 {
1321         int rc = 0;
1322
1323         LASSERT(imp->imp_obd == obd);
1324         CDEBUG(D_MGC, "import event %#x\n", event);
1325
1326         switch (event) {
1327         case IMP_EVENT_DISCON:
1328                 /* MGC imports should not wait for recovery */
1329                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1330                         ptlrpc_pinger_ir_down();
1331                 break;
1332         case IMP_EVENT_INACTIVE:
1333                 break;
1334         case IMP_EVENT_INVALIDATE: {
1335                 struct ldlm_namespace *ns = obd->obd_namespace;
1336                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
1337                 break;
1338         }
1339         case IMP_EVENT_ACTIVE:
1340                 CDEBUG(D_INFO, "%s: Reactivating import\n", obd->obd_name);
1341                 /* Clearing obd_no_recov allows us to continue pinging */
1342                 obd->obd_no_recov = 0;
1343                 mgc_notify_active(obd);
1344                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1345                         ptlrpc_pinger_ir_up();
1346                 break;
1347         case IMP_EVENT_OCD:
1348                 break;
1349         case IMP_EVENT_DEACTIVATE:
1350         case IMP_EVENT_ACTIVATE:
1351                 break;
1352         default:
1353                 CERROR("Unknown import event %#x\n", event);
1354                 LBUG();
1355         }
1356         RETURN(rc);
1357 }
1358
1359 enum {
1360         CONFIG_READ_NRPAGES_INIT = 1 << (20 - PAGE_SHIFT),
1361         CONFIG_READ_NRPAGES      = 4
1362 };
1363
1364 static int mgc_apply_recover_logs(struct obd_device *mgc,
1365                                   struct config_llog_data *cld,
1366                                   __u64 max_version,
1367                                   void *data, int datalen, bool mne_swab)
1368 {
1369         struct config_llog_instance *cfg = &cld->cld_cfg;
1370         struct lustre_sb_info       *lsi = s2lsi(cfg->cfg_sb);
1371         struct mgs_nidtbl_entry *entry;
1372         struct lustre_cfg       *lcfg;
1373         struct lustre_cfg_bufs   bufs;
1374         u64   prev_version = 0;
1375         char *inst;
1376         char *buf;
1377         int   bufsz;
1378         int   pos;
1379         int   rc  = 0;
1380         int   off = 0;
1381         ENTRY;
1382
1383         LASSERT(cfg->cfg_instance != NULL);
1384         LASSERT(cfg->cfg_sb == cfg->cfg_instance);
1385
1386         OBD_ALLOC(inst, PAGE_SIZE);
1387         if (inst == NULL)
1388                 RETURN(-ENOMEM);
1389
1390         if (!IS_SERVER(lsi)) {
1391                 pos = snprintf(inst, PAGE_SIZE, "%p", cfg->cfg_instance);
1392                 if (pos >= PAGE_SIZE) {
1393                         OBD_FREE(inst, PAGE_SIZE);
1394                         return -E2BIG;
1395                 }
1396         } else {
1397                 LASSERT(IS_MDT(lsi));
1398                 rc = server_name2svname(lsi->lsi_svname, inst, NULL,
1399                                         PAGE_SIZE);
1400                 if (rc) {
1401                         OBD_FREE(inst, PAGE_SIZE);
1402                         RETURN(-EINVAL);
1403                 }
1404                 pos = strlen(inst);
1405         }
1406
1407         ++pos;
1408         buf   = inst + pos;
1409         bufsz = PAGE_SIZE - pos;
1410
1411         while (datalen > 0) {
1412                 int   entry_len = sizeof(*entry);
1413                 int   is_ost, i;
1414                 struct obd_device *obd;
1415                 char *obdname;
1416                 char *cname;
1417                 char *params;
1418                 char *uuid;
1419
1420                 rc = -EINVAL;
1421                 if (datalen < sizeof(*entry))
1422                         break;
1423
1424                 entry = (typeof(entry))(data + off);
1425
1426                 /* sanity check */
1427                 if (entry->mne_nid_type != 0) /* only support type 0 for ipv4 */
1428                         break;
1429                 if (entry->mne_nid_count == 0) /* at least one nid entry */
1430                         break;
1431                 if (entry->mne_nid_size != sizeof(lnet_nid_t))
1432                         break;
1433
1434                 entry_len += entry->mne_nid_count * entry->mne_nid_size;
1435                 if (datalen < entry_len) /* must have entry_len at least */
1436                         break;
1437
1438                 /* Keep this swab for normal mixed endian handling. LU-1644 */
1439                 if (mne_swab)
1440                         lustre_swab_mgs_nidtbl_entry(entry);
1441                 if (entry->mne_length > PAGE_SIZE) {
1442                         CERROR("MNE too large (%u)\n", entry->mne_length);
1443                         break;
1444                 }
1445
1446                 if (entry->mne_length < entry_len)
1447                         break;
1448
1449                 off     += entry->mne_length;
1450                 datalen -= entry->mne_length;
1451                 if (datalen < 0)
1452                         break;
1453
1454                 if (entry->mne_version > max_version) {
1455                         CERROR("entry index(%lld) is over max_index(%lld)\n",
1456                                entry->mne_version, max_version);
1457                         break;
1458                 }
1459
1460                 if (prev_version >= entry->mne_version) {
1461                         CERROR("index unsorted, prev %lld, now %lld\n",
1462                                prev_version, entry->mne_version);
1463                         break;
1464                 }
1465                 prev_version = entry->mne_version;
1466
1467                 /*
1468                  * Write a string with format "nid::instance" to
1469                  * lustre/<osc|mdc>/<target>-<osc|mdc>-<instance>/import.
1470                  */
1471
1472                 is_ost = entry->mne_type == LDD_F_SV_TYPE_OST;
1473                 memset(buf, 0, bufsz);
1474                 obdname = buf;
1475                 pos = 0;
1476
1477                 /* lustre-OST0001-osc-<instance #> */
1478                 strcpy(obdname, cld->cld_logname);
1479                 cname = strrchr(obdname, '-');
1480                 if (cname == NULL) {
1481                         CERROR("mgc %s: invalid logname %s\n",
1482                                mgc->obd_name, obdname);
1483                         break;
1484                 }
1485
1486                 pos = cname - obdname;
1487                 obdname[pos] = 0;
1488                 pos += sprintf(obdname + pos, "-%s%04x",
1489                                   is_ost ? "OST" : "MDT", entry->mne_index);
1490
1491                 cname = is_ost ? "osc" : "mdc",
1492                 pos += sprintf(obdname + pos, "-%s-%s", cname, inst);
1493                 lustre_cfg_bufs_reset(&bufs, obdname);
1494
1495                 /* find the obd by obdname */
1496                 obd = class_name2obd(obdname);
1497                 if (obd == NULL) {
1498                         CDEBUG(D_INFO, "mgc %s: cannot find obdname %s\n",
1499                                mgc->obd_name, obdname);
1500                         rc = 0;
1501                         /* this is a safe race, when the ost is starting up...*/
1502                         continue;
1503                 }
1504
1505                 /* osc.import = "connection=<Conn UUID>::<target instance>" */
1506                 ++pos;
1507                 params = buf + pos;
1508                 pos += sprintf(params, "%s.import=%s", cname, "connection=");
1509                 uuid = buf + pos;
1510
1511                 down_read(&obd->u.cli.cl_sem);
1512                 if (obd->u.cli.cl_import == NULL) {
1513                         /* client does not connect to the OST yet */
1514                         up_read(&obd->u.cli.cl_sem);
1515                         rc = 0;
1516                         continue;
1517                 }
1518
1519                 /* iterate all nids to find one */
1520                 /* find uuid by nid */
1521                 rc = -ENOENT;
1522                 for (i = 0; i < entry->mne_nid_count; i++) {
1523                         rc = client_import_find_conn(obd->u.cli.cl_import,
1524                                                      entry->u.nids[i],
1525                                                      (struct obd_uuid *)uuid);
1526                         if (rc == 0)
1527                                 break;
1528                 }
1529
1530                 up_read(&obd->u.cli.cl_sem);
1531                 if (rc < 0) {
1532                         CERROR("mgc: cannot find uuid by nid %s\n",
1533                                libcfs_nid2str(entry->u.nids[0]));
1534                         break;
1535                 }
1536
1537                 CDEBUG(D_INFO, "Find uuid %s by nid %s\n",
1538                        uuid, libcfs_nid2str(entry->u.nids[0]));
1539
1540                 pos += strlen(uuid);
1541                 pos += sprintf(buf + pos, "::%u", entry->mne_instance);
1542                 LASSERT(pos < bufsz);
1543
1544                 lustre_cfg_bufs_set_string(&bufs, 1, params);
1545
1546                 lcfg = lustre_cfg_new(LCFG_PARAM, &bufs);
1547                 if (lcfg == NULL) {
1548                         rc = -ENOMEM;
1549                         break;
1550                 }
1551
1552                 CDEBUG(D_INFO, "ir apply logs %lld/%lld for %s -> %s\n",
1553                        prev_version, max_version, obdname, params);
1554
1555                 rc = class_process_config(lcfg);
1556                 lustre_cfg_free(lcfg);
1557                 if (rc)
1558                         CDEBUG(D_INFO, "process config for %s error %d\n",
1559                                obdname, rc);
1560
1561                 /* continue, even one with error */
1562         }
1563
1564         OBD_FREE(inst, PAGE_SIZE);
1565         RETURN(rc);
1566 }
1567
1568 /**
1569  * This function is called if this client was notified for target restarting
1570  * by the MGS. A CONFIG_READ RPC is going to send to fetch recovery or
1571  * nodemap logs.
1572  */
1573 static int mgc_process_recover_nodemap_log(struct obd_device *obd,
1574                                            struct config_llog_data *cld)
1575 {
1576         struct ptlrpc_connection *mgc_conn;
1577         struct ptlrpc_request *req = NULL;
1578         struct config_llog_instance *cfg = &cld->cld_cfg;
1579         struct mgs_config_body *body;
1580         struct mgs_config_res *res;
1581         struct nodemap_config *new_config = NULL;
1582         struct lu_nodemap *recent_nodemap = NULL;
1583         struct ptlrpc_bulk_desc *desc;
1584         struct page **pages = NULL;
1585         __u64 config_read_offset = 0;
1586         __u8 nodemap_cur_pass = 0;
1587         int nrpages = 0;
1588         bool eof = true;
1589         bool mne_swab = false;
1590         int i;
1591         int ealen;
1592         int rc;
1593         ENTRY;
1594
1595         mgc_conn = class_exp2cliimp(cld->cld_mgcexp)->imp_connection;
1596
1597         /* don't need to get local config */
1598         if (cld_is_nodemap(cld) &&
1599             (LNET_NETTYP(LNET_NIDNET(mgc_conn->c_peer.nid)) == LOLND))
1600                 GOTO(out, rc = 0);
1601
1602         /* allocate buffer for bulk transfer.
1603          * if this is the first time for this mgs to read logs,
1604          * CONFIG_READ_NRPAGES_INIT will be used since it will read all logs
1605          * once; otherwise, it only reads increment of logs, this should be
1606          * small and CONFIG_READ_NRPAGES will be used.
1607          */
1608         nrpages = CONFIG_READ_NRPAGES;
1609         if (cfg->cfg_last_idx == 0 || cld_is_nodemap(cld))
1610                 nrpages = CONFIG_READ_NRPAGES_INIT;
1611
1612         OBD_ALLOC(pages, sizeof(*pages) * nrpages);
1613         if (pages == NULL)
1614                 GOTO(out, rc = -ENOMEM);
1615
1616         for (i = 0; i < nrpages; i++) {
1617                 pages[i] = alloc_page(GFP_KERNEL);
1618                 if (pages[i] == NULL)
1619                         GOTO(out, rc = -ENOMEM);
1620         }
1621
1622 again:
1623 #ifdef HAVE_SERVER_SUPPORT
1624         if (cld_is_nodemap(cld) && config_read_offset == 0) {
1625                 new_config = nodemap_config_alloc();
1626                 if (IS_ERR(new_config)) {
1627                         rc = PTR_ERR(new_config);
1628                         new_config = NULL;
1629                         GOTO(out, rc);
1630                 }
1631         }
1632 #endif
1633         LASSERT(cld_is_recover(cld) || cld_is_nodemap(cld));
1634         LASSERT(mutex_is_locked(&cld->cld_lock));
1635         req = ptlrpc_request_alloc(class_exp2cliimp(cld->cld_mgcexp),
1636                                    &RQF_MGS_CONFIG_READ);
1637         if (req == NULL)
1638                 GOTO(out, rc = -ENOMEM);
1639
1640         rc = ptlrpc_request_pack(req, LUSTRE_MGS_VERSION, MGS_CONFIG_READ);
1641         if (rc)
1642                 GOTO(out, rc);
1643
1644         /* pack request */
1645         body = req_capsule_client_get(&req->rq_pill, &RMF_MGS_CONFIG_BODY);
1646         LASSERT(body != NULL);
1647         LASSERT(sizeof(body->mcb_name) > strlen(cld->cld_logname));
1648         if (strlcpy(body->mcb_name, cld->cld_logname, sizeof(body->mcb_name))
1649             >= sizeof(body->mcb_name))
1650                 GOTO(out, rc = -E2BIG);
1651         if (cld_is_nodemap(cld))
1652                 body->mcb_offset = config_read_offset;
1653         else
1654                 body->mcb_offset = cfg->cfg_last_idx + 1;
1655         body->mcb_type   = cld->cld_type;
1656         body->mcb_bits   = PAGE_SHIFT;
1657         body->mcb_units  = nrpages;
1658         body->mcb_nm_cur_pass = nodemap_cur_pass;
1659
1660         /* allocate bulk transfer descriptor */
1661         desc = ptlrpc_prep_bulk_imp(req, nrpages, 1,
1662                                     PTLRPC_BULK_PUT_SINK | PTLRPC_BULK_BUF_KIOV,
1663                                     MGS_BULK_PORTAL,
1664                                     &ptlrpc_bulk_kiov_pin_ops);
1665         if (desc == NULL)
1666                 GOTO(out, rc = -ENOMEM);
1667
1668         for (i = 0; i < nrpages; i++)
1669                 desc->bd_frag_ops->add_kiov_frag(desc, pages[i], 0,
1670                                                  PAGE_SIZE);
1671
1672         ptlrpc_request_set_replen(req);
1673         rc = ptlrpc_queue_wait(req);
1674         if (rc)
1675                 GOTO(out, rc);
1676
1677         res = req_capsule_server_get(&req->rq_pill, &RMF_MGS_CONFIG_RES);
1678         if (!res)
1679                 GOTO(out, rc = -EPROTO);
1680
1681         if (cld_is_nodemap(cld)) {
1682                 config_read_offset = res->mcr_offset;
1683                 eof = config_read_offset == II_END_OFF;
1684                 nodemap_cur_pass = res->mcr_nm_cur_pass;
1685         } else {
1686                 if (res->mcr_size < res->mcr_offset)
1687                         GOTO(out, rc = -EINVAL);
1688
1689                 /* always update the index even though it might have errors with
1690                  * handling the recover logs
1691                  */
1692                 cfg->cfg_last_idx = res->mcr_offset;
1693                 eof = res->mcr_offset == res->mcr_size;
1694
1695                 CDEBUG(D_INFO, "Latest version %lld, more %d.\n",
1696                        res->mcr_offset, eof == false);
1697         }
1698
1699         ealen = sptlrpc_cli_unwrap_bulk_read(req, req->rq_bulk, 0);
1700         if (ealen < 0)
1701                 GOTO(out, rc = ealen);
1702
1703         if (ealen > nrpages << PAGE_SHIFT)
1704                 GOTO(out, rc = -EINVAL);
1705
1706         if (ealen == 0) { /* no logs transferred */
1707 #ifdef HAVE_SERVER_SUPPORT
1708                 /* config changed since first read RPC */
1709                 if (cld_is_nodemap(cld) && config_read_offset == 0) {
1710                         recent_nodemap = NULL;
1711                         nodemap_config_dealloc(new_config);
1712                         new_config = NULL;
1713
1714                         CDEBUG(D_INFO, "nodemap config changed in transit, retrying\n");
1715
1716                         /* setting eof to false, we request config again */
1717                         eof = false;
1718                         GOTO(out, rc = 0);
1719                 }
1720 #endif
1721                 if (!eof)
1722                         rc = -EINVAL;
1723                 GOTO(out, rc);
1724         }
1725
1726         mne_swab = !!ptlrpc_rep_need_swab(req);
1727 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
1728         /* This import flag means the server did an extra swab of IR MNE
1729          * records (fixed in LU-1252), reverse it here if needed. LU-1644 */
1730         if (unlikely(req->rq_import->imp_need_mne_swab))
1731                 mne_swab = !mne_swab;
1732 #endif
1733
1734         /* When a nodemap config is received, we build a new nodemap config,
1735          * with new nodemap structs. We keep track of the most recently added
1736          * nodemap since the config is read ordered by nodemap_id, and so it
1737          * is likely that the next record will be related. Because access to
1738          * the nodemaps is single threaded until the nodemap_config is active,
1739          * we don't need to reference count with recent_nodemap, though
1740          * recent_nodemap should be set to NULL when the nodemap_config
1741          * is either destroyed or set active.
1742          */
1743         for (i = 0; i < nrpages && ealen > 0; i++) {
1744                 int rc2;
1745                 union lu_page   *ptr;
1746
1747                 ptr = kmap(pages[i]);
1748                 if (cld_is_nodemap(cld))
1749                         rc2 = nodemap_process_idx_pages(new_config, ptr,
1750                                                        &recent_nodemap);
1751                 else
1752                         rc2 = mgc_apply_recover_logs(obd, cld, res->mcr_offset,
1753                                                      ptr,
1754                                                      min_t(int, ealen,
1755                                                            PAGE_SIZE),
1756                                                      mne_swab);
1757                 kunmap(pages[i]);
1758                 if (rc2 < 0) {
1759                         CWARN("%s: error processing %s log %s: rc = %d\n",
1760                               obd->obd_name,
1761                               cld_is_nodemap(cld) ? "nodemap" : "recovery",
1762                               cld->cld_logname,
1763                               rc2);
1764                         GOTO(out, rc = rc2);
1765                 }
1766
1767                 ealen -= PAGE_SIZE;
1768         }
1769
1770 out:
1771         if (req) {
1772                 ptlrpc_req_finished(req);
1773                 req = NULL;
1774         }
1775
1776         if (rc == 0 && !eof)
1777                 goto again;
1778
1779 #ifdef HAVE_SERVER_SUPPORT
1780         if (new_config != NULL) {
1781                 /* recent_nodemap cannot be used after set_active/dealloc */
1782                 if (rc == 0)
1783                         nodemap_config_set_active_mgc(new_config);
1784                 else
1785                         nodemap_config_dealloc(new_config);
1786         }
1787 #endif
1788
1789         if (pages) {
1790                 for (i = 0; i < nrpages; i++) {
1791                         if (pages[i] == NULL)
1792                                 break;
1793                         __free_page(pages[i]);
1794                 }
1795                 OBD_FREE(pages, sizeof(*pages) * nrpages);
1796         }
1797         return rc;
1798 }
1799
1800 /* Copy a remote log locally */
1801 static int mgc_llog_local_copy(const struct lu_env *env,
1802                                struct obd_device *obd,
1803                                struct llog_ctxt *rctxt,
1804                                struct llog_ctxt *lctxt, char *logname)
1805 {
1806         char    *temp_log;
1807         int      rc;
1808
1809         ENTRY;
1810
1811         /*
1812          * - copy it to backup using llog_backup()
1813          * - copy remote llog to logname using llog_backup()
1814          * - if failed then move bakup to logname again
1815          */
1816
1817         OBD_ALLOC(temp_log, strlen(logname) + 2);
1818         if (!temp_log)
1819                 RETURN(-ENOMEM);
1820         sprintf(temp_log, "%sT", logname);
1821
1822         /* make a copy of local llog at first */
1823         rc = llog_backup(env, obd, lctxt, lctxt, logname, temp_log);
1824         if (rc < 0 && rc != -ENOENT)
1825                 GOTO(out, rc);
1826         /* copy remote llog to the local copy */
1827         rc = llog_backup(env, obd, rctxt, lctxt, logname, logname);
1828         if (rc == -ENOENT) {
1829                 /* no remote llog, delete local one too */
1830                 llog_erase(env, lctxt, NULL, logname);
1831         } else if (rc < 0) {
1832                 /* error during backup, get local one back from the copy */
1833                 llog_backup(env, obd, lctxt, lctxt, temp_log, logname);
1834 out:
1835                 CERROR("%s: failed to copy remote log %s: rc = %d\n",
1836                        obd->obd_name, logname, rc);
1837         }
1838         llog_erase(env, lctxt, NULL, temp_log);
1839         OBD_FREE(temp_log, strlen(logname) + 2);
1840         return rc;
1841 }
1842
1843 /* local_only means it cannot get remote llogs */
1844 static int mgc_process_cfg_log(struct obd_device *mgc,
1845                                struct config_llog_data *cld, int local_only)
1846 {
1847         struct llog_ctxt        *ctxt, *lctxt = NULL;
1848         struct client_obd       *cli = &mgc->u.cli;
1849         struct lustre_sb_info   *lsi = NULL;
1850         int                      rc = 0;
1851         bool                     sptlrpc_started = false;
1852         struct lu_env           *env;
1853
1854         ENTRY;
1855
1856         LASSERT(cld);
1857         LASSERT(mutex_is_locked(&cld->cld_lock));
1858
1859         /*
1860          * local copy of sptlrpc log is controlled elsewhere, don't try to
1861          * read it up here.
1862          */
1863         if (cld_is_sptlrpc(cld) && local_only)
1864                 RETURN(0);
1865
1866         if (cld->cld_cfg.cfg_sb)
1867                 lsi = s2lsi(cld->cld_cfg.cfg_sb);
1868
1869         OBD_ALLOC_PTR(env);
1870         if (env == NULL)
1871                 RETURN(-ENOMEM);
1872
1873         rc = lu_env_init(env, LCT_MG_THREAD);
1874         if (rc)
1875                 GOTO(out_free, rc);
1876
1877         ctxt = llog_get_context(mgc, LLOG_CONFIG_REPL_CTXT);
1878         LASSERT(ctxt);
1879
1880         lctxt = llog_get_context(mgc, LLOG_CONFIG_ORIG_CTXT);
1881
1882         /* Copy the setup log locally if we can. Don't mess around if we're
1883          * running an MGS though (logs are already local). */
1884         if (lctxt && lsi && IS_SERVER(lsi) && !IS_MGS(lsi) &&
1885             cli->cl_mgc_configs_dir != NULL &&
1886             lu2dt_dev(cli->cl_mgc_configs_dir->do_lu.lo_dev) ==
1887             lsi->lsi_dt_dev) {
1888                 if (!local_only)
1889                         /* Only try to copy log if we have the lock. */
1890                         rc = mgc_llog_local_copy(env, mgc, ctxt, lctxt,
1891                                                  cld->cld_logname);
1892                 if (local_only || rc) {
1893                         if (strcmp(cld->cld_logname, PARAMS_FILENAME) != 0 &&
1894                             llog_is_empty(env, lctxt, cld->cld_logname)) {
1895                                 LCONSOLE_ERROR_MSG(0x13a, "Failed to get MGS "
1896                                                    "log %s and no local copy."
1897                                                    "\n", cld->cld_logname);
1898                                 GOTO(out_pop, rc = -ENOENT);
1899                         }
1900                         CDEBUG(D_MGC, "Failed to get MGS log %s, using local "
1901                                "copy for now, will try to update later.\n",
1902                                cld->cld_logname);
1903                         rc = 0;
1904                 }
1905                 /* Now, whether we copied or not, start using the local llog.
1906                  * If we failed to copy, we'll start using whatever the old
1907                  * log has. */
1908                 llog_ctxt_put(ctxt);
1909                 ctxt = lctxt;
1910                 lctxt = NULL;
1911         } else {
1912                 if (local_only) /* no local log at client side */
1913                         GOTO(out_pop, rc = -EIO);
1914         }
1915
1916         if (cld_is_sptlrpc(cld)) {
1917                 sptlrpc_conf_log_update_begin(cld->cld_logname);
1918                 sptlrpc_started = true;
1919         }
1920
1921         /* logname and instance info should be the same, so use our
1922          * copy of the instance for the update.  The cfg_last_idx will
1923          * be updated here. */
1924         rc = class_config_parse_llog(env, ctxt, cld->cld_logname,
1925                                      &cld->cld_cfg);
1926         EXIT;
1927
1928 out_pop:
1929         __llog_ctxt_put(env, ctxt);
1930         if (lctxt)
1931                 __llog_ctxt_put(env, lctxt);
1932
1933         /*
1934          * update settings on existing OBDs. doing it inside
1935          * of llog_process_lock so no device is attaching/detaching
1936          * in parallel.
1937          * the logname must be <fsname>-sptlrpc
1938          */
1939         if (sptlrpc_started) {
1940                 LASSERT(cld_is_sptlrpc(cld));
1941                 sptlrpc_conf_log_update_end(cld->cld_logname);
1942                 class_notify_sptlrpc_conf(cld->cld_logname,
1943                                           strlen(cld->cld_logname) -
1944                                           strlen("-sptlrpc"));
1945         }
1946
1947         lu_env_fini(env);
1948 out_free:
1949         OBD_FREE_PTR(env);
1950         return rc;
1951 }
1952
1953 static bool mgc_import_in_recovery(struct obd_import *imp)
1954 {
1955         bool in_recovery = true;
1956
1957         spin_lock(&imp->imp_lock);
1958         if (imp->imp_state == LUSTRE_IMP_FULL ||
1959             imp->imp_state == LUSTRE_IMP_CLOSED)
1960                 in_recovery = false;
1961         spin_unlock(&imp->imp_lock);
1962
1963         return in_recovery;
1964 }
1965
1966 /**
1967  * Get a configuration log from the MGS and process it.
1968  *
1969  * This function is called for both clients and servers to process the
1970  * configuration log from the MGS.  The MGC enqueues a DLM lock on the
1971  * log from the MGS, and if the lock gets revoked the MGC will be notified
1972  * by the lock cancellation callback that the config log has changed,
1973  * and will enqueue another MGS lock on it, and then continue processing
1974  * the new additions to the end of the log.
1975  *
1976  * Since the MGC import is not replayable, if the import is being evicted
1977  * (rcl == -ESHUTDOWN, \see ptlrpc_import_delay_req()), retry to process
1978  * the log until recovery is finished or the import is closed.
1979  *
1980  * Make a local copy of the log before parsing it if appropriate (non-MGS
1981  * server) so that the server can start even when the MGS is down.
1982  *
1983  * There shouldn't be multiple processes running process_log at once --
1984  * sounds like badness.  It actually might be fine, as long as they're not
1985  * trying to update from the same log simultaneously, in which case we
1986  * should use a per-log semaphore instead of cld_lock.
1987  *
1988  * \param[in] mgc       MGC device by which to fetch the configuration log
1989  * \param[in] cld       log processing state (stored in lock callback data)
1990  *
1991  * \retval              0 on success
1992  * \retval              negative errno on failure
1993  */
1994 int mgc_process_log(struct obd_device *mgc, struct config_llog_data *cld)
1995 {
1996         struct lustre_handle lockh = { 0 };
1997         __u64 flags = LDLM_FL_NO_LRU;
1998         int rc = 0, rcl;
1999         bool retry = false;
2000         ENTRY;
2001
2002         LASSERT(cld != NULL);
2003
2004         /* I don't want multiple processes running process_log at once --
2005            sounds like badness.  It actually might be fine, as long as
2006            we're not trying to update from the same log
2007            simultaneously (in which case we should use a per-log sem.) */
2008 restart:
2009         mutex_lock(&cld->cld_lock);
2010         if (cld->cld_stopping) {
2011                 mutex_unlock(&cld->cld_lock);
2012                 RETURN(0);
2013         }
2014
2015         OBD_FAIL_TIMEOUT(OBD_FAIL_MGC_PAUSE_PROCESS_LOG, 20);
2016
2017         CDEBUG(D_MGC, "Process log %s:%p from %d\n", cld->cld_logname,
2018                cld->cld_cfg.cfg_instance, cld->cld_cfg.cfg_last_idx + 1);
2019
2020         /* Get the cfg lock on the llog */
2021         rcl = mgc_enqueue(mgc->u.cli.cl_mgc_mgsexp, LDLM_PLAIN, NULL,
2022                           LCK_CR, &flags, NULL, NULL, NULL,
2023                           cld, 0, NULL, &lockh);
2024         if (rcl == 0) {
2025                 /* Get the cld, it will be released in mgc_blocking_ast. */
2026                 config_log_get(cld);
2027                 rc = ldlm_lock_set_data(&lockh, (void *)cld);
2028                 LASSERT(rc == 0);
2029         } else {
2030                 CDEBUG(D_MGC, "Can't get cfg lock: %d\n", rcl);
2031
2032                 if (rcl == -ESHUTDOWN &&
2033                     atomic_read(&mgc->u.cli.cl_mgc_refcount) > 0 && !retry) {
2034                         struct obd_import *imp;
2035                         struct l_wait_info lwi;
2036                         int secs = cfs_time_seconds(obd_timeout);
2037
2038                         mutex_unlock(&cld->cld_lock);
2039                         imp = class_exp2cliimp(mgc->u.cli.cl_mgc_mgsexp);
2040
2041                         /* Let's force the pinger, and wait the import to be
2042                          * connected, note: since mgc import is non-replayable,
2043                          * and even the import state is disconnected, it does
2044                          * not mean the "recovery" is stopped, so we will keep
2045                          * waitting until timeout or the import state is
2046                          * FULL or closed */
2047                         ptlrpc_pinger_force(imp);
2048
2049                         lwi = LWI_TIMEOUT(secs, NULL, NULL);
2050                         l_wait_event(imp->imp_recovery_waitq,
2051                                      !mgc_import_in_recovery(imp), &lwi);
2052
2053                         if (imp->imp_state == LUSTRE_IMP_FULL) {
2054                                 retry = true;
2055                                 goto restart;
2056                         } else {
2057                                 mutex_lock(&cld->cld_lock);
2058                                 spin_lock(&config_list_lock);
2059                                 cld->cld_lostlock = 1;
2060                                 spin_unlock(&config_list_lock);
2061                         }
2062                 } else {
2063                         /* mark cld_lostlock so that it will requeue
2064                          * after MGC becomes available. */
2065                         spin_lock(&config_list_lock);
2066                         cld->cld_lostlock = 1;
2067                         spin_unlock(&config_list_lock);
2068                 }
2069         }
2070
2071         if (cld_is_recover(cld) || cld_is_nodemap(cld)) {
2072                 if (!rcl)
2073                         rc = mgc_process_recover_nodemap_log(mgc, cld);
2074                 else if (cld_is_nodemap(cld))
2075                         rc = rcl;
2076
2077                 if (cld_is_recover(cld) && rc) {
2078                         if (!rcl) {
2079                                 CERROR("%s: recover log %s failed, not fatal: rc = %d\n",
2080                                        mgc->obd_name, cld->cld_logname, rc);
2081                                 spin_lock(&config_list_lock);
2082                                 cld->cld_lostlock = 1;
2083                                 spin_unlock(&config_list_lock);
2084                         }
2085                         rc = 0; /* this is not a fatal error for recover log */
2086                 }
2087         } else {
2088                 rc = mgc_process_cfg_log(mgc, cld, rcl != 0);
2089         }
2090
2091         CDEBUG(D_MGC, "%s: configuration from log '%s' %sed (%d).\n",
2092                mgc->obd_name, cld->cld_logname, rc ? "fail" : "succeed", rc);
2093
2094         mutex_unlock(&cld->cld_lock);
2095
2096         /* Now drop the lock so MGS can revoke it */
2097         if (!rcl) {
2098                 rcl = mgc_cancel(mgc->u.cli.cl_mgc_mgsexp, LCK_CR, &lockh);
2099                 if (rcl)
2100                         CERROR("Can't drop cfg lock: %d\n", rcl);
2101         }
2102
2103         RETURN(rc);
2104 }
2105
2106
2107 /** Called from lustre_process_log.
2108  * LCFG_LOG_START gets the config log from the MGS, processes it to start
2109  * any services, and adds it to the list logs to watch (follow).
2110  */
2111 static int mgc_process_config(struct obd_device *obd, size_t len, void *buf)
2112 {
2113         struct lustre_cfg *lcfg = buf;
2114         struct config_llog_instance *cfg = NULL;
2115         char *logname;
2116         int rc = 0;
2117         ENTRY;
2118
2119         switch(lcfg->lcfg_command) {
2120         case LCFG_LOV_ADD_OBD: {
2121                 /* Overloading this cfg command: register a new target */
2122                 struct mgs_target_info *mti;
2123
2124                 if (LUSTRE_CFG_BUFLEN(lcfg, 1) !=
2125                     sizeof(struct mgs_target_info))
2126                         GOTO(out, rc = -EINVAL);
2127
2128                 mti = (struct mgs_target_info *)lustre_cfg_buf(lcfg, 1);
2129                 CDEBUG(D_MGC, "add_target %s %#x\n",
2130                        mti->mti_svname, mti->mti_flags);
2131                 rc = mgc_target_register(obd->u.cli.cl_mgc_mgsexp, mti);
2132                 break;
2133         }
2134         case LCFG_LOV_DEL_OBD:
2135                 /* Unregister has no meaning at the moment. */
2136                 CERROR("lov_del_obd unimplemented\n");
2137                 rc = -ENOSYS;
2138                 break;
2139         case LCFG_SPTLRPC_CONF: {
2140                 rc = sptlrpc_process_config(lcfg);
2141                 break;
2142         }
2143         case LCFG_LOG_START: {
2144                 struct config_llog_data *cld;
2145                 struct super_block *sb;
2146
2147                 logname = lustre_cfg_string(lcfg, 1);
2148                 cfg = (struct config_llog_instance *)lustre_cfg_buf(lcfg, 2);
2149                 sb = *(struct super_block **)lustre_cfg_buf(lcfg, 3);
2150
2151                 CDEBUG(D_MGC, "parse_log %s from %d\n", logname,
2152                        cfg->cfg_last_idx);
2153
2154                 /* We're only called through here on the initial mount */
2155                 cld = config_log_add(obd, logname, cfg, sb);
2156                 if (IS_ERR(cld)) {
2157                         rc = PTR_ERR(cld);
2158                         break;
2159                 }
2160
2161                 /* COMPAT_146 */
2162                 /* FIXME only set this for old logs!  Right now this forces
2163                    us to always skip the "inside markers" check */
2164                 cld->cld_cfg.cfg_flags |= CFG_F_COMPAT146;
2165
2166                 rc = mgc_process_log(obd, cld);
2167                 if (rc == 0 && cld->cld_recover != NULL) {
2168                         if (OCD_HAS_FLAG(&obd->u.cli.cl_import->
2169                                          imp_connect_data, IMP_RECOV)) {
2170                                 rc = mgc_process_log(obd, cld->cld_recover);
2171                         } else {
2172                                 struct config_llog_data *cir;
2173
2174                                 mutex_lock(&cld->cld_lock);
2175                                 cir = cld->cld_recover;
2176                                 cld->cld_recover = NULL;
2177                                 mutex_unlock(&cld->cld_lock);
2178                                 config_log_put(cir);
2179                         }
2180
2181                         if (rc)
2182                                 CERROR("Cannot process recover llog %d\n", rc);
2183                 }
2184
2185                 if (rc == 0 && cld->cld_params != NULL) {
2186                         rc = mgc_process_log(obd, cld->cld_params);
2187                         if (rc == -ENOENT) {
2188                                 CDEBUG(D_MGC, "There is no params "
2189                                               "config file yet\n");
2190                                 rc = 0;
2191                         }
2192                         /* params log is optional */
2193                         if (rc)
2194                                 CERROR("%s: can't process params llog: rc = %d\n",
2195                                        obd->obd_name, rc);
2196                 }
2197
2198                 break;
2199         }
2200         case LCFG_LOG_END: {
2201                 logname = lustre_cfg_string(lcfg, 1);
2202
2203                 if (lcfg->lcfg_bufcount >= 2)
2204                         cfg = (struct config_llog_instance *)lustre_cfg_buf(
2205                                 lcfg, 2);
2206                 rc = config_log_end(logname, cfg);
2207                 break;
2208         }
2209         default: {
2210                 CERROR("Unknown command: %d\n", lcfg->lcfg_command);
2211                 GOTO(out, rc = -EINVAL);
2212
2213         }
2214         }
2215 out:
2216         RETURN(rc);
2217 }
2218
2219 static struct obd_ops mgc_obd_ops = {
2220         .o_owner        = THIS_MODULE,
2221         .o_setup        = mgc_setup,
2222         .o_precleanup   = mgc_precleanup,
2223         .o_cleanup      = mgc_cleanup,
2224         .o_add_conn     = client_import_add_conn,
2225         .o_del_conn     = client_import_del_conn,
2226         .o_connect      = client_connect_import,
2227         .o_disconnect   = client_disconnect_export,
2228         .o_set_info_async = mgc_set_info_async,
2229         .o_get_info       = mgc_get_info,
2230         .o_import_event = mgc_import_event,
2231         .o_process_config = mgc_process_config,
2232 };
2233
2234 static int __init mgc_init(void)
2235 {
2236         return class_register_type(&mgc_obd_ops, NULL, true, NULL,
2237                                    LUSTRE_MGC_NAME, NULL);
2238 }
2239
2240 static void __exit mgc_exit(void)
2241 {
2242         class_unregister_type(LUSTRE_MGC_NAME);
2243 }
2244
2245 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
2246 MODULE_DESCRIPTION("Lustre Management Client");
2247 MODULE_VERSION(LUSTRE_VERSION_STRING);
2248 MODULE_LICENSE("GPL");
2249
2250 module_init(mgc_init);
2251 module_exit(mgc_exit);