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